Rails使用API
我是初学者,正在使用API。 我正在尝试使用Forecast API 。 我不想使用它的官方包装 ,因为我首先喜欢学习和学习。
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示例,但无法弄清楚究竟要做什么。
你能帮我解决一下并用API指出相关资源吗?
我在使用API时不使用httparty gem而是使用typhoeus gem ,它允许并行的http请求,因此启用了并发性,但我相信如果您使用httparty,下面的示例也会起作用。 我将使用一个简单的例子来说明我如何使用API。 假设您正在尝试与JSON api服务进行通信以获取产品列表。
服务端点的URL是http://path/to/products.json
在您的应用程序中,您可以使用带有index
操作的products_controller.rb
,如下所示:
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
{"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
类中,如下所示:
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创建如下的产品模型:
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
,您可以拥有:
Products Listing
<% @products.each do |product| %> - Name: <%= product.name %> Price: <%= product.price %>
<% end %>
这将列出从api获取的所有产品。 这只是一个简单的例子,在使用API时会涉及更多内容。 我建议您阅读使用Ruby和Rails的面向服务的设计以获取更多详细信息。