rainforestapp/grape

Name: grape

Owner: Rainforest QA

Description: An opinionated framework for creating REST-like APIs in Ruby.

Forked from: ruby-grape/grape

Created: 2017-08-10 21:50:27.0

Updated: 2017-08-10 21:50:29.0

Pushed: 2017-08-10 21:56:16.0

Homepage: http://www.ruby-grape.org

Size: 4300

Language: Ruby

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

grape logo

Gem Version Build Status Dependency Status Code Climate Coverage Status Inline docs git.legal Join the chat at https://gitter.im/ruby-grape/grape

Table of Contents
What is Grape?

Grape is a REST-like API framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs. It has built-in support for common conventions, including multiple formats, subdomain/prefix restriction, content negotiation, versioning and much more.

Stable Release

You're reading the documentation for the next release of Grape, which should be 1.0.1. Please read UPGRADING when upgrading from a previous version. The current stable release is 1.0.0.

Project Resources
Installation

Grape is available as a gem, to install it just install the gem:

gem install grape

If you're using Bundler, add the gem to Gemfile.

gem 'grape'

Run bundle install.

Basic Usage

Grape APIs are Rack applications that are created by subclassing Grape::API. Below is a simple example showing some of the more common features of Grape in the context of recreating parts of the Twitter API.

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

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

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

resource :statuses do
  desc 'Return a public timeline.'
  get :public_timeline do
    Status.limit(20)
  end

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

  desc 'Return a status.'
  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 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 ':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 ':id' do
    authenticate!
    current_user.statuses.find(params[:id]).destroy
  end
end
d

Mounting
Rack

The above sample creates a Rack application that can be run from a rackup config.ru file with rackup:

Twitter::API

And would respond to the following routes:

GET /api/statuses/public_timeline
GET /api/statuses/home_timeline
GET /api/statuses/:id
POST /api/statuses
PUT /api/statuses/:id
DELETE /api/statuses/:id

Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.

ActiveRecord without Rails

If you want to use ActiveRecord within Grape, you will need to make sure that ActiveRecord's connection pool is handled correctly.

The easiest way to achieve that is by using ActiveRecord's ConnectionManagement middleware in your config.ru before mounting Grape, e.g.:

ActiveRecord::ConnectionAdapters::ConnectionManagement

Twitter::API
Alongside Sinatra (or other frameworks)

If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using Rack::Cascade:

ample config.ru

ire 'sinatra'
ire 'grape'

s API < Grape::API
t :hello do
{ hello: 'world' }
d


s Web < Sinatra::Base
t '/' do
'Hello world.'
d


Rack::Session::Cookie
Rack::Cascade.new [API, Web]
Rails

Place API files into app/api. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory for Twitter::API should be app/api/twitter/api.rb.

Modify application.rb:

ig.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
ig.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

Modify config/routes:

t Twitter::API => '/'

Additionally, if the version of your Rails is 4.0+ and the application uses the default model layer of ActiveRecord, you will want to use the hashie-forbidden_attributes gem. This gem disables the security feature of strong_params at the model layer, allowing you the use of Grape's own params validation instead.

mfile
'hashie-forbidden_attributes'

See below for additional code that enables reloading of API changes in development.

Modules

You can mount multiple API implementations inside another one. These don't have to be different versions, but may be components of the same API.

s Twitter::API < Grape::API
unt Twitter::APIv1
unt Twitter::APIv2

You can also mount on a path, which is similar to using prefix inside the mounted API itself.

s Twitter::API < Grape::API
unt Twitter::APIv1 => '/v1'

Keep in mind such declarations as before/after/rescue_from must be placed before mount in a case where they should be inherited.

s Twitter::API < Grape::API
fore do
header 'X-Base-Header', 'will be defined for all APIs that are mounted below'
d

unt Twitter::Users
unt Twitter::Search

Versioning

There are four strategies in which clients can reach your API's endpoints: :path, :header, :accept_version_header and :param. The default strategy is :path.

Path
ion 'v1', using: :path

Using this versioning strategy, clients should pass the desired version in the URL.

curl http://localhost:9292/v1/statuses/public_timeline
Header
ion 'v1', using: :header, vendor: 'twitter'

Currently, Grape only supports versioned media types in the following format:

vendor-and-or-resource-v1234+format

Basically all tokens between the final - and the + will be interpreted as the version.

Using this versioning strategy, clients should pass the desired version in the HTTP Accept head.

curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline

By default, the first matching version is used when no Accept header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the :strict option. When this option is set to true, a 406 Not Acceptable error is returned when no correct Accept header is supplied.

When an invalid Accept header is supplied, a 406 Not Acceptable error is returned if the :cascade option is set to false. Otherwise a 404 Not Found error is returned by Rack if no other route matches.

Accept-Version Header
ion 'v1', using: :accept_version_header

Using this versioning strategy, clients should pass the desired version in the HTTP Accept-Version header.

curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline

By default, the first matching version is used when no Accept-Version header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the :strict option. When this option is set to true, a 406 Not Acceptable error is returned when no correct Accept header is supplied and the :cascade option is set to false. Otherwise a 404 Not Found error is returned by Rack if no other route matches.

Param
ion 'v1', using: :param

Using this versioning strategy, clients should pass the desired version as a request parameter, either in the URL query string or in the request body.

curl http://localhost:9292/statuses/public_timeline?apiver=v1

The default name for the query parameter is 'apiver' but can be specified using the :parameter option.

ion 'v1', using: :param, parameter: 'v'
curl http://localhost:9292/statuses/public_timeline?v=v1
Describing Methods

You can add a description to API methods and namespaces.

 'Returns your public timeline.' do
tail 'more details'
rams  API::Entities::Status.documentation
ccess API::Entities::Entity
ilure [[401, 'Unauthorized', 'Entities::Error']]
med 'My named route'
aders XAuthToken: {
        description: 'Validates your identity',
        required: true
      },
      XOptionalHeader: {
        description: 'Not really needed',
        required: false
      }


:public_timeline do
atus.limit(20)

Parameters

Request parameters are available through the params hash object. This includes GET, POST and PUT parameters, along with any named parameters you specify in your route strings.

:public_timeline do
atus.order(params[:sort_by])

Parameters are automatically populated from the request body on POST and PUT for form input, JSON and XML content-types.

The request:

 -d '{"text": "140 characters"}' 'http://localhost:9292/statuses' -H Content-Type:application/json -v

The Grape endpoint:

 '/statuses' do
atus.create!(text: params[:text])

Multipart POSTs and PUTs are supported as well.

The request:

 --form image_file='@image.jpg;type=image/jpg' http://localhost:9292/upload

The Grape endpoint:

 'upload' do
file in params[:image_file]

In the case of conflict between either of:

Route string parameters will have precedence.

Params Class

By default parameters are available as ActiveSupport::HashWithIndifferentAccess. This can be changed to, for example, Ruby Hash or Hashie::Mash for the entire API.

s API < Grape::API
clude Grape::Extensions::Hashie::Mash::ParamBuilder

rams do
optional :color, type: String
d
t do
params.color # instead of params[:color]
d

The class can also be overridden on individual parameter blocks using build_with as follows.

ms do
ild_with Grape::Extensions::Hash::ParamBuilder
tional :color, type: String

In the example above, params["color"] will return nil since params is a plain Hash.

Available parameter builders are Grape::Extensions::Hash::ParamBuilder, Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder and Grape::Extensions::Hashie::Mash::ParamBuilder.

Declared

Grape allows you to access only the parameters that have been declared by your params block. It filters out the params that have been passed, but are not allowed. Consider the following API endpoint:

at :json

 'users/signup' do
'declared_params' => declared(params) }

If you do not specify any parameters, declared will return an empty hash.

Request

 -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": "last name"}}'

Response


eclared_params": {}

Once we add parameters requirements, grape will start returning only the declared parameters.

at :json

ms do
quires :user, type: Hash do
requires :first_name, type: String
requires :last_name, type: String
d


 'users/signup' do
'declared_params' => declared(params) }

Request

 -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": "last name", "random": "never shown"}}'

Response


eclared_params": {
"user": {
  "first_name": "first name",
  "last_name": "last name"
}


The returned hash is an ActiveSupport::HashWithIndifferentAccess.

The #declared method is not available to before filters, as those are evaluated prior to parameter coercion.

Include Parent Namespaces

By default declared(params) includes parameters that were defined in all parent namespaces. If you want to return only parameters from your current namespace, you can set include_parent_namespaces option to false.

at :json

space :parent do
rams do
requires :parent_name, type: String
d

mespace ':parent_name' do
params do
  requires :child_name, type: String
end
get ':child_name' do
  {
    'without_parent_namespaces' => declared(params, include_parent_namespaces: false),
    'with_parent_namespaces' => declared(params, include_parent_namespaces: true),
  }
end
d

Request

 -X GET -H "Content-Type: application/json" localhost:9292/parent/foo/bar

Response


ithout_parent_namespaces": {
"child_name": "bar"

ith_parent_namespaces": {
"parent_name": "foo",
"child_name": "bar"


Include missing

By default declared(params) includes parameters that have nil values. If you want to return only the parameters that are not nil, you can use the include_missing option. By default, include_missing is set to true. Consider the following API:

at :json

ms do
quires :first_name, type: String
tional :last_name, type: String


 'users/signup' do
'declared_params' => declared(params, include_missing: false) }

Request

 -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "random": "never shown"}}'

Response with include_missing:false


eclared_params": {
"user": {
  "first_name": "first name"
}


Response with include_missing:true


eclared_params": {
"first_name": "first name",
"last_name": null


It also works on nested hashes:

at :json

ms do
quires :user, type: Hash do
requires :first_name, type: String
optional :last_name, type: String
requires :address, type: Hash do
  requires :city, type: String
  optional :region, type: String
end
d


 'users/signup' do
'declared_params' => declared(params, include_missing: false) }

Request

 -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "random": "never shown", "address": { "city": "SF"}}}'

Response with include_missing:false


eclared_params": {
"user": {
  "first_name": "first name",
  "address": {
    "city": "SF"
  }
}


Response with include_missing:true


eclared_params": {
"user": {
  "first_name": "first name",
  "last_name": null,
  "address": {
    "city": "Zurich",
    "region": null
  }
}


Note that an attribute with a nil value is not considered missing and will also be returned when include_missing is set to false:

Request

 -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": null, "address": { "city": "SF"}}}'

Response with include_missing:false


eclared_params": {
"user": {
  "first_name": "first name",
  "last_name": null,
  "address": { "city": "SF"}
}


Parameter Validation and Coercion

You can define validations and coercion options for your parameters using a params block.

ms do
quires :id, type: Integer
tional :text, type: String, regexp: /\A[a-z]+\z/
oup :media, type: Hash do
requires :url
d
tional :audio, type: Hash do
requires :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3
d
tually_exclusive :media, :audio

':id' do
params[:id] is an Integer

When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.

Optional parameters can have a default value.

ms do
tional :color, type: String, default: 'blue'
tional :random_number, type: Integer, default: -> { Random.rand(1..100) }
tional :non_random_number, type: Integer, default:  Random.rand(1..100)

Note that default values will be passed through to any validation options specified. The following example will always fail if :color is not explicitly provided.

Default values are eagerly evaluated. Above :non_random_number will evaluate to the same number for each call to the endpoint of this params block. To have the default evaluate lazily with each request use a lambda, like :random_number above.

ms do
tional :color, type: String, default: 'blue', values: ['red', 'green']

The correct implementation is to ensure the default value passes all validations.

ms do
tional :color, type: String, default: 'blue', values: ['blue', 'red', 'green']

Supported Parameter Types

The following are all valid types, supported out of the box by Grape:

Integer/Fixnum and Coercions

Please be aware that the behavior differs between Ruby 2.4 and earlier versions. In Ruby 2.4, values consisting of numbers are converted to Integer, but in earlier versions it will be treated as Fixnum.

ms do
quires :integers, type: Hash do
requires :int, coerce: Integer
d

'/int' do
rams[:integers][:int].class




'/int' integers: { int: '45' }
> Integer in ruby 2.4
> Fixnum in earlier ruby versions
Custom Types and Coercions

Aside from the default set of supported types listed above, any class can be used as a type so long as an explicit coercion method is supplied. If the type implements a class-level parse method, Grape will use it automatically. This method must take one string argument and return an instance of the correct type, or raise an exception to indicate the value was invalid. E.g.,

s Color
tr_reader :value
f initialize(color)
@value = color
d

f self.parse(value)
fail 'Invalid color' unless %w(blue red green).include?(value)
new(value)
d


.

ms do
quires :color, type: Color, default: Color.new('blue')


'/stuff' do
params[:color] is already a Color.
rams[:color].value

Alternatively, a custom coercion method may be supplied for any type of parameter using coerce_with. Any class or object may be given that implements a parse or call method, in that order of precedence. The method must accept a single string parameter, and the return value must match the given type.

ms do
quires :passwd, type: String, coerce_with: Base64.method(:decode)
quires :loud_color, type: Color, coerce_with: ->(c) { Color.parse(c.downcase) }

quires :obj, type: Hash, coerce_with: JSON do
requires :words, type: Array[String], coerce_with: ->(val) { val.split(/\s+/) }
optional :time, type: Time, coerce_with: Chronic
d

Example of use of coerce_with with a lambda (a class with a parse method could also have been used) It will parse a string and return an Array of Integers, matching the Array[Integer] type.

ms do
quires :values, type: Array[Integer], coerce_with: ->(val) { val.split(/\s+/).map(&:to_i) }

Multipart File Parameters

Grape makes use of Rack::Request's built-in support for multipart file parameters. Such parameters can be declared with type: File:

ms do
quires :avatar, type: File

 '/' do
rams[:avatar][:filename] # => 'avatar.png'
rams[:avatar][:avatar] # => 'image/png'
rams[:avatar][:tempfile] # => #<File>

First-Class JSON Types

Grape supports complex parameters given as JSON-formatted strings using the special type: JSON declaration. JSON objects and arrays of objects are accepted equally, with nested validation rules applied to all objects in either case:

ms do
quires :json, type: JSON do
requires :int, type: Integer, values: [1, 2, 3]
d

'/' do
rams[:json].inspect


.

nt.get('/', json: '{"int":1}') # => "{:int=>1}"
nt.get('/', json: '[{"int":"1"}]') # => "[{:int=>1}]"

nt.get('/', json: '{"int":4}') # => HTTP 400
nt.get('/', json: '[{"int":4}]') # => HTTP 400

Additionally type: Array[JSON] may be used, which explicitly marks the parameter as an array of objects. If a single object is supplied it will be wrapped.

ms do
quires :json, type: Array[JSON] do
requires :int, type: Integer
d

'/' do
rams[:json].each { |obj| ... } # always works

For stricter control over the type of JSON structure which may be supplied, use type: Array, coerce_with: JSON or type: Hash, coerce_with: JSON.

Multiple Allowed Types

Variant-type parameters can be declared using the types option rather than type:

ms do
quires :status_code, types: [Integer, String, Array[Integer, String]]

'/' do
rams[:status_code].inspect


.

nt.get('/', status_code: 'OK_GOOD') # => "OK_GOOD"
nt.get('/', status_code: 300) # => 300
nt.get('/', status_code: %w(404 NOT FOUND)) # => [404, "NOT", "FOUND"]

As a special case, variant-member-type collections may also be declared, by passing a Set or Array with more than one member to type:

ms do
quires :status_codes, type: Array[Integer,String]

'/' do
rams[:status_codes].inspect


.

nt.get('/', status_codes: %w(1 two)) # => [1, "two"]
Validation of Nested Parameters

Parameters can be nested using group or by calling requires or optional with a block. In the above example, this means params[:media][:url] is required along with params[:id], and params[:audio][:format] is required only if params[:audio] is present. With a block, group, requires and optional accept an additional option type which can be either Array or Hash, and defaults to Array. Depending on the value, the nested parameters will be treated either as values of a hash or as values of hashes in an array.

ms do
tional :preferences, type: Array do
requires :key
requires :value
d

quires :name, type: Hash do
requires :first_name
requires :last_name
d

Dependent Parameters

Suppose some of your parameters are only relevant if another parameter is given; Grape allows you to express this relationship through the given method in your parameters block, like so:

ms do
tional :shelf_id, type: Integer
ven :shelf_id do
requires :bin_id, type: Integer
d

In the example above Grape will use blank? to check whether the shelf_id param is present.

Given also takes a Proc with custom code. Below, the param description is required only if the value of category is equal foo:

ms do
tional :category
ven category: ->(val) { val == 'foo' } do
requires :description
d

Group Options

Parameters options can be grouped. It can be useful if you want to extract common validation or types for several parameters. The example below presents a typical case when parameters share common options.

ms do
quires :first_name, type: String, regexp: /w+/, desc: 'First name'
quires :middle_name, type: String, regexp: /w+/, desc: 'Middle name'
quires :last_name, type: String, regexp: /w+/, desc: 'Last name'

Grape allows you to present the same logic through the with method in your parameters block, like so:

ms do
th(type: String, regexp: /w+/) do
requires :first_name, desc: 'First name'
requires :middle_name, desc: 'Middle name'
requires :last_name, desc: 'Last name'
d

Alias

You can set an alias for parameters using as, which can be useful when refactoring existing APIs:

urce :users do
rams do
requires :email_address, as: :email
requires :password
d
st do
User.create!(declared(params)) # User takes email and password
d

The value passed to as will be the key when calling params or declared(params).

Built-in Validators
allow_blank

Parameters can be defined as allow_blank, ensuring that they contain a value. By default, requires only validates that a parameter was sent in the request, regardless its value. With allow_blank: false, empty values or whitespace only values are invalid.

allow_blank can be combined with both requires and optional. If the parameter is required, it has to contain a value. If it's optional, it's possible to not send it in the request, but if it's being sent, it has to have some value, and not an empty string/only whitespaces.

ms do
quires :username, allow_blank: false
tional :first_name, allow_blank: false

values

Parameters can be restricted to a specific set of values with the :values option.

ms do
quires :status, type: Symbol, values: [:not_started, :processing, :done]
tional :numbers, type: Array[Integer], default: 1, values: [1, 2, 3, 5, 8]

Supplying a range to the :values option ensures that the parameter is (or parameters are) included in that range (using Range#include?).

ms do
quires :latitude, type: Float, values: -90.0..+90.0
quires :longitude, type: Float, values: -180.0..+180.0
tional :letters, type: Array[String], values: 'a'..'z'

Note that both range endpoints have to be a #kind_of? your :type option (if you don't supply the :type option, it will be guessed to be equal to the class of the range's first endpoint). So the following is invalid:

ms do
quires :invalid1, type: Float, values: 0..10 # 0.kind_of?(Float) => false
tional :invalid2, values: 0..10.0 # 10.0.kind_of?(0.class) => false

The :values option can also be supplied with a Proc, evaluated lazily with each request. If the Proc has arity zero (i.e. it takes no arguments) it is expected to return either a list or a range which will then be used to validate the parameter.

For example, given a status model you may want to restrict by hashtags that you have previously defined in the HashTag model.

ms do
quires :hashtag, type: String, values: -> { Hashtag.all.map(&:tag) }

Alternatively, a Proc with arity one (i.e. taking one argument) can be used to explicitly validate each parameter value. In that case, the Proc is expected to return a truthy value if the parameter value is valid.

ms do
quires :number, type: Integer, values: ->(v) { v.even? && v < 25 }

While Procs are convenient for single cases, consider using Custom Validators in cases where a validation is used more than once.

except_values

Parameters can be restricted from having a specific set of values with the :except_values option.

The except_values validator behaves similarly to the values validator in that it accepts either an Array, a Range, or a Proc. Unlike the values validator, however, except_values only accepts Procs with arity zero.

ms do
quires :browser, except_values: [ 'ie6', 'ie7', 'ie8' ]
quires :port, except_values: { value: 0..1024, message: 'is not allowed' }
quires :hashtag, except_values: -> { Hashtag.FORBIDDEN_LIST }

regexp

Parameters can be restricted to match a specific regular expression with the :regexp option. If the value does not match the regular expression an error will be returned. Note that this is true for both requires and optional parameters.

ms do
quires :email, regexp: /.+@.+/

The validator will pass if the parameter was sent without value. To ensure that the parameter contains a value, use allow_blank: false.

ms do
quires :email, allow_blank: false, regexp: /.+@.+/

mutually_exclusive

Parameters can be defined as mutually_exclusive, ensuring that they aren't present at the same time in a request.

ms do
tional :beer
tional :wine
tually_exclusive :beer, :wine

Multiple sets can be defined:

ms do
tional :beer
tional :wine
tually_exclusive :beer, :wine
tional :scotch
tional :aquavit
tually_exclusive :scotch, :aquavit

Warning: Never define mutually exclusive sets with any required params. Two mutually exclusive required params will mean params are never valid, thus making the endpoint useless. One required param mutually exclusive with an optional param will mean the latter is never valid.

exactly_one_of

Parameters can be defined as 'exactly_one_of', ensuring that exactly one parameter gets selected.

ms do
tional :beer
tional :wine
actly_one_of :beer, :wine

at_least_one_of

Parameters can be defined as 'at_least_one_of', ensuring that at least one parameter gets selected.

ms do
tional :beer
tional :wine
tional :juice
_least_one_of :beer, :wine, :juice

all_or_none_of

Parameters can be defined as 'all_or_none_of', ensuring that all or none of parameters gets selected.

ms do
tional :beer
tional :wine
tional :juice
l_or_none_of :beer, :wine, :juice

Nested mutually_exclusive, exactly_one_of, at_least_one_of, all_or_none_of

All of these methods can be used at any nested level.

ms do
quires :food, type: Hash do
optional :meat
optional :fish
optional :rice
at_least_one_of :meat, :fish, :rice
d
oup :drink, type: Hash do
optional :beer
optional :wine
optional :juice
exactly_one_of :beer, :wine, :juice
d
tional :dessert, type: Hash do
optional :cake
optional :icecream
mutually_exclusive :cake, :icecream
d
tional :recipe, type: Hash do
optional :oil
optional :meat
all_or_none_of :oil, :meat
d

Namespace Validation and Coercion

Namespaces allow parameter definitions and apply to every method within the namespace.

space :statuses do
rams do
requires :user_id, type: Integer, desc: 'A user ID.'
d
mespace ':user_id' do
desc "Retrieve a user's status."
params do
  requires :status_id, type: Integer, desc: 'A status ID.'
end
get ':status_id' do
  User.find(params[:user_id]).statuses.find(params[:status_id])
end
d

The namespace method has a number of aliases, including: group, resource, resources, and segment. Use whichever reads the best for your API.

You can conveniently define a route parameter as a namespace using route_param.

space :statuses do
ute_param :id do
desc 'Returns all replies for a status.'
get 'replies' do
  Status.find(params[:id]).replies
end
desc 'Returns a status.'
get do
  Status.find(params[:id])
end
d

You can also define a route parameter type by passing to route_param's options.

space :arithmetic do
ute_param :n, type: Integer do
desc 'Returns in power'
get 'power' do
  params[:n] ** params[:n]
end
d

Custom Validators
s AlphaNumeric < Grape::Validations::Base
f validate_param!(attr_name, params)
unless params[attr_name] =~ /\A[[:alnum:]]+\z/
  fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: 'must consist of alpha-numeric characters'
end
d

uby
ms do
quires :text, alpha_numeric: true

You can also create custom classes that take parameters.

s Length < Grape::Validations::Base
f validate_param!(attr_name, params)
unless params[attr_name].length <= @option
  fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: "must be at the most #{@option} characters long"
end
d

uby
ms do
quires :text, length: 140

You can also create custom validation that use request to validate the attribute. For example if you want to have parameters that are available to only admins, you can do the following.

s Admin < Grape::Validations::Base
f validate(request)
# return if the param we are checking was not in request
# @attrs is a list containing the attribute we are currently validating
# in our sample case this method once will get called with
# @attrs being [:admin_field] and once with @attrs being [:admin_false_field]
return unless request.params.key?(@attrs.first)
# check if admin flag is set to true
return unless @option
# check if user is admin or not
# as an example get a token from request and check if it's admin or not
fail Grape::Exceptions::Validation, params: @attrs, message: 'Can not set admin-only field.' unless request.headers['X-Access-Token'] == 'admin'
d

And use it in your endpoint definition as:

ms do
tional :admin_field, type: String, admin: true
tional :non_admin_field, type: String
tional :admin_false_field, type: String, admin: false

Every validation will have it's own instance of the validator, which means that the validator can have a state.

Validation Errors

Validation and coercion errors are collected and an exception of type Grape::Exceptions::ValidationErrors is raised. If the exception goes uncaught it will respond with a status of 400 and an error message. The validation errors are grouped by parameter name and can be accessed via Grape::Exceptions::ValidationErrors#errors.

The default response from a Grape::Exceptions::ValidationErrors is a humanly readable string, such as “beer, wine are mutually exclusive”, in the following example.

ms do
tional :beer
tional :wine
tional :juice
actly_one_of :beer, :wine, :juice

You can rescue a Grape::Exceptions::ValidationErrors and respond with a custom response or turn the response into well-formatted JSON for a JSON API that separates individual parameters and the corresponding error messages. The following rescue_from example produces [{"params":["beer","wine"],"messages":["are mutually exclusive"]}].

at :json
ect.rescue_from Grape::Exceptions::ValidationErrors do |e|
ror! e, 400

Grape::Exceptions::ValidationErrors#full_messages returns the validation messages as an array. Grape::Exceptions::ValidationErrors#message joins the messages to one string.

For responding with an array of validation messages, you can use Grape::Exceptions::ValidationErrors#full_messages.

at :json
ect.rescue_from Grape::Exceptions::ValidationErrors do |e|
ror!({ messages: e.full_messages }, 400)

Grape returns all validation and coercion errors found by default. To skip all subsequent validation checks when a specific param is found invalid, use fail_fast: true.

The following example will not check if :wine is present unless it finds :beer.

ms do
quired :beer, fail_fast: true
quired :wine

The result of empty params would be a single Grape::Exceptions::ValidationErrors error.

Similarly, no regular expression test will be performed if :blah is blank in the following example.

ms do
quired :blah, allow_blank: false, regexp: /blah/, fail_fast: true

I18n

Grape supports I18n for parameter-related error messages, but will fallback to English if translations for the default locale have not been provided. See en.yml for message keys.

Custom Validation messages

Grape supports custom validation messages for parameter-related and coerce-related error messages.

presence, allow_blank, values, regexp
ms do
quires :name, values: { value: 1..10, message: 'not in range from 1 to 10' }, allow_blank: { value: false, message: 'cannot be blank' }, regexp: { value: /^[a-z]+$/, message: 'format is invalid' }, message: 'is required'

all_or_none_of
ms do
tional :beer
tional :wine
tional :juice
l_or_none_of :beer, :wine, :juice, message: "all params are required or none is required"

mutually_exclusive
ms do
tional :beer
tional :wine
tional :juice
tually_exclusive :beer, :wine, :juice, message: "are mutually exclusive cannot pass both params"

exactly_one_of
ms do
tional :beer
tional :wine
tional :juice
actly_one_of :beer, :wine, :juice, message: {exactly_one: "are missing, exactly one parameter is required", mutual_exclusion: "are mutually exclusive, exactly one parameter is required"}

at_least_one_of
ms do
tional :beer
tional :wine
tional :juice
_least_one_of :beer, :wine, :juice, message: "are missing, please specify at least one param"

Coerce
ms do
quires :int, type: {value: Integer, message: "type cast is invalid" }

With Lambdas
ms do
quires :name, values: { value: -> { (1..10).to_a }, message: 'not in range from 1 to 10' }

Pass symbols for i18n translations

You can pass a symbol if you want i18n translations for your custom validation messages.

ms do
quires :name, message: :name_required

.yml


ape:
errors:
  format: ! '%{attributes} %{message}'
  messages:
    name_required: 'must be present'
Overriding attribute names

You can also override attribute names.

.yml


ape:
errors:
  format: ! '%{attributes} %{message}'
  messages:
    name_required: 'must be present'
  attributes:
    name: 'Oops! Name'

Will produce 'Oops! Name must be present'

With Default

You cannot set a custom message option for Default as it requires interpolation %{option1}: %{value1} is incompatible with %{option2}: %{value2}. You can change the default error message for Default by changing the incompatible_option_values message key inside en.yml

ms do
quires :name, values: { value: -> { (1..10).to_a }, message: 'not in range from 1 to 10' }, default: 5

Headers

Request headers are available through the headers helper or from env in their original form.

do
ror!('Unauthorized', 401) unless headers['Secret-Password'] == 'swordfish'

uby
do
ror!('Unauthorized', 401) unless env['HTTP_SECRET_PASSWORD'] == 'swordfish'

You can set a response header with header inside an API.

er 'X-Robots-Tag', 'noindex'

When raising error!, pass additional headers as arguments.

r! 'Unauthorized', 401, 'X-Error-Detail' => 'Invalid token.'
Routes

Optionally, you can define requirements for your named route parameters using regular expressions on namespace or endpoint. The route will match only if all requirements are met.

':id', requirements: { id: /[0-9]*/ } do
atus.find(params[:id])


space :outer, requirements: { id: /[0-9]*/ } do
t :id do
d

t ':id/edit' do
d

Helpers

You can define helper methods that your endpoints can use with the helpers macro by either giving a block or an array of modules.

le StatusHelpers
f user_info(user)
"#{user} has statused #{user.statuses} status(s)"
d


le HttpCodesHelpers
f unauthorized
401
d


s API < Grape::API
define helpers with a block
lpers do
def current_user
  User.find(params[:user_id])
end
d

or mix in an array of modules
lpers StatusHelpers, HttpCodesHelpers

fore do
error!('Access Denied', unauthorized) unless current_user
d

t 'info' do
# helpers available in your endpoint and filters
user_info(current_user)
d

You can define reusable params using helpers.

s API < Grape::API
lpers do
params :pagination do
  optional :page, type: Integer
  optional :per_page, type: Integer
end
d

sc 'Get collection'
rams do
use :pagination # aliases: includes, use_scope
d
t do
Collection.page(params[:page]).per(params[:per_page])
d

You can also define reusable params using shared helpers.

le SharedParams
tend Grape::API::Helpers

rams :period do
optional :start_date
optional :end_date
d

rams :pagination do
optional :page, type: Integer
optional :per_page, type: Integer
d


s API < Grape::API
lpers SharedParams

sc 'Get collection.'
rams do
use :period, :pagination
d

t do
Collection
  .from(params[:start_date])
  .to(params[:end_date])
  .page(params[:page])
  .per(params[:per_page])
d

Helpers support blocks that can help set default values. The following API can return a collection sorted by id or created_at in asc or desc order.

le SharedParams
tend Grape::API::Helpers

rams :order do |options|
optional :order_by, type:Symbol, values:options[:order_by], default:options[:default_order_by]
optional :order, type:Symbol, values:%i(asc desc), default:options[:default_order]
d


s API < Grape::API
lpers SharedParams

sc 'Get a sorted collection.'
rams do
use :order, order_by:%i(id created_at), default_order_by: :created_at, default_order: :asc
d

t do
Collection.send(params[:order], params[:order_by])
d

Path Helpers

If you need methods for generating paths inside your endpoints, please see the grape-route-helpers gem.

Parameter Documentation

You can attach additional documentation to params using a documentation hash.

ms do
tional :first_name, type: String, documentation: { example: 'Jim' }
quires :last_name, type: String, documentation: { example: 'Smith' }

Cookies

You can set, get and delete your cookies very simply using cookies method.

s API < Grape::API
t 'status_count' do
cookies[:status_count] ||= 0
cookies[:status_count] += 1
{ status_count: cookies[:status_count] }
d

lete 'status_count' do
{ status_count: cookies.delete(:status_count) }
d

Use a hash-based syntax to set more than one value.

ies[:status_count] = {
lue: 0,
pires: Time.tomorrow,
main: '.twitter.com',
th: '/'


ies[:status_count][:value] +=1

Delete a cookie with delete.

ies.delete :status_count

Specify an optional path.

ies.delete :status_count, path: '/'
HTTP Status Code

By default Grape returns a 201 for POST-Requests, 204 for DELETE-Requests that don't return any content, and 200 status code for all other Requests. You can use status to query and set the actual HTTP Status Code

 do
atus 202

 status == 200
 # do some thing
d

You can also use one of status codes symbols that are provided by Rack utils

 do
atus :no_content

Redirecting

You can redirect to a new url temporarily (302) or permanently (301).

rect '/statuses'
uby
rect '/statuses', permanent: true
Recognizing Path

You can recognize the endpoint matched with given path.

This API returns an instance of Grape::Endpoint.

s API < Grape::API
t '/statuses' do
d


recognize_path '/statuses'
Allowed Methods

When you add a GET route for a resource, a route for the HEAD method will also be added automatically. You can disable this behavior with do_not_route_head!.

s API < Grape::API
_not_route_head!

t '/example' do
# only responds to GET
d

When you add a route for a resource, a route for the OPTIONS method will also be added. The response to an OPTIONS request will include an “Allow” header listing the supported methods. If the resource has before and after callbacks they will be executed, but no other callbacks will run.

s API < Grape::API
t '/rt_count' do
{ rt_count: current_user.rt_count }
d

rams do
requires :value, type: Integer, desc: 'Value to add to the rt count.'
d
t '/rt_count' do
current_user.rt_count += params[:value].to_i
{ rt_count: current_user.rt_count }
d

shell
 -v -X OPTIONS http://localhost:3000/rt_count

TIONS /rt_count HTTP/1.1

TP/1.1 204 No Content
low: OPTIONS, GET, PUT

You can disable this behavior with do_not_route_options!.

If a request for a resource is made with an unsupported HTTP method, an HTTP 405 (Method Not Allowed) response will be returned. If the resource has before callbacks they will be executed, but no other callbacks will run.

 -X DELETE -v http://localhost:3000/rt_count/

LETE /rt_count/ HTTP/1.1
st: localhost:3000

TP/1.1 405 Method Not Allowed
low: OPTIONS, GET, PUT
Raising Exceptions

You can abort the execution of an API method by raising errors with error!.

r! 'Access Denied', 401

Anything that responds to #to_s can be given as a first argument to error!.

r! :not_found, 404

You can also return JSON formatted objects by raising error! and passing a hash instead of a message.

r!({ error: 'unexpected error', detail: 'missing widget' }, 500)

You can present documented errors with a Grape entity using the the grape-entity gem.

le API
ass Error < Grape::Entity
expose :code
expose :message
d

The following example specifies the entity to use in the http_codes definition.

 'My Route' do
lure [[408, 'Unauthorized', API::Error]]

r!({ message: 'Unauthorized' }, 408)

The following example specifies the presented entity explicitly in the error message.

 'My Route' do
lure [[408, 'Unauthorized']]

r!({ message: 'Unauthorized', with: API::Error }, 408)
Default Error HTTP Status Code

By default Grape returns a 500 status code from error!. You can change this with default_error_status.

s API < Grape::API
fault_error_status 400
t '/example' do
error! 'This should have http status code 400'
d

Handling 404

For Grape to handle all the 404s for your API, it can be useful to use a catch-all. In its simplest form, it can be like:

e :any, '*path' do
ror! # or something else

It is very crucial to define this endpoint at the very end of your API, as it literally accepts every request.

Exception Handling

Grape can be told to rescue all exceptions and return them in the API format.

s Twitter::API < Grape::API
scue_from :all

Grape can also rescue from all exceptions and still use the built-in exception handing. This will give the same behavior as rescue_from :all with the addition that Grape will use the exception handling defined by all Exception classes that inherit Grape::Exceptions::Base.

The intent of this setting is to provide a simple way to cover the most common exceptions and return any unexpected exceptions in the API format.

s Twitter::API < Grape::API
scue_from :grape_exceptions

You can also rescue specific exceptions.

s Twitter::API < Grape::API
scue_from ArgumentError, UserDefinedError

In this case `UserDefinedErrormust be inherited from ``StandardError```.

Notice that you could combine these two approaches (rescuing custom errors takes precedence). For example, it's useful for handling all exceptions except Grape validation errors.

s Twitter::API < Grape::API
scue_from Grape::Exceptions::ValidationErrors do |e|
error!(e, 400)
d

scue_from :all

The error format will match the request format. See “Content-Types” below.

Custom error formatters for existing and additional types can be defined with a proc.

s Twitter::API < Grape::API
ror_formatter :txt, ->(message, backtrace, options, env) {
"error: #{message} from #{backtrace}"


You can also use a module or class.

le CustomFormatter
f self.call(message, backtrace, options, env)
{ message: message, backtrace: backtrace }
d


s Twitter::API < Grape::API
ror_formatter :custom, CustomFormatter

You can rescue all exceptions with a code block. The error! wrapper automatically sets the default error code and content-type.

s Twitter::API < Grape::API
scue_from :all do |e|
error!("rescued from #{e.class.name}")
d

Optionally, you can set the format, status code and headers.

s Twitter::API < Grape::API
rmat :json
scue_from :all do |e|
error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
d

You can also rescue all exceptions with a code block and handle the Rack response at the lowest level.

s Twitter::API < Grape::API
scue_from :all do |e|
Rack::Response.new([ e.message ], 500, { 'Content-type' => 'text/error' }).finish
d

Or rescue specific exceptions.

s Twitter::API < Grape::API
scue_from ArgumentError do |e|
error!("ArgumentError: #{e.message}")
d

scue_from NotImplementedError do |e|
error!("NotImplementedError: #{e.message}")
d

By default, rescue_from will rescue the exceptions listed and all their subclasses.

Assume you have the following exception classes defined.

le APIErrors
ass ParentError < StandardError; end
ass ChildError < ParentError; end

Then the following rescue_from clause will rescue exceptions of type APIErrors::ParentError and its subclasses (in this case APIErrors::ChildError).

ue_from APIErrors::ParentError do |e|
error!({
  error: "#{e.class} error",
  message: e.message
}, e.status)

To only rescue the base exception class, set rescue_subclasses: false. The code below will rescue exceptions of type RuntimeError but not its subclasses.

ue_from RuntimeError, rescue_subclasses: false do |e|
error!({
  status: e.status,
  message: e.message,
  errors: e.errors
}, e.status)

Helpers are also available inside rescue_from.

s Twitter::API < Grape::API
rmat :json
lpers do
def server_error!
  error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
end
d

scue_from :all do |e|
server_error!
d

The rescue_from block must return a Rack::Response object, call error! or re-raise an exception.

The with keyword is available as rescue_from options, it can be passed method name or Proc object.

s Twitter::API < Grape::API
rmat :json
lpers do
def server_error!
  error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
end
d

scue_from :all,          with: :server_error!
scue_from ArgumentError, with: -> { Rack::Response.new('rescued with a method', 400) }

Rescuing exceptions inside namespaces

You could put rescue_from clauses inside a namespace and they will take precedence over ones defined in the root scope:

s Twitter::API < Grape::API
scue_from ArgumentError do |e|
error!("outer")
d

mespace :statuses do
rescue_from ArgumentError do |e|
  error!("inner")
end
get do
  raise ArgumentError.new
end
d

Here 'inner' will be result of handling occured ArgumentError.

Unrescuable Exceptions

Grape::Exceptions::InvalidVersionHeader, which is raised when the version in the request header doesn't match the currently evaluated version for the endpoint, will never be rescued from a rescue_from block (even a rescue_from :all) This is because Grape relies on Rack to catch that error and try the next versioned-route for cases where there exist identical Grape endpoints with different versions.

Rails 3.x

When mounted inside containers, such as Rails 3.x, errors such as “404 Not Found” or “406 Not Acceptable” will likely be handled and rendered by Rails handlers. For instance, accessing a nonexistent route “/api/foo” raises a 404, which inside rails will ultimately be translated to an ActionController::RoutingError, which most likely will get rendered to a HTML error page.

Most APIs will enjoy preventing downstream handlers from handling errors. You may set the :cascade option to false for the entire API or separately on specific version definitions, which will remove the X-Cascade: true header from API responses.

ade false
uby
ion 'v1', using: :header, vendor: 'twitter', cascade: false
Logging

Grape::API provides a logger method which by default will return an instance of the Logger class from Ruby's standard library.

To log messages from within an endpoint, you need to define a helper to make the logger available in the endpoint context.

s API < Grape::API
lpers do
def logger
  API.logger
end
d
st '/statuses' do
# ...
logger.info "#{current_user} has statused"
d

To change the logger level.

s API < Grape::API
lf.logger.level = Logger::INFO

You can also set your own logger.

s MyLogger
f warning(message)
puts "this is a warning: #{message}"
d


s API < Grape::API
gger MyLogger.new
lpers do
def logger
  API.logger
end
d
t '/statuses' do
logger.warning "#{current_user} has statused"
d

For similar to Rails request logging try the grape_logging or grape-middleware-logger gems.

API Formats

Your API can declare which content-types to support by using content_type. If you do not specify any, Grape will support XML, JSON, BINARY, and TXT content-types. The default format is :txt; you can change this with default_format. Essentially, the two APIs below are equivalent.

s Twitter::API < Grape::API
no content_type declarations, so Grape uses the defaults


s Twitter::API < Grape::API
the following declarations are equivalent to the defaults

ntent_type :xml, 'application/xml'
ntent_type :json, 'application/json'
ntent_type :binary, 'application/octet-stream'
ntent_type :txt, 'text/plain'

fault_format :txt

If you declare any content_type whatsoever, the Grape defaults will be overridden. For example, the following API will only support the :xml and :rss content-types, but not :txt, :json, or :binary. Importantly, this means the :txt default format is not supported! So, make sure to set a new default_format.

s Twitter::API < Grape::API
ntent_type :xml, 'application/xml'
ntent_type :rss, 'application/xml+rss'

fault_format :xml

Serialization takes place automatically. For example, you do not have to call to_json in each JSON API endpoint implementation. The response format (and thus the automatic serialization) is determined in the following order:

For example, consider the following API.

s MultipleFormatAPI < Grape::API
ntent_type :xml, 'application/xml'
ntent_type :json, 'application/json'

fault_format :json

t :hello do
{ hello: 'world' }
d

You can override this process explicitly by specifying env['api.format'] in the API itself. For example, the following API will let you upload arbitrary files and return their contents as an attachment with the correct MIME type.

s Twitter::API < Grape::API
st 'attachment' do
filename = params[:file][:filename]
content_type MIME::Types.type_for(filename)[0].to_s
env['api.format'] = :binary # there's no formatter for :binary, data will be returned "as is"
header 'Content-Disposition', "attachment; filename*=UTF-8''#{CGI.escape(filename)}"
params[:file][:tempfile].read
d

You can have your API only respond to a single format with format. If you use this, the API will not respond to file extensions other than specified in format. For example, consider the following API.

s SingleFormatAPI < Grape::API
rmat :json

t :hello do
{ hello: 'world' }
d

The formats apply to parsing, too. The following API will only respond to the JSON content-type and will not parse any other input than application/json, application/x-www-form-urlencoded, multipart/form-data, multipart/related and multipart/mixed. All other requests will fail with an HTTP 406 error code.

s Twitter::API < Grape::API
rmat :json

When the content-type is omitted, Grape will return a 406 error code unless default_format is specified. The following API will try to parse any data without a content-type using a JSON parser.

s Twitter::API < Grape::API
rmat :json
fault_format :json

If you combine format with rescue_from :all, errors will be rendered using the same format. If you do not want this behavior, set the default error formatter with default_error_formatter.

s Twitter::API < Grape::API
rmat :json
ntent_type :txt, 'text/plain'
fault_error_formatter :txt

Custom formatters for existing and additional types can be defined with a proc.

s Twitter::API < Grape::API
ntent_type :xls, 'application/vnd.ms-excel'
rmatter :xls, ->(object, env) { object.to_xls }

You can also use a module or class.

le XlsFormatter
f self.call(object, env)
object.to_xls
d


s Twitter::API < Grape::API
ntent_type :xls, 'application/vnd.ms-excel'
rmatter :xls, XlsFormatter

Built-in formatters are the following.

Response statuses that indicate no content as defined by Rack here will bypass serialization and the body entity - though there should be none - will not be modified.

JSONP

Grape supports JSONP via Rack::JSONP, part of the rack-contrib gem. Add rack-contrib to your Gemfile.

ire 'rack/contrib'

s API < Grape::API
e Rack::JSONP
rmat :json
t '/' do
'Hello World'
d

CORS

Grape supports CORS via Rack::CORS, part of the rack-cors gem. Add rack-cors to your Gemfile, then use the middleware in your config.ru file.

ire 'rack/cors'

Rack::Cors do
low do
origins '*'
resource '*', headers: :any, methods: :get
d


Twitter::API
Content-type

Content-type is set by the formatter. You can override the content-type of the response at runtime by setting the Content-Type header.

s API < Grape::API
t '/home_timeline_js' do
content_type 'application/javascript'
"var statuses = ...;"
d

API Data Formats

Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters section above. It also supports custom data formats. You must declare additional content-types via content_type and optionally supply a parser via parser unless a parser is already available within Grape to enable a custom format. Such a parser can be a function or a class.

With a parser, parsed data is available “as-is” in env['api.request.body']. Without a parser, data is available “as-is” and in env['api.request.input'].

The following example is a trivial parser that will assign any input with the “text/custom” content-type to :value. The parameter will be available via params[:value] inside the API call.

le CustomParser
f self.call(object, env)
{ value: object.to_s }
d

uby
ent_type :txt, 'text/plain'
ent_type :custom, 'text/custom'
er :custom, CustomParser

'value' do
rams[:value]

You can invoke the above API as follows.

 -X PUT -d 'data' 'http://localhost:9292/value' -H Content-Type:text/custom -v

You can disable parsing for a content-type with nil. For example, parser :json, nil will disable JSON parsing altogether. The request data is then available as-is in env['api.request.body'].

JSON and XML Processors

Grape uses JSON and ActiveSupport::XmlMini for JSON and XML parsing by default. It also detects and supports multi_json and multi_xml. Adding those gems to your Gemfile and requiring them will enable them and allow you to swap the JSON and XML back-ends.

RESTful Model Representations

Grape supports a range of ways to present your data with some help from a generic present method, which accepts two arguments: the object to be presented and the options associated with it. The options hash may include :with, which defines the entity to expose.

Grape Entities

Add the grape-entity gem to your Gemfile. Please refer to the grape-entity documentation for more details.

The following example exposes statuses.

le API
dule Entities
class Status < Grape::Entity
  expose :user_name
  expose :text, documentation: { type: 'string', desc: 'Status update text.' }
  expose :ip, if: { type: :full }
  expose :user_type, :user_id, if: ->(status, options) { status.user.public? }
  expose :digest do |status, options|
    Digest::MD5.hexdigest(status.txt)
  end
  expose :replies, using: API::Status, as: :replies
end
d

ass Statuses < Grape::API
version 'v1'

desc 'Statuses index' do
  params: API::Entities::Status.documentation
end
get '/statuses' do
  statuses = Status.all
  type = current_user.admin? ? :full : :default
  present statuses, with: API::Entities::Status, type: type
end
d

You can use entity documentation directly in the params block with using: Entity.documentation.

le API
ass Statuses < Grape::API
version 'v1'

desc 'Create a status'
params do
  requires :all, except: [:ip], using: API::Entities::Status.documentation.except(:id)
end
post '/status' do
  Status.create! params
end
d

You can present with multiple entities using an optional Symbol argument.

t '/statuses' do
statuses = Status.all.page(1).per(20)
present :total_page, 10
present :per_page, 20
present :statuses, statuses, with: API::Entities::Status
d

The response will be


total_page: 10,
per_page: 20,
statuses: []

In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.

s Status
f entity
Entity.new(self)
d

ass Entity < Grape::Entity
expose :text, :user_id
d

If you organize your entities this way, Grape will automatically detect the Entity class and use it to present your models. In this example, if you added present Status.new to your endpoint, Grape will automatically detect that there is a Status::Entity class and use that as the representative entity. This can still be overridden by using the :with option or an explicit represents call.

You can present hash with Grape::Presenters::Presenter to keep things consistent.

'/users' do
esent { id: 10, name: :dgz }, with: Grape::Presenters::Presenter

The response will be


:   10,
me: 'dgz'

It has the same result with

'/users' do
esent :id, 10
esent :name, :dgz

Hypermedia and Roar

You can use Roar to render HAL or Collection+JSON with the help of grape-roar, which defines a custom JSON formatter and enables presenting entities with Grape's present keyword.

Rabl

You can use Rabl templates with the help of the grape-rabl gem, which defines a custom Grape Rabl formatter.

Active Model Serializers

You can use Active Model Serializers serializers with the help of the grape-active_model_serializers gem, which defines a custom Grape AMS formatter.

Sending Raw or No Data

In general, use the binary format to send raw data.

s API < Grape::API
t '/file' do
content_type 'application/octet-stream'
File.binread 'file.bin'
d

You can set the response body explicitly with body.

s API < Grape::API
t '/' do
content_type 'text/plain'
body 'Hello World'
# return value ignored
d

Use body false to return 204 No Content without any data or content-type.

You can also set the response to a file with file.

s API < Grape::API
t '/' do
file '/path/to/file'
d

If you want a file to be streamed using Rack::Chunked, use stream.

s API < Grape::API
t '/' do
stream '/path/to/file'
d

Authentication
Basic and Digest Auth

Grape has built-in Basic and Digest authentication (the given block is executed in the context of the current Endpoint). Authentication applies to the current namespace and any children, but not parents.

_basic do |username, password|
verify user's password here
'test' => 'password1' }[username] == password

uby
_digest({ realm: 'Test Api', opaque: 'app secret' }) do |username|
lookup the user's password here
'user1' => 'password1' }[username]

Register custom middleware for authentication

Grape can use custom Middleware for authentication. How to implement these Middleware have a look at Rack::Auth::Basic or similar implementations.

For registering a Middleware you need the following options:

Example:

e::Middleware::Auth::Strategies.add(:my_auth, AuthMiddleware, ->(options) { [options[:realm]] } )


 :my_auth, { realm: 'Test Api'} do |credentials|
lookup the user's password here
'user1' => 'password1' }[username]

Use warden-oauth2 or rack-oauth2 for OAuth2 support.

Describing and Inspecting an API

Grape routes can be reflected at runtime. This can notably be useful for generating documentation.

Grape exposes arrays of API versions and compiled routes. Each route contains a route_prefix, route_version, route_namespace, route_method, route_path and route_params. You can add custom route settings to the route metadata with route_setting.

s TwitterAPI < Grape::API
rsion 'v1'
sc 'Includes custom settings.'
ute_setting :custom, key: 'value'
t do

d

Examine the routes at runtime.

terAPI::versions # yields [ 'v1', 'v2' ]
terAPI::routes # yields an array of Grape::Route objects
terAPI::routes[0].version # => 'v1'
terAPI::routes[0].description # => 'Includes custom settings.'
terAPI::routes[0].settings[:custom] # => { key: 'value' }

Note that Route#route_xyz methods have been deprecated since 0.15.0.

Please use Route#xyz instead.

Note that difference of Route#options and Route#settings.

The options can be referred from your route, it should be set by specifing key and value on verb methods such as get, post and put. The settings can also be referred from your route, but it should be set by specifing key and value on route_setting.

Current Route and Endpoint

It's possible to retrieve the information about the current route from within an API call with route.

s MyAPI < Grape::API
sc 'Returns a description of a parameter.'
rams do
requires :id, type: Integer, desc: 'Identity.'
d
t 'params/:id' do
route.route_params[params[:id]] # yields the parameter description
d

The current endpoint responding to the request is self within the API block or env['api.endpoint'] elsewhere. The endpoint has some interesting properties, such as source which gives you access to the original code block of the API implementation. This can be particularly useful for building a logger middleware.

s ApiLogger < Grape::Middleware::Base
f before
file = env['api.endpoint'].source.source_location[0]
line = env['api.endpoint'].source.source_location[1]
logger.debug "[api] #{file}:#{line}"
d

Before and After

Blocks can be executed before or after every API call, using before, after, before_validation and after_validation.

Before and after callbacks execute in the following order:

  1. before
  2. before_validation
  3. validations
  4. after_validation
  5. the API call
  6. after

Steps 4, 5 and 6 only happen if validation succeeds.

If a request for a resource is made with an unsupported HTTP method (returning HTTP 405) only before callbacks will be executed. The remaining callbacks will be bypassed.

If a request for a resource is made that triggers the built-in OPTIONS handler, only before and after callbacks will be executed. The remaining callbacks will be bypassed.

Examples

Using a simple before block to set a header

re do
ader 'X-Robots-Tag', 'noindex'

Namespaces

Callbacks apply to each API call within and below the current namespace:

s MyAPI < Grape::API
t '/' do
"root - #{@blah}"
d

mespace :foo do
before do
  @blah = 'blah'
end

get '/' do
  "root - foo - #{@blah}"
end

namespace :bar do
  get '/' do
    "root - foo - bar - #{@blah}"
  end
end
d

The behaviour is then:

/           # 'root - '
/foo        # 'root - foo - blah'
/foo/bar    # 'root - foo - bar - blah'

Params on a namespace (or whichever alias you are using) will also be available when using before_validation or after_validation:

s MyAPI < Grape::API
rams do
requires :blah, type: Integer
d
source ':blah' do
after_validation do
  # if we reach this point validations will have passed
  @blah = declared(params, include_missing: false)[:blah]
end

get '/' do
  @blah.class
end
d

The behaviour is then:

/123        # 'Integer'
/foo        # 400 error - 'blah is invalid'

Versioning

When a callback is defined within a version block, it's only called for the routes defined in that block.

s Test < Grape::API
source :foo do
version 'v1', :using => :path do
  before do
    @output ||= 'v1-'
  end
  get '/' do
    @output += 'hello'
  end
end

version 'v2', :using => :path do
  before do
    @output ||= 'v2-'
  end
  get '/' do
    @output += 'hello'
  end
end
d

The behaviour is then:

/foo/v1       # 'v1-hello'
/foo/v2       # 'v2-hello'

Altering Responses

Using present in any callback allows you to add data to a response:

s MyAPI < Grape::API
rmat :json

ter_validation do
present :name, params[:name] if params[:name]
d

t '/greeting' do
present :greeting, 'Hello!'
d

The behaviour is then:

/greeting              # {"greeting":"Hello!"}
/greeting?name=Alan    # {"name":"Alan","greeting":"Hello!"}

Instead of altering a response, you can also terminate and rewrite it from any callback using error!, including after. This will cause all subsequent steps in the process to not be called. This includes the actual api call and any callbacks

Anchoring

Grape by default anchors all request paths, which means that the request URL should match from start to end to match, otherwise a 404 Not Found is returned. However, this is sometimes not what you want, because it is not always known upfront what can be expected from the call. This is because Rack-mount by default anchors requests to match from the start to the end, or not at all. Rails solves this problem by using a anchor: false option in your routes. In Grape this option can be used as well when a method is defined.

For instance when your API needs to get part of an URL, for instance:

s TwitterAPI < Grape::API
mespace :statuses do
get '/(*:status)', anchor: false do

end
d

This will match all paths starting with '/statuses/'. There is one caveat though: the params[:status] parameter only holds the first part of the request url. Luckily this can be circumvented by using the described above syntax for path specification and using the PATH_INFO Rack environment variable, using env['PATH_INFO']. This will hold everything that comes after the '/statuses/' part.

Using Custom Middleware
Grape Middleware

You can make a custom middleware by using Grape::Middleware::Base. It's inherited from some grape official middlewares in fact.

For example, you can write a middleware to log application exception.

s LoggingError < Grape::Middleware::Base
f after
return unless @app_response && @app_response[0] == 500
env['rack.logger'].error("Raised error on #{env['PATH_INFO']}")
d

Your middleware can overwrite application response as follows, except error case.

s Overwriter < Grape::Middleware::Base
f after
[200, { 'Content-Type' => 'text/plain' }, ['Overwritten.']]
d

You can add your custom middleware with use, that push the middleware onto the stack, and you can also control where the middleware is inserted using insert, insert_before and insert_after.

s CustomOverwriter < Grape::Middleware::Base
f after
[200, { 'Content-Type' => 'text/plain' }, [@options[:message]]]
d



s API < Grape::API
e Overwriter
sert_before Overwriter, CustomOverwriter, message: 'Overwritten again.'
sert 0, CustomOverwriter, message: 'Overwrites all other middleware.'

t '/' do
d

Rails Middleware

Note that when you're using Grape mounted on Rails you don't have to use Rails middleware because it's already included into your middleware stack. You only have to implement the helpers to access the specific env variable.

Remote IP

By default you can access remote IP with request.ip. This is the remote IP address implemented by Rack. Sometimes it is desirable to get the remote IP Rails-style with ActionDispatch::RemoteIp.

Add gem 'actionpack' to your Gemfile and require 'action_dispatch/middleware/remote_ip.rb'. Use the middleware in your API and expose a client_ip helper. See this documentation for additional options.

s API < Grape::API
e ActionDispatch::RemoteIp

lpers do
def client_ip
  env['action_dispatch.remote_ip'].to_s
end
d

t :remote_ip do
{ ip: client_ip }
d

Writing Tests
Writing Tests with Rack

Use rack-test and define your API as app.

RSpec

You can test a Grape API with RSpec by making HTTP requests and examining the response.

ire 'spec_helper'

ribe Twitter::API do
clude Rack::Test::Methods

f app
Twitter::API
d

ntext 'GET /api/statuses/public_timeline' do
it 'returns an empty array of statuses' do
  get '/api/statuses/public_timeline'
  expect(last_response.status).to eq(200)
  expect(JSON.parse(last_response.body)).to eq []
end
d
ntext 'GET /api/statuses/:id' do
it 'returns a status by id' do
  status = Status.create!
  get "/api/statuses/#{status.id}"
  expect(last_response.body).to eq status.to_json
end
d

There's no standard way of sending arrays of objects via an HTTP GET, so POST JSON data and specify the correct content-type.

ribe Twitter::API do
ntext 'POST /api/statuses' do
it 'creates many statuses' do
  statuses = [{ text: '...' }, { text: '...'}]
  post '/api/statuses', statuses.to_json, 'CONTENT_TYPE' => 'application/json'
  expect(last_response.body).to eq 201
end
d

Airborne

You can test with other RSpec-based frameworks, including Airborne, which uses rack-test to make requests.

ire 'airborne'

orne.configure do |config|
nfig.rack_app = Twitter::API


ribe Twitter::API do
ntext 'GET /api/statuses/:id' do
it 'returns a status by id' do
  status = Status.create!
  get "/api/statuses/#{status.id}"
  expect_json(status.as_json)
end
d

MiniTest
ire 'test_helper'

s Twitter::APITest < MiniTest::Test
clude Rack::Test::Methods

f app
Twitter::API
d

f test_get_api_statuses_public_timeline_returns_an_empty_array_of_statuses
get '/api/statuses/public_timeline'
assert last_response.ok?
assert_equal [], JSON.parse(last_response.body)
d

f test_get_api_statuses_id_returns_a_status_by_id
status = Status.create!
get "/api/statuses/#{status.id}"
assert_equal status.to_json, last_response.body
d

Writing Tests with Rails
RSpec
ribe Twitter::API do
ntext 'GET /api/statuses/public_timeline' do
it 'returns an empty array of statuses' do
  get '/api/statuses/public_timeline'
  expect(response.status).to eq(200)
  expect(JSON.parse(response.body)).to eq []
end
d
ntext 'GET /api/statuses/:id' do
it 'returns a status by id' do
  status = Status.create!
  get "/api/statuses/#{status.id}"
  expect(response.body).to eq status.to_json
end
d

In Rails, HTTP request tests would go into the spec/requests group. You may want your API code to go into app/api - you can match that layout under spec by adding the following in spec/rails_helper.rb.

c.configure do |config|
nfig.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/

MiniTest
s Twitter::APITest < ActiveSupport::TestCase
clude Rack::Test::Methods

f app
Rails.application
d

st 'GET /api/statuses/public_timeline returns an empty array of statuses' do
get '/api/statuses/public_timeline'
assert last_response.ok?
assert_equal [], JSON.parse(last_response.body)
d

st 'GET /api/statuses/:id returns a status by id' do
status = Status.create!
get "/api/statuses/#{status.id}"
assert_equal status.to_json, last_response.body
d

Stubbing Helpers

Because helpers are mixed in based on the context when an endpoint is defined, it can be difficult to stub or mock them for testing. The Grape::Endpoint.before_each method can help by allowing you to define behavior on the endpoint that will run before every request.

ribe 'an endpoint that needs helpers stubbed' do
fore do
Grape::Endpoint.before_each do |endpoint|
  allow(endpoint).to receive(:helper_name).and_return('desired_value')
end
d

ter do
Grape::Endpoint.before_each nil
d

 'stubs the helper' do
# ...
d

Reloading API Changes in Development
Reloading in Rack Applications

Use grape-reload.

Reloading in Rails Applications

Add API paths to config/application.rb.

to-load API and its subdirectories
ig.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
ig.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

Create config/initializers/reload_api.rb.

ails.env.development?
tiveSupport::Dependencies.explicitly_unloadable_constants << 'Twitter::API'

i_files = Dir[Rails.root.join('app', 'api', '**', '*.rb')]
i_reloader = ActiveSupport::FileUpdateChecker.new(api_files) do
Rails.application.reload_routes!
d
tionDispatch::Callbacks.to_prepare do
api_reloader.execute_if_updated
d

See StackOverflow #3282655 for more information.

Performance Monitoring
Active Support Instrumentation

Grape has built-in support for ActiveSupport::Notifications which provides simple hook points to instrument key parts of your application.

The following are currently supported:

endpoint_run.grape

The main execution of an endpoint, includes filters and rendering.

endpoint_render.grape

The execution of the main content block of the endpoint.

endpoint_run_filters.grape endpoint_run_validators.grape

The execution of validators.

See the ActiveSupport::Notifications documentation for information on how to subscribe to these events.

Monitoring Products

Grape integrates with following third-party tools:

Contributing to Grape

Grape is work of hundreds of contributors. You're encouraged to submit pull requests, propose features and discuss issues.

See CONTRIBUTING.

License

MIT License. See LICENSE for details.

Copyright

Copyright (c) 2010-2017 Michael Bleigh, and Intridea, Inc.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.