LoginSignup
30
36

More than 5 years have passed since last update.

Rails4:自力でControllerからAPIを叩くシンプルな実装

Posted at

やりたい事

HTMLのform(form_for)から特定のmodelデータ(ここではUser)を受信して追加(create)する時に、業務管理のAPでプロセスをキックさせたい。
そこで業務管理のAPで提供しているAPIに、データsave後任意のパラメータを設定したHTTPリクエスト(GET)を送る実装をしてみた。
ControllerからAPI叩く時には似たような流れで応用出来ると思います。
※なお、今回はレスポンスのチェックなどは行いません。

Modelの実装

Modelに紐づく値をGETメソッドのパラメータとして渡したい(特定のURLでのHTTPリクエストを行いたい)ので、ModelでURLの組み立てを行う。
データ名は各種API仕様書を参考のこと。

app/models/user.rb
class User < ActiveRecord::Base
  BASE_API_URL = "https://example.com".freeze

  # ...

  # API実行用のURLを返却
  def api_url
    h = {
      "data[0]" =>      name,
      "data[1]" =>      tel,
      "data[2]" =>      email.downcase
    }
    BASE_API_URL + "?" + h.map{|k,v| URI.encode(k.to_s) + "=" + URI.encode(v.to_s)}.join("&")
  end
end
  • ハッシュでパラメータ名と該当のする値を作成
  • 各データをURLエンコードした文字列を、ハッシュのmap等で連結(&がセパレータ)

URL例:
https://example.com?data[0]=nameの値&data[1]=telの値&data[2]=emailの値

Controllerの実装

ModelでURLを返却するメソッドを実装したので、
Controllerでそれを呼んで、Net::HTTPでgetリクエストを飛ばします。
(require 'net/http'の記述が必要)

app/controllers/users_controller.rb
class UsersController < ApplicationController
  require 'net/http'

  # ...

  def create
    @user = User.new(user_params)
    if @user.save

      # ...

      # 新規データ作成成功時にNet::HTTPでリクエストしてAPI叩く
      Net::HTTP.get_response(URI.parse(@user.api_url))
      redirect_to action: :thanks
    else
      render action: :new
    end
  end

  # ...

end

ブラウザ側から(Ajax等で)アクセスしなくてよいAPIなら、この流れが分かりやすいかなと思います。

30
36
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
30
36