[Rails] Grape

Tags
Rails
Engineering
Created
Oct 26, 2023 03:21 AM
Edited
Oct 25, 2023
Description
An opinionated framework for creating REST-like APIs in Ruby and designed to run on Rack - a modular Ruby web server interface.

Basic Usage

module Twitter
  class API < Grape::API
    version 'v1', using: :header, vendor: 'twitter'
    format :json
    prefix :api

    # helper functions
    helpers do
      def current_user
        @current_user ||= User.authorize!(env)
      end

      def authenticate!
        error!('401 Unauthorized', 401) unless current_user
      end
    end

    # Specify the data model to be used
    resource :statuses do
      desc 'Return a public timeline.'
      # GET api/v1/statuses/public_timeline
      get :public_timeline do
        Status.limit(20)
      end

      desc 'Return a personal timeline.'
      # api/v1/statuses/home_timeline
      get :home_timeline do
        authenticate!
        current_user.statuses.limit(20)
      end

      desc 'Return a status.'
      # parameter can be required or optional
      # GET api/v1/statuses/:id
      params do
        requires :id, type: Integer, desc: 'Status ID.'
      end
      route_param :id do
        get do
          Status.find(params[:id])
        end
      end

      desc 'Create a status.'
      params do
        requires :status, type: String, desc: 'Your status.'
      end
      # POST api/v1/statuses/:status
      post do
        authenticate!
        Status.create!({
          user: current_user,
          text: params[:status]
        })
      end

      desc 'Update a status.'
      params do
        requires :id, type: String, desc: 'Status ID.'
        requires :status, type: String, desc: 'Your status.'
      end
      # PUT api/v1/statuses/:id
      put ':id' do
        authenticate!
        current_user.statuses.find(params[:id]).update({
          user: current_user,
          text: params[:status]
        })
      end

      desc 'Delete a status.'
      params do
        requires :id, type: String, desc: 'Status ID.'
      end
      # DELETE api/v1/statuses/:id
      delete ':id' do
        authenticate!
        current_user.statuses.find(params[:id]).destroy
      end
    end
  end
end

before, after, finally

  • finally is like ensure - meaning always executed
finally do
  # this code will run after every request (successful or failed)
end

Mount

Like declaring that I want to use this class’s API?
Mount within the Rails routes does the equivalent of a Unix mount. It actually tells the app that another application (usually a Rack application) exists on that location. It is used mostly for Rails Engines.
 
  • mount <Some class that inherit Grape::API>
  • has to be placed in a class that inherit Grape::API
# 1
class MyClass < Grape::API
  mount MyClass
end

# 2
class MyClass < Grape::API

end

class MyRouter < Grape:API
  mount MyClass
end

Source