3
2

More than 1 year has passed since last update.

【Rails】外部APIを使う方法

Posted at

初めに

Railsで外部 API を利用するには、gem やNET::HTTPを使う方法がありますが、今回はRubyにあるNET::HTTPを使います。

HTTP リクエストの仕方

以下は、Net::HTTPを利用してPokeAPIからポケモンのデータを取得する例です。
https://pokeapi.co/api/v2/pokemon/:idに対して、GETメソッドでリクエストを送信します。
そして、json データを受け取ります。

api_controller.rb
require 'net/http'

class ApiController < ApplicationController
  def show
    pokemon_id = params[:id]
    uri = URI.parse('https://pokeapi.co')
    # URI.parseは、URIオブジェクトを生成するメソッドです。
    http_client= Net::HTTP.new(uri.host,uri.port)
    # HTTPクライアントを生成し、引数にホスト名とポート番号を指定しています。
    get_request = Net::HTTP::Get.new("/api/v2/pokemon/#{pokemon_id}", 'Content-Type' => 'application/json')
    # Net::HTTP::Getは、HTTPのGETリクエストを表すクラスです。
    # 引数にリクエストするpathとヘッダーを指定しています。
    http_client.use_ssl = true
    # httpsで通信をする場合はuse_sslをtrueにする必要がある
    response = http_client.request(get_request)
    # requestメソッドの引数にNet:HTTP:Responseオブジェクトをあたえます。
    # responseには、HTTPレスポンスが格納されている
    @data = JSON.parse(response.body)
    # @responseはJSON形式になっているので、JSON.parseでHashに変換する必要がある
  end
end

参考

3
2
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
3
2