LoginSignup
7
11

More than 3 years have passed since last update.

【rails】HTTPClientを用いて外部APIに接続する方法(QiitaAPIに接続してみた)

Last updated at Posted at 2020-09-27

はじめに

railsで外部APIに接続する際にはgemのHTTPClientを使用します。
今回は例としてQiitaのAPIに接続して、記事一覧を取得(get)してみます。

HTTPClientをインストール

Gemfile
gem 'httpclient'
ターミナル
$ bundle install

route.rbに追加

エンドポイントは /api/qiitaとします。

routes.rb
Rails.application.routes.draw do 
  namespace :api do 
    get '/qiita' to: 'qiita#index'
  end
end

QiitaAPIに接続する(Controller)

まず、最も基本的な形です。(headerやqueryを指定しないgetリクエスト)

controllers/api/qiita_controller.rb
class Api::QiitaController < ApplicationController
  # HTTPClientを呼び出す
  require 'httpclient'

  def index
    url = "https://qiita.com/api/v2/items"  # URLを設定
    client = HTTPClient.new                 # インスタンスを生成
    response = client.get(url)              # Getリクエスト
    render json: JSON.parse(response.body)  # 結果をjsonにパースして表示
  end
end

http://localhost:3000/api/qiita にアクセスするとこんな感じでデータの一覧がjsonで返ってきます。
整形していないので非常に見づらいですね。

スクリーンショット 2020-09-27 13.39.51.png

次にheaderやqueryを指定する場合です。

controllers/api/qiita_controller.rb
class Api::QiitaController < ApplicationController
  # HTTPClientを呼び出す
  require 'httpclient'

  def index
    url = "https://qiita.com/api/v2/items"
    header = { Authorization: "Bearer xxxxx" } # 例) ヘッダーに"Bearer xxxxx"を付与
    query = { page: 1, per_page: 20 }          # 例) 1ページ目、1ページごとのデータ取得数を20件にするquery       
    client = HTTPClient.new
    response = client.get(url, header: header, query: query) #headerとqueryを指定
    render json: JSON.parse(response.body)
  end
end

終わりに

今回はgetリクエストのみだけの説明にしましたが、HTTPClientではPostなど他のリクエストも送れるので調べてみてください。

QiitaのAPIの詳細は下記を参照しました。
Qiita API v2 documentation - Qiita:Developer
Qiita API v2 の概要(非公式)

7
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
11