LoginSignup
3
3

More than 3 years have passed since last update.

RailsでAPIを作ってみた(前編)

Last updated at Posted at 2020-05-10

こんにちは!モリタケンタロウです!
今回はRuby on RailsでAPIを作る方法について紹介します。

後編は↓

開発環境

  • ruby 2.6.3p62
  • Rails 5.0.7.2

Let's Try Anyway

今回はひとまず、コントローラーの作成とルーティングの設定を行います。

APIモードでRailsアプリを作成

今回はAPIモードでRailsのアプリを作ります。
Ruby on Railsで普通にアプリを作ろうとすると、MVCモデルを前提に色々と部品を用意してくれますが、APIモードで作成することで、ViewとかAPIに要らないものを除いた最小構成でアプリを作ることができます。

rails new rails_app -d mysql --api

ちなみにDBはMySQLを採用しています。
※何かとエラーが出た場合は↓を試してみてください。

sudo yum install mysql-devel
gem install mysql2

参考:AWS Cloud9でRuby on Railsを動かしてみた(MySQL編)

コントローラーを作成

無事にアプリが作成できたら次にコントローラーを作ります。

$ rails g controller contents

コマンドを実行すると、app/controllers/contents_controller.rbというファイルができます。
このファイルをひとまず↓のように編集します。

app/controllers/contents_controller.rb
class ContentsController < ApplicationController

    def index
        render json: { action: action_name }
    end

    def create
        render json: { action: action_name }
    end

    def show
        render json: { action: action_name }
    end

    def update
        render json: { action: action_name }
    end

    def destroy
        render json: { action: action_name }
    end

end

まずは、アクション名を返すだけの処理です。

ルーティングの設定

各アクションのURLを定義するために、ルーティングの設定をします。

config/routes.rb
Rails.application.routes.draw do
  resources :contents
end

これを一行書くだけで、APIモードのアプリでは、index、create、show、update、destroyの5つのアクションに紐づくルーティングが設定されるようです。
参考:Rails のルーティング

念のため、rake routesコマンドで確認してみます。

$ rake routes
  Prefix Verb   URI Pattern             Controller#Action
contents GET    /contents(.:format)     contents#index
         POST   /contents(.:format)     contents#create
 content GET    /contents/:id(.:format) contents#show
         PATCH  /contents/:id(.:format) contents#update
         PUT    /contents/:id(.:format) contents#update
         DELETE /contents/:id(.:format) contents#destroy

ちゃんとルーティングの設定ができているようです。

動作確認

それでは、早速APIの動きを確かめてみます。
まずはアプリ諸々立ち上げます。

$ sudo service mysqld start # MySQLのDB起動
$ rails db:create # DB作成
$ rails s -p 3001 # アプリ起動(3001番ポート使用)

curlコマンドでAPIの動作確認をしてみます。

$ curl -G  http://localhost:3001/contents
# {"action":"index"}

$ curl -XPOST  http://localhost:3001/contents
# {"action":"create"}

$ curl -XPUT  http://localhost:3001/contents/id
# {"action":"update"}

$ curl -XPATCH  http://localhost:3001/contents/id
# {"action":"update"}

$ curl -XDELETE  http://localhost:3001/contents/id
# {"action":"destroy"}

ちゃんと期待した通りのアクション名が返ってきています。
今回は一旦ここまでで、次回はモデルと連携してCRUD処理の動きを確認してみようと思います。
それでは~

3
3
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
3
3