エンジニアになりたい文系大学生

プログラミングを始めてからもうすぐ1年。iOSアプリ開発が中心。最近Webサービスの開発をやりたいのでRuby on Railsに触れ始めてます。

【Rails】Grapeで最速API開発

最近、grapeを用いてapiを作っています。
最速と言っても他のを試した事はないんですが、かなり早くできたので...

初期設定のところから記載してきます。
jbuilderを使ってresponseのjson生成してます。

設定

1. Gemfile

# Gemfile
gem 'grape'
gem 'grape-jbuilder'

Gemfileに記入後、いつも通りインストール。

$ bundle install

2. application.rb

apiのフォルダを読み込んでもらうためにパスを追加。

# config/application.rb
config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
config.middleware.use(Rack::Config) do |env|
  env['api.tilt.root'] = Rails.root.join 'app', 'views', 'api'
end

3. API

今回は、/app/api/api.rbに作っていきます。 モデルには、親モデルarticle.rbと子モデルcomment.rbを使います。

# /app/api/api.rb
class API < Grape::API

  prefix 'api'

  version 'v1', :using => :path

  format :json
  formatter :json, Grape::Formatter::Jbuilder

  resources "articles" do

    # GET /api/v1/articles
    get '', jbuilder: 'articles/index' do
      @articles = Article.all
    end

    # GET /api/v1/articles/:id
    params do
      requires :id, type: Integer
    end
    get ':id', jbuilder: 'articles/show' do
      @article = Article.find(params[:id])
    end

    # POST /api/v1/articles
    params do
      optional :title, type: String
      optional :body, type: String
    end
    post '', jbuilder: 'articles/new' do
      @article = Article.create(title: params[:title], body: params[:body])
    end

    # ネストを生成
    route_param :id do

      resources "comments" do

        # GET /api/v1/articles/:id/comments
        params do
          requires :id, type: Integer
        end
        get '', jbuilder: 'comments/index' do
          @comments = Article.find(params[:id]).comments.all
        end
      end
    end
  end
end

4. Jbuilder

viewsフォルダ配下に作っていきます。 パスは、/views/api/<モデル名>/<メソッド名>です。

# /views/api/articles/index
json.set! :articles do
  json.array! @articles do |article|
    json.id article.id
    json.title article.title
    json.body article.body
  end
end

テスト

今回は、POSTを試してみる。 まずはコマンドラインからサーバーを起動。

$ rails s

POSTを試す時には、curlを使います。

$ curl -X POST -d <data> <URL> -H "Content-Type: application/json"

-H "Content-Type: application/json"でデータ型を指定しないとサーバー側で読み取ってくれないみたいです... なので、実際にはこんな感じです。

$ curl -X POST -d '{"title": "Test Title", "body": "Test Body"}' http://localhost:3000/api/v1/articles -H "Content-Type: application/json"```

基本的な部分はこれで実装できると思います。 認証とかトークンとかはこれからやっていきます。。。