はじめに
久しぶりにRailsを触ったので、思い出すためにメモとして書いていきます。
APIを開発した経験はあまりないので、学習のためにやってみました!
APIモードでRailsアプリを作成
--apiをつけることでAPIモードでアプリを作成できます。
(不要なviewが作成されません。)
ターミナル
rails new blog --api
モデル・コントローラーの作成
postsテーブルはtitleというstring型のカラムを持ちます。
ターミナル
rails g model post title:string
rails g controller posts
rails db:create
rake db:migrate
ルーティングの設定
postsコントローラーへ飛ばすルーティングを設定します。
routes.rb
Rails.application.routes.draw do
  resources :posts
end
rails routesでルーティングが設定できているか確認しましょう。
ターミナル
posts GET    /posts(.:format)       posts#index 
      POST   /posts(.:format)       posts#create 
post  GET    /posts/:id(.:format)   posts#show
      PATCH  /posts/:id(.:format)   posts#update
      PUT    /posts/:id(.:format)   posts#update
      DELETE /posts/:id(.:format)   posts#destroy
コントローラーの設定
Postモデルから情報を取得して、JSON形式で返します。
情報の取得、作成、編集、削除ができるようアクションを設定します。app/controllers/posts_controller.rb
class PostsController < ApplicationController
      before_action :set_post, only: [:show, :update, :destroy]
      def index
        posts = Post.order(created_at: :desc)
        render json: { status: 'SUCCESS', message: 'Loaded posts', data: posts }
      end
      def show
        render json: { status: 'SUCCESS', message: 'Loaded the post', data: @post }
      end
      def create
        post = Post.new(post_params)
        if post.save
          render json: { status: 'SUCCESS', data: post }
        else
          render json: { status: 'ERROR', data: post.errors }
        end
      end
      def destroy
        @post.destroy
        render json: { status: 'SUCCESS', message: 'Deleted the post', data: @post }
      end
      def update
        if @post.update(post_params)
          render json: { status: 'SUCCESS', message: 'Updated the post', data: @post }
        else
          render json: { status: 'SUCCESS', message: 'Not updated', data: @post.errors }
        end
      end
      private
      def set_post
        @post = Post.find(params[:id])
      end
      def post_params
        params.require(:post).permit(:title)
      end
    end
  end
end
コンソールを起動して、データベースに情報を書き込みます。
ターミナル
rails console
ターミナル
2.4.4 :001 > Post.create(title:'title1')
2.4.4 :001 > Post.create(title:'title2')
curlコマンドでAPIを叩く
APIのエンドポイントに対してcurlコマンドで叩くとJSON形式で値が取れていることが確認できます。
ターミナル
curl -i localhost:3000/posts/{:id}
結果
ターミナル
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
ETag: W/"88d59c3df976fb273012ace448a85cc4"
Cache-Control: max-age=0, private, must-revalidate
X-Request-Id: b0785445-95c8-4543-861f-30565adfd6c1
X-Runtime: 0.003727
Transfer-Encoding: chunked
{"status":"SUCCESS","message":"Loaded the post","data":{"id":1,"title":"title1","created_at":"2021-04-10T06:31:55.906Z","updated_at":"2021-04-10T06:31:55.906Z"}}%  
