Rails 使用 API [英] Rails working with API

查看:57
本文介绍了Rails 使用 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 API 的初学者.我正在尝试使用 Forecast API.我不想使用它的官方包装,因为首先我喜欢学习和学习.

I am beginner in working with API. I'm trying to work with the Forecast API. I don't want to use its official wrapper, because first I like to study and learn.

class Forecast
  include HTTParty

  base_uri "api.forecast.io/forecast/#{@api_key}/#{@latitude},#{@longitude}"

  def initialize(api_key,latitude,longitude)
     self.api_key = api_key
     self.latitude = latitude
     self.longitude = longitude
  end


end

现在初始化之后的下一步应该是什么.我尝试使用 httparty gem 示例来理解,但无法弄清楚到底要做什么.

Now what should be the next step after initialization. I've tried to understand using the httparty gem examples, but cant figure out what exactly to do.

你能帮我修一下吗?使用 API 指向相关资源?

Could you help me to fix it & point related resources with APIs?

推荐答案

我在使用 API 时不使用 httparty gem,而是使用 typhoeus gem 允许发出并行 http 请求并因此启用并发,但我相信如果您使用 httparty,下面的示例也将起作用.我将使用一个简单的示例来展示我如何使用 API.假设您正在尝试与 JSON api 服务通信以获取产品列表.

I do not use httparty gem when working with APIs instead i use typhoeus gem which allow making parallel http requests and therefore enable concurrency but i believe the example below will also work if you use httparty. I am going to use a simple example to show how i work with APIs. Let's say you are trying to communicate with a JSON api service to fetch a list of products.

服务端点的url为http://path/to/products.json

在你的应用程序中,你可以有一个 products_controller.rb 和一个 index 动作,如下所示:

in your application, you can have a products_controller.rb with an index action that looks like this:

class ProductsController < ApplicationController
  def index
   # make a http request to the api to fetch the products in json format
    hydra = Typhoeus::Hydra.hydra
    get_products = Typhoeus::Request.new('http://path/to/products.json')
    get_products.on_complete do |response|
      products = MultipleProducts.from_json(response.body)
      @products = products.products
    end
    hydra.queue get_products
    hydra.run
  end
end

假设对 http://path/to/products.json 的 http 请求返回以下 json

Let's say that the http request to http://path/to/products.json returns the following json

{"products" [{"id": 1,
  "name": "First product",
  "description": "Description",
  "price": "25.99"}, {"id": 2,
  "name": "Second product",
  "description": "Description",
  "price": "5.99"}]

这个 json 可以包含在一个类中,名称类似于 multiple_products.rb 看起来像这样:

This json can be wrapped in a class with a name like, multiple_products.rb Which looks like this:

class MultipleProducts
  attr_reader :products 
  def initialize(attributes)
    @products = attributes[:products]
  end
  def self.from_json(json_string)
    parsed = JSON.parse(json_string)
    products = parsed['products'].map do |product|
      Product.new(product)
    end
    new(products: products)
  end
end

然后您可以使用 ActiveModel 来创建这样的产品模型:

You can then use ActiveModel to create a product model like this:

class Product
  include ActiveModel::Serializers::JSON
  include ActiveModel::Validations
  ATTRIBUTES =  [:id, :name, :description, :price]
  attr_accessor *ATTRIBUTES
  validates_presence_of :id, :name, :price

  def initialize(attributes = {})
    self.attributes = attributes
  end

  def attributes
    ATTRIBUTES.inject(ActiveSupport::HashWithIndifferentAccess.new) do |result, key|
      result[key] = read_attribute_for_validation(key)
      result
    end
  end

 def attributes= (attrs)
   attrs.each_pair {|k, v| send("#{k}=", v)}
 end

 def read_attribute_for_validation(key)
   send(key)
 end
end

在您的 app/views/products/index.html 中,您可以:

In your app/views/products/index.html, you can have:

<h1>Products Listing</h1>
 <ul>
   <% @products.each do |product| %>
     <li>Name: <%= product.name %> Price: <%= product.price %> </li>
   <% end %>
 </ul>

这将列出从 api 获取的所有产品.这只是一个简单的示例,在使用 API 时涉及更多内容.我建议您阅读 使用 Ruby 和 Rails 的面向服务的设计 了解更多详情.

This will list all the products fetched from the api. This is just but a simple example and there is much more involved when working with APIs. I would recommend you read Service-Oriented Design with Ruby and Rails for more details.

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

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