ruby-on-railsswaggerdocumentationruby-grape

Grape API (swagger doc) - Global configuration of 'desc'


Its been an interesting an busy week. I am working on a Rails project and included Grape to implement the API.

The API has 2 sections

I setup the app with and all is working...

For stating that a header is required I use some thing like this...

class ProfilesApi < Grape::API

  resource :profiles do

    desc 'List all profiles' do
      headers Authorization: {
                description: 'Validates identity through JWT provided in auth/login',
                required: true
              }
    end
    get do
      present User.all, with: Presenters::ProfilePresenter
    end
  end
end

Now the problem is that I this description in a lot of similar mountable API classes.

Is there a way that can kind of make this common (kind of inherited) so that I don't need to define it wit every Grape method.

    desc 'List all profiles' do
      headers Authorization: {
                description: 'Validates identity through JWT provided in auth/login',
                required: true
              }
    end

Solution

  • Yes, there's a way. I achieve that by defining a method in class API so that it's accessible in everything that inherits from API. Something like:

    module Myapp
      class API < Grape::API
        def self.auth_headers
          { Authorization: { description: 'Validates identity through JWT provided in auth/login',required: true}}
        end
      end
    end
    

    And you access it like that:

    desc "List all profiles", {
      headers: Myapp::API.auth_headers
    }
    

    Of course, there're much more ways but they depend on your implementation.