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
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.
Could you help me to fix it & point related resources with APIs?
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.
The url of the service endpoint is
http://path/to/products.json
in your application, you can have a
products_controller.rb
with anindex
action that looks like this:Let's say that the http request to
http://path/to/products.json
returns the following jsonThis json can be wrapped in a class with a name like,
multiple_products.rb
Which looks like this:You can then use ActiveModel to create a product model like this:
In your
app/views/products/index.html
, you can have: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.