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)
Then call this class in the controller:
require 'url_api' class UniqueNumberController < ApplicationController def create api = UrlApi.new() url = api.unique_url @user =
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 .
source share