LoginSignup
22
21

More than 5 years have passed since last update.

Rails(Grape)でAPIを作成する備忘録1

Last updated at Posted at 2015-03-12

追記 2017/01/28
rails5でapiモードができているのでそちらを参照されたほうが良いと思います
とても簡単にrestAPIが作成できますよ

目的

研究室内wikiツールの作成

開発方針

  • フロントはAngularを用いる
  • そのためRailsではデータだけ返すAPIさえ作れれば良い

目標

  • wikiの作成、更新、削除、コメント機能の実装
  • ユーザー認証の仕組みを勉強するため1から作成

やったこと

grapeを追記

Gemfile
gem 'grape'

config/route.rbに以下を追加

config/route.rb
mount API => "/"

config/application.rbに以下を追加

config/application.rb
config.autoload_paths += %W(#{config.root}/lib/api)

lib以下にapi/api.rbを作成

lib/api/api.rb
class API < Grape::API
  prefix "api"
  format :json
  mount Document_API
  ...#以下作成するAPIを追記
end

Document_APIクラスを定義

lib/api/document_api.rb
class Document_API < Grape::API
  resource "documents" do
    helpers do
      def document_params
        ActionController::Parameters.new(params).permit(:user_id, :content, :title)
        #ここでstrong_parametersの設定
      end
    end

    #全件取得
    desc "returns all documents"
    # http://localhost:3000/api/document
    get do
      Document.all
    end

    #ID単一取得
    desc "return a document"
    params do
      requires :id, type: Integer
    end
    # http://localhost:3000/api/documents/{:id}
    get ':id' do
      Document.find(params[:id])
    end

    desc "create a document"
    params do
      requires :content, type: String
      requires :title, type: String
      requires :user_id, type: Integer
    end
    # http://localhost:3000/api/document
    post do
      document = Document.new(document_params)
      #ここでStrongParameterを用いたオブジェクトの作成
      document.save
    end

    desc "edit a document"
    # http://localhost:3000/api/documents/{:id}
    params do
      optional :content, type: String
      optional :title, type: String
    end
    patch ':id' do
      document = Document.find(params[:id])
      document.content = params[:content] if params[:content].present?
      document.title = params[:title] if params[:title].present?
      document.save
    end

    desc "delete a document"
    # http://localhost:3000/api/documents/{:id}
    params do
      requires :id, type: Integer
    end
    delete ':id' do
      document = Document.find(params[:id])
      document.destroy
    end
  end
end

一応これにてGET,POST,PATCH,DELETEは出来るようになりました
methodの中身が書いてあるサイトが少なかったので全部晒したいと思います

ここから認証を通したり、クロスドメインの設定などもやっていきたいと思います

意見や改善点などあればお願いします

参考
RailsとGrapeでRESTのWebApiを作ってみた
Grape での mass assignment 対策

22
21
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
22
21