Very Basic Rails 4.1 API Call using HTTParty

依然范特西╮ 提交于 2019-12-04 07:25:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!