Use gem's HTTP Client when connecting to an external API with rails. This time, as an example, I will connect to Qiita's API and get the article list.
Gemfile
gem 'httpclient'
Terminal
$ bundle install
The endpoint is / api / qiita
.
routes.rb
Rails.application.routes.draw do
namespace :api do
get '/qiita' to: 'qiita#index'
end
end
First, the most basic form. (Get request without header or query)
controllers/api/qiita_controller.rb
class Api::QiitaController < ApplicationController
#Call HTTPClient
require 'httpclient'
def index
url = "https://qiita.com/api/v2/items" #Set URL
client = HTTPClient.new #Create an instance
response = client.get(url) #Get request
render json: JSON.parse(response.body) #Parse and display the result in json
end
end
When you access http: // localhost: 3000 / api / qiita, a list of data will be returned in json like this. It's very hard to see because it's not shaped.
Next is the case of specifying header or query.
controllers/api/qiita_controller.rb
class Api::QiitaController < ApplicationController
#Call HTTPClient
require 'httpclient'
def index
url = "https://qiita.com/api/v2/items"
header = { Authorization: "Bearer xxxxx" } #Example)In the header"Bearer xxxxx"Grant
query = { page: 1, per_page: 20 } #Example)1st page, query to increase the number of data acquisitions per page to 20
client = HTTPClient.new
response = client.get(url, header: header, query: query) #Specify header and query
render json: JSON.parse(response.body)
end
end
This time, I explained only get request, but HTTP Client can send other requests such as Post, so please check it.
For details of Qiita API, refer to the following. Qiita API v2 documentation - Qiita:Developer Overview of Qiita API v2 (unofficial)
Recommended Posts