Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very Basic Rails 4.1 API Call using HTTParty

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?

like image 414
keith Avatar asked Nov 12 '14 22:11

keith


1 Answers

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.

like image 110
Pete Avatar answered Nov 15 '22 08:11

Pete