Reputation: 131
Is there any way that I can common header in Rails with Grape so I do not have to specify the same header over and over again?
namespace :user do
desc 'Return a user.', {
headers: {
"Authorization" => {
description: "Some Token",
required: true
}
}
}
get do
{}
end
end
Notice that headers would have to be specified over and over in all my APIs since I want them to be secure. Is there a shortcut way (a design pattern) that I can follow without creating this header everytime?
And no I am not looking for something like this:
def headers
{
"Authorization" => {
description: "Some Token",
required: true
}
}
end
namespace :user do
desc 'Return a user.', {
headers: headers
}
get do
{}
end
end
Upvotes: 2
Views: 2160
Reputation: 1484
This worked well.
You can add class method that returns header definitions to api root class and call it from each api class.
app/api/root.rb
module Api
class Root < Grape::API
def self.headers_definition
{
"Authorization" => {
description: "Some Token",
required: true
}
}
end
mount Home
end
end
app/api/home.rb
module Api
class Home < Grape::API
resources :home do
desc "Home Page", headers: Root.headers_definition
get do
# some codes ...
end
end
end
end
end
Upvotes: 2
Reputation: 900
This is what I did:
app/api/api.rb
def my_headers
{
key1: {
description: 'hello',
required: true
},
key2: {
description: 'hello',
required: false
}
}
end
# define my_headers outside of API class
class API < Grape::API
version 'v1', using: :param, parameter: 'v', vendor: 'Larvata'
content_type :json, 'application/json'
# some codes ...
app/api/home.rb
class Home < API
resources :home do
desc "Home Page", { headers: my_headers }
get do
# some codes ...
oh, sorry, you are looking for this solution ...
Upvotes: 2