5

Relatively new to Rails. I am trying to call an API and it's supposed to return a unique URL to me. I have HTTParty bundled on my app. I have created a UniqueNumber controller and I have read through several HTTParty guides as far as what I want but maybe I'm just a bit lost and really have no idea what to do.

Basically, all I need to do is call the API, get the URL it returns, then insert that URL into the database for a user. Can anyone point me in the right direction or share some code with me?

Flip
  • 6,233
  • 7
  • 46
  • 75
keith
  • 651
  • 2
  • 6
  • 10
  • Could you elaborate a bit on the API part? E.g is it a JSON based API? What HTTP method do you need to use to get the data (GET/POST etc)? Do you need to send any data with the API call? etc. – Pete Nov 12 '14 at 22:23
  • I'm not sure on the JSON part, I think so? I'll send an email asking. I should be able to just send a GET reqeust. I do not need to send any data with the API call. Each request should spit a new unique url back – keith Nov 12 '14 at 22:33

1 Answers1

12

Let's assume the API is in a JSON format and returns the data like so:

{"url": "http://example.com/unique-url"}

To keep things tidy and well structured, the API logic should belong in it's own class:

# lib/url_api.rb
require 'httparty'

class UrlApi
  API_URL = 'http://example.com/create'

  def unique_url
    response = HTTParty.get(API_URL)
    # TODO more error checking (500 error, etc)
    json = JSON.parse(response.body)
    json['url']
  end
end

Then call that class in the controller:

require 'url_api'

class UniqueNumberController < ApplicationController
  def create
    api = UrlApi.new()
    url = api.unique_url

    @user = # Code to retrieve User
    @user.update_attribute :url, url
    # etc
  end
end

Basically HTTParty returns a response object that contains the HTTP response data which includes both the headers and the actual content (.body). The body contains a string of data that you can process as you like. In this case, we're parsing the string as JSON into a Ruby hash. If you need to customise the HTTP request to the API you can see all the options in the HTTParty documentation.

Pete
  • 2,196
  • 1
  • 17
  • 25
  • After messing with it for a bit of time now @peter I'm not sure how to make it actually run the code? What I would like to do, is when a user hits a submit button when they signup, it automatically requests the API URL and pushes it into the URL field in the database. Does that make sense? I am currently using devise in my app to handle user signups etc. – keith Nov 13 '14 at 00:00