使用 HTTParty 的非常基本的 Rails 4.1 API 调用 [英] Very Basic Rails 4.1 API Call using HTTParty
问题描述
Rails 相对较新.我正在尝试调用一个 API,它应该向我返回一个唯一的 URL.我的应用程序中捆绑了 HTTParty.我已经创建了一个 UniqueNumber 控制器,并且我已经阅读了几个 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.
基本上,我需要做的就是调用 API,获取它返回的 URL,然后将该 URL 插入到用户的数据库中.谁能指出我正确的方向或与我分享一些代码?
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?
推荐答案
让我们假设 API 是 JSON 格式并像这样返回数据:
Let's assume the API is in a JSON format and returns the data like so:
{"url": "http://example.com/unique-url"}
为了保持整洁和结构良好,API 逻辑应该属于它自己的类:
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
基本上 HTTParty 返回一个响应对象,其中包含 HTTP 响应数据,其中包括标头和实际内容 (.body
).正文包含一串数据,您可以随意处理.在本例中,我们将字符串作为 JSON 解析为 Ruby 哈希.如果您需要自定义对 API 的 HTTP 请求,您可以在 HTTParty 文档中查看所有选项.
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.
这篇关于使用 HTTParty 的非常基本的 Rails 4.1 API 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!