LoginSignup
27
20

More than 3 years have passed since last update.

Rails 5 の API モードを触ってみる

Last updated at Posted at 2019-01-23

Rails で JSON を返す API を作りたい!
でも MVC の V は要らないな・・。
そんな時は API モードで!
Rails による API 専用アプリ

Rails を --api で作成

$ rails new my-service --api
$ cd my-service
$ bundle install
$ rails s

http://localhost:3000/ へアクセス

rails_welcome.png

この画面が見えると安心しますね

JSON を返す API を作成

それでは試しに user というリソースを作ってみます
scaffold を使います
scaffold は controller や model を自動生成してくれる機能です
カラムが何も無いとアレなので name:string くらい作っておきます

$ rails g scaffold user name:string
$ rails db:migrate
$ rails s

サーバーを立ち上げたまま、ターミナルをもう一つ開いてユーザーを登録します
name はマイケルジャクソンさんも絶賛の Lion Stout にします

$ curl --request POST --url http://localhost:3000/users/ --data 'user%5Bname%5D=Lion%20Stout'

今度は以下の URL にアクセスしてみます
(users で複数形になっていることに注意です)

ちゃんと Lion Stout さんが登録されていますね!

rails_welcome_json.png

(JSON formatter という Chrome 拡張を使っています)

controller

こんな感じで自動生成されます
REST に沿って CRUD 操作のメソッドが用意される感じです
render json: @users で JSON のレスポンスを返します

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :update, :destroy]

  # GET /users
  def index
    @users = User.all

    render json: @users
  end

  # GET /users/1
  def show
    render json: @user
  end

  # POST /users
  def create
    @user = User.new(user_params)

    if @user.save
      render json: @user, status: :created, location: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # PATCH/PUT /users/1
  def update
    if @user.update(user_params)
      render json: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

  # DELETE /users/1
  def destroy
    @user.destroy
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def user_params
      params.require(:user).permit(:name)
    end
end

テスト

これは scaffold の機能ですがテストも自動生成してくれます

$ rails t
Running via Spring preloader in process 20343
Run options: --seed 58286

# Running:

.....

Finished in 0.832185s, 6.0083 runs/s, 8.4116 assertions/s.
5 runs, 7 assertions, 0 failures, 0 errors, 0 skips

参考

Rails でトークン認証 API を 15 分で実装する も宜しければご覧ください。

27
20
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
27
20