Very Basic Rails 4.1 API Call using HTTParty

此生再无相见时 提交于 2019-12-06 02:11:57

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26897592/very-basic-rails-4-1-api-call-using-httparty

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