apiを作ってみる
今までviewのあるrailsしか作成したことがありませんでした。
viewのないapiだけのrailsはどんな感じなのか理解したいと思い、ミニマムなapiアプリを作ってみることにしました!
手順や注意点について書いておこうと思います!
作成手順
rails newする
通常のrailsアプリを作るときと同じように、以下のコマンドでrailsアプリを生成します。
rals new api_practice
モデルとテーブル作成
こちらも通常のrailsアプリを作るときと同じく、以下のコマンドでモデルとテーブルを作成します。
rails g model comment body:string
rails db:migrate
コントローラ作成
コントローラは通常とディレクトリの階層構造が違ってきます。
app/controllers/api/v1/配下にコントローラファイルを生成するよう、以下のコマンドを実行します。
作成したら以下のようにコントローラに各アクションを定義してあげます 。
class Api::V1::CommentsController < ApplicationController
protect_from_forgery
before_action :set_comment, only: [:show, :update, :destroy]
def index
comments = Comment.all
render json: { status: 'SUCCESS', message: 'Loaded comments', data: comments }
end
def show
render json: { status: 'SUCCESS', message: 'Loaded the comment', data: @comment }
end
def create
comment = Comment.new(comment_params)
if comment.save
render json: { status: 'SUCCESS', data: comment }
else
render json: { status: 'ERROR', data: comment.errors }
end
end
def destroy
@comment.destroy
render json: { status: 'SUCCESS', message: 'Deleted the comment', data: @comment }
end
def update
if @comment.update(comment_params)
render json: { status: 'SUCCESS', message: 'Updated the comment', data: @comment }
else
render json: { status: 'ERROR', message: 'Not updated', data: @comment.errors }
end
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:body)
end
end
※protect_from_forgeryをつけてあげないとトークンエラーが出てしまいました。階層構造が通常アプリのときと違うため必要なのでしょうか。。。?rails newする時からapiモードで作成してれば大丈夫だったのかな。。。?
ルーティング
コントローラの階層がapp/controllers/api/vi/comments_controller.rbとなっているので、ルーティングも以下のようにnamespaceを指定してあげます。
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
namespace 'api' do
namespace 'v1' do
resources :comments
end
end
end
これで各アクションが動くようになっております!
動作確認
データ作成
apiアプリの動作確認前にデータをいくつか作成します。
$ rails c
irb(main):001:0> Comment.create(body: "hello world")
(0.1ms) begin transaction
=> #<Comment id: 1, body: "hello world", created_at: "2019-09-26 07:59:07", updated_at: "2019-09-26 07:59:07">
irb(main):002:0> Comment.create(body: "hello hayashi")
=> #<Comment id: 2, body: "hello hayashi", created_at: "2019-09-26 07:59:17", updated_at: "2019-09-26 07:59:17">
動かしてみる
アプリを動かすためにまずrails sでサーバーを立ち上げます。
- getの確認
getの確認はブラウザから行うことができます。
以下はapi/v1/comments#indexへアクセスしています。
- post
$ curl -X POST -H "Content-Type: application/json" -d '{"body":"hoge"}' localhost:3000/api/v1/comments
- put
$ curl -X PUT -H "Content-Type: application/json" -d '{"body":"fuga"}' localhost:3000/api/v1/comments/3
- delete
$ curl -X DELETE localhost:3000/api/v1/comments/3
感想その他
本当に最低限の機能しか試せていないのでまだ未知な部分がたくさんあるとは思いますが、なんとなく概要は掴めたのではないかと思います。。。!!