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.
You're reading the documentation for the next release of Grape, which should be 0.2.4. The current stable release is 0.2.3.
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.
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.
classTwitter::API < Grape::APIversion'v1',:using=>:header,:vendor=>'twitter'format:jsonhelpersdodefcurrent_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."endget':id'doStatus.find(params[:id])enddesc"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]).destroyendendendThe above sample creates a Rack application that can be run from a rackup config.ru file
with rackup:
runTwitter::APIAnd would respond to the following routes:
GET /statuses/public_timeline(.json)
GET /statuses/home_timeline(.json)
GET /statuses/:id(.json)
POST /statuses(.json)
PUT /statuses/:id(.json)
DELETE /statuses/:id(.json)
In a Rails application, modify config/routes:
mountTwitter::API=>"/"Note that when using Rails you will need to restart the server to pick up changes in your API classes (see Issue 131).
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::APIv2endThere are three strategies in which clients can reach your API's endpoints: :header,
:path and :param. The default strategy is :path.
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.
version'v1',:using=>:pathUsing this versioning strategy, clients should pass the desired version in the URL.
curl -H http://localhost:9292/v1/statuses/public_timeline
version'v1',:using=>:paramUsing 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
You can add a description to API methods and namespaces.
desc"Returns your public timeline."get:public_timelinedoStatus.limit(20)endRequest parameters are available through the params hash object. This includes GET and POST parameters,
along with any named parameters you specify in your route strings.
get:public_timelinedoStatus.order(params[:sort_by])endParameters are also populated from the request body on POST and PUT for 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]})endYou 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:urlendendput':id'do# params[:id] is an IntegerendWhen a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.
Parameters can be nested using group. In the above example, this means
params[:media][:url] is required along with params[:id].
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])endendendclassAlphaNumeric < Grape::Validations::Validatordefvalidate_param!(attr_name,params)unlessparams[attr_name] =~ /^[[:alnum:]]+$/throw:error,:status=>400,:message=>"#{attr_name}: must consist of alpha-numeric characters"endendendparamsdorequires:text,:alpha_numeric=>trueendYou can also create custom classes that take parameters.
classLength < Grape::Validations::SingleOptionValidatordefvalidate_param!(attr_name,params)unlessparams[attr_name].length <= @optionthrow:error,:status=>400,:message=>"#{attr_name}: must be at the most #{@option} characters long"endendendparamsdorequires:text,:length=>140endWhen validation and coercion errors occur an exception of type Grape::Exceptions::ValidationError is raised.
If the exception goes uncaught it will respond with a status of 400 and an error message.
You can rescue a Grape::Exceptions::ValidationError and respond with a custom response.
rescue_fromGrape::Exceptions::ValidationErrordo |e|
Rack::Response.new({'status'=>e.status,'message'=>e.message,'param'=>e.param}.to_json,e.status)endHeaders are available through the header helper or the env hash object.
getdocontent_type=header['Content-type']
...
endgetdoerror!('Unauthorized',401)unlessenv['HTTP_SECRET_PASSWORD'] == 'swordfish'
...
endOptionally, you can define requirements for your named route parameters using regular expressions. The route will match only if all requirements are met.
get':id',:requirements=>{:id=>/[0-9]*/}doStatus.find(params[:id])endYou 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)endendYou 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)}endendUse 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] +=1You can redirect to a new url temporarily (302) or permanently (301).
redirect"/statuses"redirect"/statuses",:permanent=>trueWhen you add a route for a resource, a route for the HTTP 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}endendcurl -v -X OPTIONS http://localhost:3000/rt_count
> OPTIONS /rt_count HTTP/1.1
>< HTTP/1.1 204 No Content
< Allow: OPTIONS, GET, PUTIf 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, PUTYou 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)Grape can be told to rescue all exceptions and return them in txt or json formats.
classTwitter::API < Grape::APIrescue_from:allendYou can also rescue specific exceptions.
classTwitter::API < Grape::APIrescue_fromArgumentError,NotImplementedErrorendThe 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}"}endYou can also use a module or class.
moduleCustomFormatterdefself.call(message,backtrace,options,env){message: message,backtrace: backtrace}endendclassTwitter::API < Grape::APIerror_formatter:custom,CustomFormatterendYou can rescue all exceptions with a code block. The rack_response wrapper
automatically sets the default error code and content-type.
classTwitter::API < Grape::APIrescue_from:alldo |e|
rack_response({:message=>"rescued from #{e.class.name}"})endendYou 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"}).finishendendOr rescue specific exceptions.
classTwitter::API < Grape::APIrescue_fromArgumentErrordo |e|
Rack::Response.new(["ArgumentError: #{e.message}"],500)endrescue_fromNotImplementedErrordo |e|
Rack::Response.new(["NotImplementedError: #{e.message}"],500)endendGrape::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"endendYou 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"endendBy default, Grape supports XML, JSON, Atom, RSS, and text content-types. Serialization takes place automatically.
Your API can declare which types to support by using content_type. Response format
is determined by the request's extension, an explicit format parameter in the query
string, or Accept header.
The following API will only respond to the JSON content-type. All other requests will fail with an HTTP 406 error code.
classTwitter::API < Grape::APIformat:jsoncontent_type:json,"application/json"endCustom 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}endYou 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,XlsFormatterendThe default format is :txt. You can set the preferred format for an API that
supports multiple formats with format.
classTwitter::API < Grape::APIformat:jsonendYou can set the fallback, default format with default_format.
classTwitter::API < Grape::APIdefault_format:jsonendAvailable formats are the following.
:json: use object'sto_jsonwhen available, otherwise callMultiJson.dump:xml: use object'sto_xmlwhen available, usually viaMultiXml, otherwise callto_s:txt: use object'sto_txtwhen available, otherwiseto_s:serializable_hash: use object'sserializable_hashwhen available, otherwise fallback to:json
The order for choosing the format is the following.
- Use the file extension, if specified. If the file is .json, choose the JSON format.
- Use the value of the
formatparameter in the query string, if specified. - Use the format set by the
formatoption, if specified. - Attempt to find an acceptable format from the
Acceptheader. - Use the default format, if specified by the
default_formatoption. - Default to
:txtotherwise.
You can override the content-type of the response by setting the Content-Type header.
classAPI < Grape::APIget'/home_timeline_js'docontent_type"application/javascript""var statuses = ...;"endendEntities are a reusable means for converting Ruby objects to API responses. Entities can be used to conditionally include fields, nest other entities, and build ever larger responses, using inheritance.
Entities inherit from Grape::Entity, and define a simple DSL. Exposures can use
runtime options to determine which fields should be visible, these options are
available to :if, :unless, and :proc. The option keys :version and :collection
will always be defined. The :version key is defined as api.version. The
:collection key is boolean, and defined as true if the object presented is an
array.
expose SYMBOLS- define a list of fields which will always be exposed
expose SYMBOLS, HASH- HASH keys include
:if,:unless,:proc,:as,:using,:format_with,:documentation:ifand:unlessaccept hashes (passed during runtime) or procs (arguments are object and options)
- HASH keys include
expose SYMBOL, { :format_with => :formatter }- expose a value, formatting it first
:format_withcan only be applied to one exposure at a time
expose SYMBOL, { :as => "alias" }- Expose a value, changing its hash key from SYMBOL to alias
:ascan only be applied to one exposure at a time
expose SYMBOL BLOCK- block arguments are object and options
- expose the value returned by the block
- block can only be applied to one exposure at a time
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(satus.txt)}expose:replies,:using=>API::Status,:as=>:repliesendendendmoduleAPImoduleEntitiesclassStatusDetailed < API::Entities::Statusexpose:internal_idendendendGrape ships with a DSL to easily define entities within the context of an existing class:
classStatusincludeGrape::Entity::DSLentity:text,:user_iddoexpose:detailed,if: :conditionalendendThe above will automatically create a Status::Entity class and define properties on it according
to the same rules as above. If you only want to define simple exposures you don't have to supply
a block and can instead simply supply a list of comma-separated symbols.
Once an entity is defined, it can be used within endpoints, by calling present. The present
method accepts two arguments, the object to be presented and the options associated with it. The
options hash must always include :with, which defines the entity to expose.
If the entity includes documentation it can be included in an endpoint's description.
moduleAPIclassStatuses < Grape::APIversion'v1'desc'Statuses index',{:object_fields=>API::Entities::Status.documentation}get'/statues'dostatuses=Status.alltype=current_user.admin? ? :full : :defaultpresentstatues,with: API::Entities::Status,:type=>typeendendendIn addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.
classStatusdefentityStatus.new(self)endclassEntity < Grape::Entityexpose:text,:user_idendendIf 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 User.new to your endpoint,
Grape would 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.
Entities with duplicate exposure names and conditions will silently overwrite one another.
In the following example, when object.check equals "foo", only field_a will be exposed.
However, when object.check equals "bar" both field_b and foo will be exposed.
moduleAPImoduleEntitiesclassStatus < Grape::Entityexpose:field_a,:foo,:if=>lambda{ |object,options| object.check == "foo"}expose:field_b,:foo,:if=>lambda{ |object,options| object.check == "bar"}endendendThis can be problematic, when you have mixed collections. Using respond_to? is safer.
moduleAPImoduleEntitiesclassStatus < Grape::Entityexpose:field_a,:if=>lambda{ |object,options| object.check == "foo"}expose:field_b,:if=>lambda{ |object,options| object.check == "bar"}expose:foo,:if=>lambda{ |object,options| object.respond_to?(:foo)}endendendAlthough Grape ships with its own entity support, it's also possible to use it with other frameworks and renderers.
Use Roar. Include Roar::Representer::JSON in your models or call to_json explicitly on representers in your API.
Rabl is supported via the grape-rabl gem.
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. The description and the optional hash that
follows the API path may contain any number of keys and its values are also
accessible via dynamically-generated route_[name] functions.
TwitterAPI::versions# yields [ 'v1', 'v2' ]TwitterAPI::routes# yields an array of Grape::Route objectsTwitterAPI::routes[0].route_version# yields 'v1'TwitterAPI::routes[0].route_description# etc.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 descriptionendendGrape 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 you're API needs to get part of an URL, for instance:
classTwitterAPI < Grape::APInamespace:statuesdoget'/(*:status)',:anchor=>falsedoendendendThis 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.
You can test a Grape API with RSpec by making HTTP requests and examining the response.
Use rack-test and define your API as app.
require'spec_helper'describeTwitter::APIdoincludeRack::Test::MethodsdefappTwitter::APIenddescribeTwitter::APIdodescribe"GET /api/v1/statuses"doit"returns an empty array of statuses"doget"/api/v1/statuses"last_response.status.should == 200JSON.parse(last_response.body).should == []endenddescribe"GET /api/v1/statuses/:id"doit"returns a status by id"dostatus=Status.create!get"/api/v1/statuses/#{status.id}"last_response.body.should == status.to_jsonendendendendrequire'spec_helper'describeTwitter::APIdodescribe"GET /api/v1/statuses"doit"returns an empty array of statuses"doget"/api/v1/statuses"response.status.should == 200JSON.parse(response.body).should == []endenddescribe"GET /api/v1/statuses/:id"doit"returns a status by id"dostatus=Status.create!get"/api/v1/statuses/#{status.id}"response.body.should == status.to_jsonendendendIn Rails, HTTP request tests would go into the spec/request 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,:example_group=>{:file_path=>/spec\/api/}endGrape is work of dozens of contributors. You're encouraged to submit pull requests, propose features and discuss issues.
- Fork the project
- Write tests for your new feature or a test that reproduces a bug
- Implement your feature or make a bug fix
- Do not mess with Rakefile, version or history
- Commit, push and make a pull request. Bonus points for topic branches.
MIT License. See LICENSE for details.
Copyright (c) 2010-2012 Michael Bleigh, and Intridea, Inc.

