使用非常基本的Rails 4.1的API调用HTTParty [英] Very Basic Rails 4.1 API Call using HTTParty

查看:194
本文介绍了使用非常基本的Rails 4.1的API调用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数据库中的用户。任何人都可以点我在正确的方向或与我分享一些code?

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响应数据既包括标题和实际内容的响应对象(。体)。正文包含只要你喜欢,你可以处理的数据字符串。在这种情况下,我们解析字符串作为JSON成一个Ruby的哈希值。如果您需要自定义HTTP请求到API,你可以看到在 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.

这篇关于使用非常基本的Rails 4.1的API调用HTTParty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆