Skip to content
This repository was archived by the owner on Mar 5, 2019. It is now read-only.

Repository files navigation

grape logo

Gem VersionBuild StatusDependency StatusCode ClimateInline docs

Table of Contents

What is Grape?

Grape is a REST-like API micro-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 0.10.2. Please read UPGRADING when upgrading from a previous version. The current stable release is 0.10.1.

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.

moduleTwitterclassAPI < Grape::APIversion'v1',using: :header,vendor: 'twitter'format:jsonprefix:apihelpersdodefcurrent_user@current_user ||= User.authorize!(env)enddefauthenticate!error!('401 Unauthorized',401)unlesscurrent_userendendresource:statusesdodesc"Return a public timeline."get:public_timelinedoStatus.limit(20)enddesc"Return a personal timeline."get:home_timelinedoauthenticate!current_user.statuses.limit(20)enddesc"Return a status."paramsdorequires:id,type: Integer,desc: "Status id."endroute_param:iddogetdoStatus.find(params[:id])endenddesc"Create a status."paramsdorequires:status,type: String,desc: "Your status."endpostdoauthenticate!Status.create!({user: current_user,text: params[:status]})enddesc"Update a status."paramsdorequires:id,type: String,desc: "Status ID."requires:status,type: String,desc: "Your status."endput':id'doauthenticate!current_user.statuses.find(params[:id]).update({user: current_user,text: params[:status]})enddesc"Delete a status."paramsdorequires:id,type: String,desc: "Status ID."enddelete':id'doauthenticate!current_user.statuses.find(params[:id]).destroyendendendend

Mounting

Rack

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

runTwitter::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.:

useActiveRecord::ConnectionAdapters::ConnectionManagementrunTwitter::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:

# Example config.rurequire'sinatra'require'grape'classAPI < Grape::APIget:hellodo{hello: "world"}endendclassWeb < Sinatra::Baseget'/'do"Hello world."endenduseRack::Session::CookierunRack::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:

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

Modify config/routes:

mountTwitter::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_railsgem. This gem disables the security feature of strong_params at the model layer, allowing you the use of Grape's own params validation instead.

# Gemfilegem"hashie_rails"

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.

classTwitter::API < Grape::APImountTwitter::APIv1mountTwitter::APIv2end

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

classTwitter::API < Grape::APImountTwitter::APIv1=>'/v1'end

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

version'v1',using: :path

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

curl -H http://localhost:9292/v1/statuses/public_timeline

Header

version'v1',using: :header,vendor: 'twitter'

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.

HTTP Status Code

By default Grape returns a 200 status code for GET-Requests and 201 for POST-Requests. You can use status to query and set the actual HTTP Status Code

postdostatus202ifstatus == 200# do some thingendend

Accept-Version Header

version'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.

Param

version'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 -H 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.

version'v1',using: :param,parameter: "v"
curl -H http://localhost:9292/statuses/public_timeline?v=v1

Describing Methods

You can add a description to API methods and namespaces.

desc"Returns your public timeline."dodetail'more details'paramsAPI::Entities::Status.documentationsuccessAPI::Entities::Entityfailure[[401,'Unauthorized',"Entities::Error"]]named'My named route'headers[XAuthToken: {description: 'Valdates your identity',required: true},XOptionalHeader: {description: 'Not really needed',required: false}]endget:public_timelinedoStatus.limit(20)end
  • detail: A more enhanced description
  • params: Define parameters directly from an Entity
  • success: (former entity) The Entity to be used to present by default this route
  • failure: (former http_codes) A definition of the used failure HTTP Codes and Entities
  • named: A helper to give a route a name and find it with this name in the documentation Hash
  • headers: A definition of the used Headers

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.

get:public_timelinedoStatus.order(params[:sort_by])end

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

The request:

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

The Grape endpoint:

post'/statuses'doStatus.create!(text: params[:text])end

Multipart POSTs and PUTs are supported as well.

The request:

curl --form image_file=@image.jpg http://localhost:9292/upload

The Grape endpoint:

post"upload"do# file in params[:image_file]end

In the case of conflict between either of:

  • route string parameters
  • GET, POST and PUT parameters
  • the contents of the request body on POST and PUT

route string parameters will have precedence.

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. Let's have the following api:

format:jsonpost'users/signup'do{"declared_params"=>declared(params)}end

If we do not specify any params, declared will return an empty Hashie::Mash instance.

Request

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

Response

{
"declared_params": {}
}

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

format:jsonparamsdorequires:user,type: Hashdorequires:first_name,type: Stringrequires:last_name,type: Stringendendpost'users/signup'do{"declared_params"=>declared(params)}end

Request

curl -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

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

Returned hash is a Hashie::Mash instance so you can access parameters via dot notation:

declared(params).user == declared(params)["user"]

Include missing

By default declared(params) returns parameters that has nil value. If you want to return only the parameters that have any value, you can use the include_missing option. By default it is true. Let's have the following api:

format:jsonparamsdorequires:first_name,type: Stringoptional:last_name,type: Stringendpost'users/signup'do{"declared_params"=>declared(params,include_missing: false)}end

Request

curl -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

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

Response with include_missing:true

{
"declared_params": {
"first_name": "first name",
"last_name": null
}
}

It also works on nested hashes:

format:jsonparamsdorequires:user,:type=>Hashdorequires:first_name,type: Stringoptional:last_name,type: Stringrequires:address,:type=>Hashdorequires:city,type: Stringoptional:region,type: Stringendendendpost'users/signup'do{"declared_params"=>declared(params,include_missing: false)}end

Request

curl -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

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

Response with include_missing:true

{
"declared_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

curl -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

{
"declared_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.

paramsdorequires:id,type: Integeroptional:text,type: String,regexp: /^[a-z]+$/group:mediadorequires:urlendoptional:audiodorequires:format,type: Symbol,values: [:mp3,:wav,:aac,:ogg],default: :mp3endmutually_exclusive:media,:audioendput':id'do# params[:id] is an Integerend

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.

paramsdooptional:color,type: String,default: 'blue'optional:random_number,type: Integer,default: ->{Random.rand(1..100)}optional:non_random_number,type: Integer,default: Random.rand(1..100)end

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.

paramsdooptional:color,type: String,default: 'blue',values: ['red','green']end

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

paramsdooptional:color,type: String,default: 'blue',values: ['blue','red','green']end

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.

paramsdooptional:preferences,type: Arraydorequires:keyrequires:valueendrequires:name,type: Hashdorequires:first_namerequires:last_nameendend

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.

paramsdorequires:username,allow_blank: falseoptional:first_name,allow_blank: falseend

values

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

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.

paramsdorequires:status,type: Symbol,values: [:not_started,:processing,:done]optional:numbers,type: Array[Integer],default: 1,values: [1,2,3,5,8]end

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

paramsdorequires:latitude,type: Float,values: -90.0..+90.0requires:longitude,type: Float,values: -180.0..+180.0optional:letters,type: Array[String],values: 'a'..'z'end

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

paramsdorequires:invalid1,type: Float,values: 0..10# 0.kind_of?(Float) => falseoptional:invalid2,values: 0..10.0# 10.0.kind_of?(0.class) => falseend

The :values option can also be supplied with a Proc, evaluated lazily with each request. For example, given a status model you may want to restrict by hashtags that you have previously defined in the HashTag model.

paramsdorequires:hashtag,type: String,values: ->{Hashtag.all.map(&:tag)}end

regexp

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

paramsdorequires:email,regexp: /.+@.+/end

mutually_exclusive

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

paramsdooptional:beeroptional:winemutually_exclusive:beer,:wineend

Multiple sets can be defined:

paramsdooptional:beeroptional:winemutually_exclusive:beer,:wineoptional:scotchoptional:aquavitmutually_exclusive:scotch,:aquavitend

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.

paramsdooptional:beeroptional:wineexactly_one_of:beer,:wineend

at_least_one_of

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

paramsdooptional:beeroptional:wineoptional:juiceat_least_one_of:beer,:wine,:juiceend

all_or_none_of

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

paramsdooptional:beeroptional:wineoptional:juiceall_or_none_of:beer,:wine,:juiceend

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.

paramsdorequires:fooddooptional:meatoptional:fishoptional:riceat_least_one_of:meat,:fish,:riceendgroup:drinkdooptional:beeroptional:wineoptional:juiceexactly_one_of:beer,:wine,:juiceendoptional:dessertdooptional:cakeoptional:icecreammutually_exclusive:cake,:icecreamendoptional:recipedooptional:oiloptional:meatall_or_none_of:oil,:meatendend

Namespace Validation and Coercion

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

namespace:statusesdoparamsdorequires:user_id,type: Integer,desc: "A user ID."endnamespace":user_id"dodesc"Retrieve a user's status."paramsdorequires:status_id,type: Integer,desc: "A status ID."endget":status_id"doUser.find(params[:user_id]).statuses.find(params[:status_id])endendend

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.

namespace:statusesdoroute_param:iddodesc"Returns all replies for a status."get'replies'doStatus.find(params[:id]).repliesenddesc"Returns a status."getdoStatus.find(params[:id])endendend

Custom Validators

classAlphaNumeric < Grape::Validations::Basedefvalidate_param!(attr_name,params)unlessparams[attr_name] =~ /^[[:alnum:]]+$/raiseGrape::Exceptions::Validation,params: [@scope.full_name(attr_name)],message: "must consist of alpha-numeric characters"endendend
paramsdorequires:text,alpha_numeric: trueend

You can also create custom classes that take parameters.

classLength < Grape::Validations::Basedefvalidate_param!(attr_name,params)unlessparams[attr_name].length <= @optionraiseGrape::Exceptions::Validation,params: [@scope.full_name(attr_name)],message: "must be at the most #{@option} characters long"endendend
paramsdorequires:text,length: 140end

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.

paramsdooptional:beeroptional:wineoptional:juiceexactly_one_of:beer,:wine,:juiceend

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"]}].

format:jsonsubject.rescue_fromGrape::Exceptions::ValidationErrorsdo |e|
rack_responsee.to_json,400end

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.

Headers

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

getdoerror!('Unauthorized',401)unlessheaders['Secret-Password'] == 'swordfish'end
getdoerror!('Unauthorized',401)unlessenv['HTTP_SECRET_PASSWORD'] == 'swordfish'end

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

header'X-Robots-Tag','noindex'

When raising error!, pass additional headers as arguments.

error!'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.

get':id',requirements: {id: /[0-9]*/}doStatus.find(params[:id])endnamespace:outer,requirements: {id: /[0-9]*/}doget:iddoendget":id/edit"doendend

Helpers

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

moduleStatusHelpersdefuser_info(user)"#{user} has statused #{user.statuses} status(s)"endendclassAPI < Grape::API# define helpers with a blockhelpersdodefcurrent_userUser.find(params[:user_id])endend# or mix in a modulehelpersStatusHelpersget'info'do# helpers available in your endpoint and filtersuser_info(current_user)endend

You can define reusable params using helpers.

classAPI < Grape::APIhelpersdoparams:paginationdooptional:page,type: Integeroptional:per_page,type: Integerendenddesc"Get collection"paramsdouse:pagination# aliases: includes, use_scopeendgetdoCollection.page(params[:page]).per(params[:per_page])endend

You can also define reusable params using shared helpers.

moduleSharedParamsextendGrape::API::Helpersparams:perioddooptional:start_dateoptional:end_dateendparams:paginationdooptional:page,type: Integeroptional:per_page,type: IntegerendendclassAPI < Grape::APIhelpersSharedParamsdesc"Get collection."paramsdouse:period,:paginationendgetdoCollection.from(params[:start_date]).to(params[:end_date]).page(params[:page]).per(params[:per_page])endend

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.

moduleSharedParamsextendGrape::API::Helpersparams:orderdo |options|
optional:order_by,type:Symbol,values:options[:order_by],default:options[:default_order_by]optional:order,type:Symbol,values:%i(ascdesc),default:options[:default_order]endendclassAPI < Grape::APIhelpersSharedParamsdesc"Get a sorted collection."paramsdouse:order,order_by:%i(idcreated_at),default_order_by: :created_at,default_order: :ascendgetdoCollection.send(params[:order],params[:order_by])endend

Parameter Documentation

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

paramsdooptional:first_name,type: String,documentation: {example: 'Jim'}requires:last_name,type: String,documentation: {example: 'Smith'}end

Cookies

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

classAPI < Grape::APIget'status_count'docookies[:status_count] ||= 0cookies[:status_count] += 1{status_count: cookies[:status_count]}enddelete'status_count'do{status_count: cookies.delete(:status_count)}endend

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

cookies[:status_count]={value: 0,expires: Time.tomorrow,domain: '.twitter.com',path: '/'}cookies[:status_count][:value] +=1

Delete a cookie with delete.

cookies.delete:status_count

Specify an optional path.

cookies.delete:status_count,path: '/'

Redirecting

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

redirect'/statuses'
redirect'/statuses',permanent: true

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!.

classAPI < Grape::APIdo_not_route_head!get'/example'do# only responds to GETendend

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.

classAPI < Grape::APIget'/rt_count'do{rt_count: current_user.rt_count}endparamsdorequires:value,type: Integer,desc: 'Value to add to the rt count.'endput'/rt_count'docurrent_user.rt_count += params[:value].to_i{rt_count: current_user.rt_count}endend
curl -v -X OPTIONS http://localhost:3000/rt_count
> OPTIONS /rt_count HTTP/1.1
>< HTTP/1.1 204 No Content
< Allow: 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.

curl -X DELETE -v http://localhost:3000/rt_count/
> DELETE /rt_count/ HTTP/1.1
> Host: localhost:3000
>< HTTP/1.1 405 Method Not Allowed
< Allow: OPTIONS, GET, PUT

Raising Exceptions

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

error!'Access Denied',401

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

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

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

moduleAPIclassError < Grape::Entityexpose:codeexpose:messageendend

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

desc 'My Route' do
failure [[408, 'Unauthorized', API::Error]]
end
error!({ message: 'Unauthorized' }, 408)

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

desc'My Route'dofailure[[408,'Unauthorized']]enderror!({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.

classAPI < Grape::APIdefault_error_status400get'/example'doerror!"This should have http status code 400"endend

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:

route:any,'*path'doerror!# or something elseend

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.

classTwitter::API < Grape::APIrescue_from:allend

You can also rescue specific exceptions.

classTwitter::API < Grape::APIrescue_fromArgumentError,UserDefinedErrorend

In this case UserDefinedError must be inherited from StandardError.

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.

classTwitter::API < Grape::APIerror_formatter:txt,lambda{ |message,backtrace,options,env|
"error: #{message} from #{backtrace}"}end

You can also use a module or class.

moduleCustomFormatterdefself.call(message,backtrace,options,env){message: message,backtrace: backtrace}endendclassTwitter::API < Grape::APIerror_formatter:custom,CustomFormatterend

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

classTwitter::API < Grape::APIrescue_from:alldo |e|
error_response({message: "rescued from #{e.class.name}"})endend

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

classTwitter::API < Grape::APIrescue_from:alldo |e|
Rack::Response.new([e.message],500,{"Content-type"=>"text/error"}).finishendend

Or rescue specific exceptions.

classTwitter::API < Grape::APIrescue_fromArgumentErrordo |e|
Rack::Response.new(["ArgumentError: #{e.message}"],500).finishendrescue_fromNotImplementedErrordo |e|
Rack::Response.new(["NotImplementedError: #{e.message}"],500).finishendend

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

Assume you have the following exception classes defined.

moduleAPIErrorsclassParentError < StandardError;endclassChildError < ParentError;endend

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

rescue_fromAPIErrors::ParentErrordo |e|
Rack::Response.new({error: "#{e.class} error",message: e.message}.to_json,e.status).finishend

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

rescue_fromRuntimeError,rescue_subclasses: falsedo |e|
Rack::Response.new({status: e.status,message: e.message,errors: e.errors}.to_json,e.status).finishend

Rails 3.x

When mounted inside containers, such as Rails 3.x, errors like "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.

cascadefalse
version'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.

classAPI < Grape::APIhelpersdodefloggerAPI.loggerendendpost'/statuses'do# ...logger.info"#{current_user} has statused"endend

You can also set your own logger.

classMyLoggerdefwarning(message)puts"this is a warning: #{message}"endendclassAPI < Grape::APIloggerMyLogger.newhelpersdodefloggerAPI.loggerendendget'/statuses'dologger.warning"#{current_user} has statused"endend

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.

classTwitter::API < Grape::API# no content_type declarations, so Grape uses the defaultsendclassTwitter::API < Grape::API# the following declarations are equivalent to the defaultscontent_type:xml,'application/xml'content_type:json,'application/json'content_type:binary,'application/octet-stream'content_type:txt,'text/plain'default_format:txtend

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.

classTwitter::API < Grape::APIcontent_type:xml,'application/xml'content_type:rss,'application/xml+rss'default_format:xmlend

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:

  • Use the file extension, if specified. If the file is .json, choose the JSON format.
  • Use the value of the format parameter in the query string, if specified.
  • Use the format set by the format option, if specified.
  • Attempt to find an acceptable format from the Accept header.
  • Use the default format, if specified by the default_format option.
  • Default to :txt.

For example, consider the following API.

classMultipleFormatAPI < Grape::APIcontent_type:xml,'application/xml'content_type:json,'application/json'default_format:jsonget:hellodo{hello: 'world'}endend
  • GET /hello (with an Accept: */* header) does not have an extension or a format parameter, so it will respond with JSON (the default format).
  • GET /hello.xml has a recognized extension, so it will respond with XML.
  • GET /hello?format=xml has a recognized format parameter, so it will respond with XML.
  • GET /hello.xml?format=json has a recognized extension (which takes precedence over the format parameter), so it will respond with XML.
  • GET /hello.xls (with an Accept: */* header) has an extension, but that extension is not recognized, so it will respond with JSON (the default format).
  • GET /hello.xls with an Accept: application/xml header has an unrecognized extension, but the Accept header corresponds to a recognized format, so it will respond with XML.
  • GET /hello.xls with an Accept: text/plain header has an unrecognized extension and an unrecognized Accept header, so it will respond with JSON (the default format).

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.

classTwitter::API < Grape::APIpost"attachment"dofilename=params[:file][:filename]content_typeMIME::Types.type_for(filename)[0].to_senv['api.format']=:binary# there's no formatter for :binary, data will be returned "as is"header"Content-Disposition","attachment; filename*=UTF-8''#{URI.escape(filename)}"params[:file][:tempfile].readendend

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. For example, consider the following API.

classSingleFormatAPI < Grape::APIformat:jsonget:hellodo{hello: 'world'}endend
  • GET /hello will respond with JSON.
  • GET /hello.xml, GET /hello.json, GET /hello.foobar, or any other extension will respond with an HTTP 404 error code.
  • GET /hello?format=xml will respond with an HTTP 406 error code, because the XML format specified by the request parameter is not supported.
  • GET /hello with an Accept: application/xml header will still respond with JSON, since it could not negotiate a recognized content-type from the headers and JSON is the effective default.

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.

classTwitter::API < Grape::APIformat:jsonend

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.

classTwitter::API < Grape::APIformat:jsondefault_format:jsonend

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.

classTwitter::API < Grape::APIformat:jsoncontent_type:txt,"text/plain"default_error_formatter:txtend

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

classTwitter::API < Grape::APIcontent_type:xls,"application/vnd.ms-excel"formatter:xls,lambda{ |object,env| object.to_xls}end

You can also use a module or class.

moduleXlsFormatterdefself.call(object,env)object.to_xlsendendclassTwitter::API < Grape::APIcontent_type:xls,"application/vnd.ms-excel"formatter:xls,XlsFormatterend

Built-in formatters are the following.

  • :json: use object's to_json when available, otherwise call MultiJson.dump
  • :xml: use object's to_xml when available, usually via MultiXml, otherwise call to_s
  • :txt: use object's to_txt when available, otherwise to_s
  • :serializable_hash: use object's serializable_hash when available, otherwise fallback to :json
  • :binary: data will be returned "as is"

JSONP

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

require'rack/contrib'classAPI < Grape::APIuseRack::JSONPformat:jsonget'/'do'Hello World'endend

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.

require'rack/cors'useRack::Corsdoallowdoorigins'*'resource'*',headers: :any,methods: :getendendrunTwitter::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.

classAPI < Grape::APIget'/home_timeline_js'docontent_type"application/javascript""var statuses = ...;"endend

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.

moduleCustomParserdefself.call(object,env){value: object.to_s}endend
content_type:txt,"text/plain"content_type:custom,"text/custom"parser:custom,CustomParserput"value"doparams[:value]end

You can invoke the above API as follows.

curl -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'].

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.

moduleAPImoduleEntitiesclassStatus < Grape::Entityexpose:user_nameexpose:text,documentation: {type: "string",desc: "Status update text."}expose:ip,if: {type: :full}expose:user_type,:user_id,if: lambda{ |status,options| status.user.public?}expose:digest{ |status,options| Digest::MD5.hexdigest(status.txt)}expose:replies,using: API::Status,as: :repliesendendclassStatuses < Grape::APIversion'v1'desc'Statuses index'doparams: API::Entities::Status.documentationendget'/statuses'dostatuses=Status.alltype=current_user.admin? ? :full : :defaultpresentstatuses,with: API::Entities::Status,type: typeendendend

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

moduleAPIclassStatuses < Grape::APIversion'v1'desc'Create a status'paramsdorequires:all,except: [:ip],using: API::Entities::Status.documentation.except(:id)endpost'/status'doStatus.create!paramsendendend

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

get'/statuses'dostatuses=Status.all.page(1).per(20)present:total_page,10present:per_page,20present:statuses,statuses,with: API::Entities::Statusend

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.

classStatusdefentityEntity.new(self)endclassEntity < Grape::Entityexpose:text,:user_idendend

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.

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.

classAPI < Grape::APIget'/file'docontent_type'application/octet-stream'File.binread'file.bin'endend

You can also set the response body explicitly with body.

classAPI < Grape::APIget'/'docontent_type'text/plain'body'Hello World'# return value ignoredendend

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

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.

http_basicdo |username,password|
# verify user's password here{'test'=>'password1'}[username] == passwordend
http_digest({realm: 'Test Api',opaque: 'app secret'})do |username|
# lookup the user's password here{'user1'=>'password1'}[username]end

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:

  • label - the name for your authenticator to use it later
  • MiddlewareClass - the MiddlewareClass to use for authentication
  • option_lookup_proc - A Proc with one Argument to lookup the options at runtime (return value is an Array as Paramter for the Middleware).

Example:

Grape::Middleware::Auth::Strategies.add(:my_auth,AuthMiddleware,->(options){[options[:realm]]})auth:my_auth,{realm: 'Test Api'}do |credentials|
# lookup the user's password here{'user1'=>'password1'}[username]end

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.

classTwitterAPI < Grape::APIversion'v1'desc"Includes custom settings."route_setting:custom,key: 'value'getdoendend

Examine the routes at runtime.

TwitterAPI::versions# yields [ 'v1', 'v2' ]TwitterAPI::routes# yields an array of Grape::Route objectsTwitterAPI::routes[0].route_version# => 'v1'TwitterAPI::routes[0].route_description# => 'Includes custom settings.'TwitterAPI::routes[0].route_settings[:custom]# => { key: 'value' }

Current Route and Endpoint

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

classMyAPI < Grape::APIdesc"Returns a description of a parameter."paramsdorequires:id,type: Integer,desc: "Identity."endget"params/:id"doroute.route_params[params[:id]]# yields the parameter descriptionendend

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.

classApiLogger < Grape::Middleware::Basedefbeforefile=env['api.endpoint'].source.source_location[0]line=env['api.endpoint'].source.source_location[1]logger.debug"[api] #{file}:#{line}"endend

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.

E.g. using before:

beforedoheader"X-Robots-Tag","noindex"end

The block applies to every API call within and below the current namespace:

classMyAPI < Grape::APIget'/'do"root - #{@blah}"endnamespace:foodobeforedo@blah='blah'endget'/'do"root - foo - #{@blah}"endnamespace:bardoget'/'do"root - foo - bar - #{@blah}"endendendend

The behaviour is then:

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

Params on a namespace (or whatever alias you are using) also work when using before_validation or after_validation:

classMyAPI < Grape::APIparamsdorequires:blah,type: Integerendresource':blah'doafter_validationdo# if we reach this point validations will have passed@blah=declared(params,include_missing: false)[:blah]endget'/'do@blah.classendendend

The behaviour is then:

GET /123 # 'Fixnum'
GET /foo # 400 error - 'blah is invalid'

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

classTest < Grape::APIresource:foodoversion'v1',:using=>:pathdobeforedo@output ||= 'v1-'endget'/'do@output += 'hello'endendversion'v2',:using=>:pathdobeforedo@output ||= 'v2-'endget'/'do@output += 'hello'endendendend

The behaviour is then:

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

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:

classTwitterAPI < Grape::APInamespace:statusesdoget'/(*:status)',anchor: falsedoendendend

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

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.

classAPI < Grape::APIuseActionDispatch::RemoteIphelpersdodefclient_ipenv["action_dispatch.remote_ip"].to_sendendget:remote_ipdo{ip: client_ip}endend

Writing Tests

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

Writing Tests with Rack

Use rack-test and define your API as app.

RSpec

require'spec_helper'describeTwitter::APIdoincludeRack::Test::MethodsdefappTwitter::APIenddescribeTwitter::APIdodescribe"GET /api/statuses/public_timeline"doit"returns an empty array of statuses"doget"/api/statuses/public_timeline"expect(last_response.status).toeq(200)expect(JSON.parse(last_response.body)).toeq[]endenddescribe"GET /api/statuses/:id"doit"returns a status by id"dostatus=Status.create!get"/api/statuses/#{status.id}"expect(last_response.body).toeqstatus.to_jsonendendendend

MiniTest

require"test_helper"classTwitter::APITest < MiniTest::Unit::TestCaseincludeRack::Test::MethodsdefappTwitter::APIenddeftest_get_api_statuses_public_timeline_returns_an_empty_array_of_statusesget"/api/statuses/public_timeline"assertlast_response.ok?assert_equalJSON.parse(last_response.body),[]enddeftest_get_api_statuses_id_returns_a_status_by_idstatus=Status.create!get"/api/statuses/#{status.id}"assert_equallast_response.body,status.to_jsonendend

Writing Tests with Rails

RSpec

describeTwitter::APIdodescribe"GET /api/statuses/public_timeline"doit"returns an empty array of statuses"doget"/api/statuses/public_timeline"expect(response.status).toeq(200)expect(JSON.parse(response.body)).toeq[]endenddescribe"GET /api/statuses/:id"doit"returns a status by id"dostatus=Status.create!get"/api/statuses/#{status.id}"expect(response.body).toeqstatus.to_jsonendendend

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/spec_helper.rb.

RSpec.configuredo |config|
config.includeRSpec::Rails::RequestExampleGroup,type: :request,file_path: /spec\/api/end

MiniTest

classTwitter::APITest < ActiveSupport::TestCaseincludeRack::Test::MethodsdefappRails.applicationendtest"GET /api/statuses/public_timeline returns an empty array of statuses"doget"/api/statuses/public_timeline"assertlast_response.ok?assert_equalJSON.parse(last_response.body),[]endtest"GET /api/statuses/:id returns a status by id"dostatus=Status.create!get"/api/statuses/#{status.id}"assert_equallast_response.body,status.to_jsonendend

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.

describe'an endpoint that needs helpers stubbed'dobeforedoGrape::Endpoint.before_eachdo |endpoint|
allow(endpoint).toreceive(:helper_name).and_return('desired_value')endendafterdoGrape::Endpoint.before_eachnilendit'should properly stub the helper'do# ...endend

Reloading API Changes in Development

Reloading in Rack Applications

Use grape-reload.

Reloading in Rails Applications

Add API paths to config/application.rb.

# Auto-load API and its subdirectoriesconfig.paths.addFile.join("app","api"),glob: File.join("**","*.rb")config.autoload_paths += Dir[Rails.root.join("app","api","*")]

Create config/initializers/reload_api.rb.

ifRails.env.development?ActiveSupport::Dependencies.explicitly_unloadable_constants << "Twitter::API"api_files=Dir[Rails.root.join('app','api','**','*.rb')]api_reloader=ActiveSupport::FileUpdateChecker.new(api_files)doRails.application.reload_routes!endActionDispatch::Callbacks.to_preparedoapi_reloader.execute_if_updatedendend

See StackOverflow #3282655 for more information.

Performance Monitoring

Grape integrates with NewRelic via the newrelic-grape gem, and with Librato Metrics with the grape-librato gem.

Contributing to Grape

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

See CONTRIBUTING.

Hacking on Grape

You can start hacking on Grape on Nitrous.IO in a matter of seconds:

Hack intridea/grape on Nitrous.IO

License

MIT License. See LICENSE for details.

Copyright

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

About

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

Resources

Contributing

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages