LoginSignup
21
23

More than 5 years have passed since last update.

rails5でWEBアプリケーションにAPI機能を追加実装

Last updated at Posted at 2017-11-01

シンプルなWEBサービスに簡単なAPI機能を実装し、外部から情報を取得できるようにする。
とりあえずAPIでjsonを返すところまで。
まずは閉じたAPIにするので、セキュリティはIP制限あたりを検討。
要件がシンプルなので、gemは使わずrailsのみでサクッと。

前提

  • HogePersonモデルが存在する。

application_controllerと別に、API用親コントローラを作成。

中身は別途。。

app/controllers/api_controller.rb
class ApiController < ActionController::API
end

APIコントローラを作成

app/api/v1/hoge_person_controller.rb
class Api::V1::HogePersonController < ApiController
  before_action :set_hoge_person, only: [:profile]

  # ライセンスホルダの情報を返す。
  def profile
    # TODO: バリデーション
    # TODO: @hoge_personとステータス(成功/失敗)等を含むオブジェクトをjsonで返す。
    render json: @hoge_person
  end

  private
  def set_hoge_person
    # TODO: 返す情報を絞る
    # TODO: enum等、返す情報をフォーマットする。(document必要)
    # TODO: パラメータ名とモデルのカラム名は分けたい。
    @hoge_person = HogePerson.find_by(hoge_number: params[:hoge_number])
  end

ルーティング

config/routes.rb
namespace :api, {format: 'json'} do
  namespace :v1 do
    resources :hoge_persons, only: [] do
      collection do
        get :profile
      end
    end
  end
end

アクセス

ターミナルで以下にアクセス。(又はブラウザからアドレス叩く。)
jsonが帰る。

curl https://service_domain/api/v1/hoge_persons/profile?hoge_number=123456001

ここから色々整備。

参考など

21
23
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
21
23