Very simple Rails 4.1 API call using HTTParty

Relatively new to Rails. I am trying to call an API and it should return a unique URL to me. I have HTTParty in my application. I created a UniqueNumber controller and I read some HTTParty tutorials as much as I want, but maybe I just lost a little and really don't know what to do.

Basically, all I need to do is call the API, return the URL, and then paste that URL into the database for the user. Can someone point me in the right direction or share the code with me?

+5
source share
1 answer

Suppose the API is in JSON format and returns data as follows:

{"url": "http://example.com/unique-url"} 

In order for everything to be well and well structured, the API logic must belong to it in its 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 this 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 

Basically, HTTParty returns a response object containing 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 wish. In this case, we parse the string as JSON into a Ruby hash file. If you need to configure the HTTP request for the API, you can see all the parameters in the HTTParty documentation .

+7
source

Source: https://habr.com/ru/post/1206749/


All Articles