Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork1.2k
An opinionated framework for creating REST-like APIs in Ruby.
License
ruby-grape/grape
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
- What is Grape?
- Stable Release
- Project Resources
- Grape for Enterprise
- Installation
- Basic Usage
- Rails 7.1
- Mounting
- Remounting
- Versioning
- Linting
- Describing Methods
- Configuration
- Parameters
- Parameter Validation and Coercion
- Supported Parameter Types
- Integer/Fixnum and Coercions
- Custom Types and Coercions
- Multipart File Parameters
- First-Class JSON Types
- Multiple Allowed Types
- Validation of Nested Parameters
- Dependent Parameters
- Group Options
- Renaming
- Built-in Validators
- Namespace Validation and Coercion
- Custom Validators
- Validation Errors
- I18n
- Custom Validation messages
- Using dry-validation or dry-schema
- Headers
- Routes
- Helpers
- Path Helpers
- Parameter Documentation
- Cookies
- HTTP Status Code
- Redirecting
- Recognizing Path
- Allowed Methods
- Raising Exceptions
- Exception Handling
- Logging
- API Formats
- Content-type
- API Data Formats
- JSON and XML Processors
- RESTful Model Representations
- Sending Raw or No Data
- Authentication
- Describing and Inspecting an API
- Current Route and Endpoint
- Before, After and Finally
- Anchoring
- Instance Variables
- Using Custom Middleware
- Writing Tests
- Reloading API Changes in Development
- Performance Monitoring
- Contributing to Grape
- Security
- License
- Copyright
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.
You're reading the documentation for the next release of Grape, which should be 3.0.0.The current stable release is2.4.0.
Available as part of the Tidelift Subscription.
The maintainers of Grape are working with Tidelift to deliver commercial support and maintenance. Save time, reduce risk, and improve code health, while paying the maintainers of Grape. Clickhere for more details.
Ruby 3.0 or newer is required.
Grape is available as a gem, to install it run:
bundle add grape
Grape APIs are Rack applications that are created by subclassingGrape::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
Grape'sdeprecator will be added to your application's deprecatorsautomatically as:grape
, so that your application's configuration can be applied to it.
By default Grape will compile the routes on the first route, but it is possible to pre-load routes using thecompile!
method.
Twitter::API.compile!
This can be added to yourconfig.ru
(if using rackup),application.rb
(if using rails), or any file that loads your server.
The above sample creates a Rack application that can be run from a rackupconfig.ru
file withrackup
:
runTwitter::API
(With pre-loading you can use)
Twitter::API.compile!runTwitter::API
And would respond to the following routes:
GET /api/statuses/public_timelineGET /api/statuses/home_timelineGET /api/statuses/:idPOST /api/statusesPUT /api/statuses/:idDELETE /api/statuses/:id
Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.
If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily usingRack::Cascade
:
# Example config.rurequire'sinatra'require'grape'classAPI <Grape::APIget:hellodo{hello:'world'}endendclassWeb <Sinatra::Baseget'/'do'Hello world.'endenduseRack::Session::CookierunRack::Cascade.new[Web,API]
Note that order of loading apps usingRack::Cascade
matters. The grape application must be last if you want to raise custom 404 errors from grape (such aserror!('Not Found',404)
). If the grape application is not last and returns 404 or 405 response,cascade utilizes that as a signal to try the next app. This may lead to undesirable behavior showing thewrong 404 page from the wrong app.
Place API files intoapp/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 forTwitter::API
should beapp/api/twitter/api.rb
.
Modifyconfig/routes
:
mountTwitter::API=>'/'
Rails's default autoloader isZeitwerk
. By default, it inflectsapi
asApi
instead ofAPI
. To make our example work, you need to uncomment the lines at the bottom ofconfig/initializers/inflections.rb
, and addAPI
as an acronym:
ActiveSupport::Inflector.inflections(:en)do |inflect|inflect.acronym'API'end
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 usingprefix
inside the mounted API itself.
classTwitter::API <Grape::APImountTwitter::APIv1=>'/v1'end
Declarations asbefore/after/rescue_from
can be placed before or aftermount
. In any case they will be inherited.
classTwitter::API <Grape::APIbeforedoheader'X-Base-Header','will be defined for all APIs that are mounted below'endrescue_from:alldoerror!({"error"=>"Internal Server Error"},500)endmountTwitter::UsersmountTwitter::Searchafterdoclean_cache!endrescue_fromZeroDivisionErrordoerror!({"error"=>"Not found"},404)endend
You can mount the same endpoints in two different locations.
classVoting::API <Grape::APInamespace'votes'dogetdo# Your logicendpostdo# Your logicendendendclassPost::API <Grape::APImountVoting::APIendclassComment::API <Grape::APImountVoting::APIend
Assuming that the post and comment endpoints are mounted in/posts
and/comments
, you should now be able to doget /posts/votes
,post /posts/votes
,get /comments/votes
andpost /comments/votes
.
You can configure remountable endpoints to change how they behave according to where they are mounted.
classVoting::API <Grape::APInamespace'votes'dodesc"Vote for your#{configuration[:votable]}"getdo# Your logicendendendclassPost::API <Grape::APImountVoting::API,with:{votable:'posts'}endclassComment::API <Grape::APImountVoting::API,with:{votable:'comments'}end
Note that if you're passing a hash as the first parameter tomount
, you will need to explicitly put()
around parameters:
# goodmount({ ::Some::Api=>'/some/api'},with:{condition:true})# badmount ::Some::Api=>'/some/api',with:{condition:true}
You can accessconfiguration
on the class (to use as dynamic attributes), inside blocks (like namespace)
If you want logic happening given on anconfiguration
, you can use the helpergiven
.
classConditionalEndpoint::API <Grape::APIgivenconfiguration[:some_setting]doget'mount_this_endpoint_conditionally'doconfiguration[:configurable_response]endendend
If you want a block of logic running every time an endpoint is mounted (within which you can access theconfiguration
Hash)
classConditionalEndpoint::API <Grape::APImounteddoYourLogger.info"This API was mounted at:#{Time.now}"getconfiguration[:endpoint_name]doconfiguration[:configurable_response]endendend
More complex results can be achieved by usingmounted
as an expression within which theconfiguration
is already evaluated as a Hash.
classExpressionEndpointAPI <Grape::APIget(mounted{configuration[:route_name] ||'default_name'})do# some logicendend
classBasicAPI <Grape::APIdesc'Statuses index'doparams:(configuration[:entity] ||API::Entities::Status).documentationendparamsdorequires:all,using:(configuration[:entity] ||API::Entities::Status).documentationendget'/statuses'dostatuses=Status.alltype=current_user.admin? ?:full ::defaultpresentstatuses,with:(configuration[:entity] ||API::Entities::Status),type:typeendendclassV1 <Grape::APIversion'v1'mountBasicAPI,with:{entity:mounted{configuration[:entity] ||API::Entities::Status}}endclassV2 <Grape::APIversion'v2'mountBasicAPI,with:{entity:mounted{configuration[:entity] ||API::Entities::V2::Status}}end
You have the option to provide various versions of your API by establishing a separateGrape::API
class for each offered version and then integrating them into a primaryGrape::API
class. Ensure that newer versions are mounted before older ones. The default approach to versioning directs the request to the subsequent Rack middleware if a specific version is not found.
require'v1'require'v2'require'v3'classApp <Grape::APImountV3mountV2mountV1end
To maintain the same endpoints from earlier API versions without rewriting them, you can indicate multiple versions within the previous API versions.
classV1 <Grape::APIversion'v1','v2','v3'get'/foo'do# your code for GET /fooendget'/other'do# your code for GET /otherendendclassV2 <Grape::APIversion'v2','v3'get'/var'do# your code for GET /varendendclassV3 <Grape::APIversion'v3'get'/foo'do# your new code for GET /fooendend
Using the example provided, the subsequent endpoints will be accessible across various versions:
GET /v1/fooGET /v1/otherGET /v2/foo# => Same behavior as v1GET /v2/other# => Same behavior as v1GET /v2/var# => New endpoint not available in v1GET /v3/foo# => Different behavior to v1 and v2GET /v3/other# => Same behavior as v1 and v2GET /v3/var# => Same behavior as v2
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
.
version'v1',using::path
Using this versioning strategy, clients should pass the desired version in the URL.
curl http://localhost:9292/v1/statuses/public_timeline
version'v1',using::header,vendor:'twitter'
Currently, Grape only supports versioned media types in the following format:
vnd.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 HTTPAccept
head.
curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline
By default, the first matching version is used when noAccept
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 totrue
, a406 Not Acceptable
error is returned when no correctAccept
header is supplied.
When an invalidAccept
header is supplied, a406 Not Acceptable
error is returned if the:cascade
option is set tofalse
. Otherwise a404 Not Found
error is returned by Rack if no other route matches.
Grape will evaluate the relative quality preference included in Accept headers and default to a quality of 1.0 when omitted. In the following example a Grape API that supports XML and JSON in that order will return JSON:
curl -H "Accept: text/xml;q=0.8, application/json;q=0.9" localhost:1234/resource
version'v1',using::accept_version_header
Using this versioning strategy, clients should pass the desired version in the HTTPAccept-Version
header.
curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline
By default, the first matching version is used when noAccept-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 totrue
, a406 Not Acceptable
error is returned when no correctAccept
header is supplied and the:cascade
option is set tofalse
. Otherwise a404 Not Found
error is returned by Rack if no other route matches.
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 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 http://localhost:9292/statuses/public_timeline?v=v1
You can check whether your API is in conformance with theRack's specification by callinglint!
at the API level or throughconfiguration.
classApi <Grape::APIlint!end
Grape.configuredo |config|config.lint=trueend
Grape.config.lint=true
If you're using Rack 3.X and theRack::Etag
middleware (used byRails), abug related to linting has been fixed in3.1.13 and3.0.15 respectively.
You can add a description to API methods and namespaces. The description would be used bygrape-swagger to generate swagger compliant documentation.
Note: Description block is only for documentation and won't affects API behavior.
desc'Returns your public timeline.'dosummary'summary'detail'more details'paramsAPI::Entities::Status.documentationsuccessAPI::Entities::Entityfailure[[401,'Unauthorized','Entities::Error']]default{code:500,message:'InvalidRequest',model:Entities::Error}named'My named route'headersXAuthToken:{description:'Validates your identity',required:true},XOptionalHeader:{description:'Not really needed',required:false}hiddenfalsedeprecatedfalseis_arraytruenickname'nickname'produces['application/json']consumes['application/json']tags['tag1','tag2']endget:public_timelinedoStatus.limit(20)end
detail
: A more enhanced descriptionparams
: Define parameters directly from anEntity
success
: (former entity) TheEntity
to be used to present the success response for this route.failure
: (former http_codes) A definition of the used failure HTTP Codes and Entities.default
: The definition andEntity
used to present the default response for this route.named
: A helper to give a route a name and find it with this name in the documentation Hashheaders
: A definition of the used Headers- Other options can be found ingrape-swagger
UseGrape.configure
to set up global settings at load time.Currently the configurable settings are:
param_builder
: Sets theParameter Builder, defaults toGrape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder
.
To change a setting value make sure that at some point during load time the following code runs
Grape.configuredo |config|config.setting=valueend
For example, for theparam_builder
, the following code could run in an initializer:
Grape.configuredo |config|config.param_builder=:hashie_mashend
Available parameter builders are:hash
,:hash_with_indifferent_access
, and:hashie_mash
.Seeparams_builder.
You can also configure a single API:
API.configuredo |config|config[key]=valueend
This will be available inside the API withconfiguration
, as if it weremount configuration.
Request parameters are available through theparams
hash object. This includesGET
,POST
andPUT
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 onPOST
andPUT
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;type=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
andPUT
parameters- the contents of the request body on
POST
andPUT
Route string parameters will have precedence.
By default parameters are available asActiveSupport::HashWithIndifferentAccess
. This can be changed to, for example, RubyHash
orHashie::Mash
for the entire API.
classAPI <Grape::APIbuild_with:hashie_mashparamsdooptional:color,type:Stringendgetdoparams.color# instead of params[:color]end
The class can also be overridden on individual parameter blocks usingbuild_with
as follows.
paramsdobuild_with:hashoptional:color,type:Stringend
In the example above,params["color"]
will returnnil
sinceparams
is a plainHash
.
Available parameter builders are:hash
,:hash_with_indifferent_access
, and:hashie_mash
.Seeparams_builder.
Grape allows you to access only the parameters that have been declared by yourparams
block. It will:
- Filter out the params that have been passed, but are not allowed.
- Include any optional params that are declared but not passed.
- Perform any parameter renaming on the resulting hash.
Consider the following API endpoint:
format:jsonpost'users/signup'do{'declared_params'=>declared(params)}end
If you do not specify any parameters,declared
will return an empty hash.
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 parameters.
format:jsonparamsdooptional:user,type:Hashdooptional:first_name,type:Stringoptional: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" } }}
Missing params that are declared as typeHash
orArray
will be included.
format:jsonparamsdooptional:user,type:Hashdooptional:first_name,type:Stringoptional:last_name,type:Stringendoptional:widgets,type:Arrayendpost'users/signup'do{'declared_params'=>declared(params)}end
Request
curl -X POST -H"Content-Type: application/json" localhost:9292/users/signup -d'{}'
Response
{"declared_params": {"user": {"first_name":null,"last_name":null },"widgets": [] }}
The returned hash is anActiveSupport::HashWithIndifferentAccess
.
The#declared
method is not available tobefore
filters, as those are evaluated prior to parameter coercion.
By defaultdeclared(params)
includes parameters that were defined in all parent namespaces. If you want to return only parameters from your current namespace, you can setinclude_parent_namespaces
option tofalse
.
format:jsonnamespace:parentdoparamsdorequires:parent_name,type:Stringendnamespace':parent_name'doparamsdorequires:child_name,type:Stringendget':child_name'do{'without_parent_namespaces'=>declared(params,include_parent_namespaces:false),'with_parent_namespaces'=>declared(params,include_parent_namespaces:true),}endendend
Request
curl -X GET -H"Content-Type: application/json" localhost:9292/parent/foo/bar
Response
{"without_parent_namespaces": {"child_name":"bar" },"with_parent_namespaces": {"parent_name":"foo","child_name":"bar" },}
By defaultdeclared(params)
includes parameters that havenil
values. If you want to return only the parameters that are notnil
, you can use theinclude_missing
option. By default,include_missing
is set totrue
. Consider the following API:
format:jsonparamsdorequires:user,type:Hashdorequires:first_name,type:Stringoptional:last_name,type:Stringendendpost'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": {"user": {"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 anil
value is not consideredmissing and will also be returned wheninclude_missing
is set tofalse
:
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"} } }}
By defaultdeclared(params)
will not evaluategiven
and return all parameters. Useevaluate_given
to evaluate allgiven
blocks and return only parameters that satisfygiven
conditions. Consider the following API:
format:jsonparamsdooptional:child_id,type:Integergiven:child_iddorequires:father_id,type:Integerendendpost'child'do{'declared_params'=>declared(params,evaluate_given:true)}end
Request
curl -X POST -H"Content-Type: application/json" localhost:9292/child -d'{"father_id": 1}'
Response with evaluate_given:false
{"declared_params": {"child_id":null,"father_id":1 }}
Response with evaluate_given:true
{"declared_params": {"child_id":null }}
It also works on nested hashes:
format:jsonparamsdorequires:child,type:Hashdooptional:child_id,type:Integergiven:child_iddorequires:father_id,type:Integerendendendpost'child'do{'declared_params'=>declared(params,evaluate_given:true)}end
Request
curl -X POST -H"Content-Type: application/json" localhost:9292/child -d'{"child": {"father_id": 1}}'
Response with evaluate_given:false
{"declared_params": {"child": {"child_id":null,"father_id":1 } }}
Response with evaluate_given:true
{"declared_params": {"child": {"child_id":null } }}
Usingroute_param
takes higher precedence over a regular parameter defined with same name:
paramsdorequires:foo,type:Stringendroute_param:foodogetdo{value:params[:foo]}endend
Request
curl -X POST -H"Content-Type: application/json" localhost:9292/bar -d'{"foo": "baz"}'
Response
{"value":"bar"}
You can define validations and coercion options for your parameters using aparams
block.
paramsdorequires:id,type:Integeroptional:text,type:String,regexp:/\A[a-z]+\z/group:media,type:Hashdorequires:urlendoptional:audio,type:Hashdorequires: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
Default values are eagerly evaluated. Above:non_random_number
will evaluate to the same number for each call to the endpoint of thisparams
block. To have the default evaluate lazily with each request use a lambda, like:random_number
above.
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
You can use the value of one parameter as the default value of some other parameter. In this case, if theprimary_color
parameter is not provided, it will have the same value as thecolor
one. If both of them not provided, both of them will haveblue
value.
paramsdooptional:color,type:String,default:'blue'optional:primary_color,type:String,default:->(params){params[:color]}end
The following are all valid types, supported out of the box by Grape:
- Integer
- Float
- BigDecimal
- Numeric
- Date
- DateTime
- Time
- Boolean
- String
- Symbol
- Rack::Multipart::UploadedFile (alias
File
) - JSON
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.
paramsdorequires:integers,type:Hashdorequires:int,coerce:Integerendendget'/int'doparams[:integers][:int].classend...get'/int'integers:{int:'45'}#=> Integer in ruby 2.4#=> Fixnum in earlier ruby versions
Aside from the default set of supported types listed above, any class can be used as a type as long as an explicit coercion method is supplied. If the type implements a class-levelparse
method, Grape will use it automatically. This method must take one string argument and return an instance of the correct type, or return an instance ofGrape::Types::InvalidValue
which optionally accepts a message to be returned in the response.
classColorattr_reader:valuedefinitialize(color)@value=colorenddefself.parse(value)returnnew(value)if%w[blueredgreen].include?(value)Grape::Types::InvalidValue.new('Unsupported color')endendparamsdorequires:color,type:Color,default:Color.new('blue')requires:more_colors,type:Array[Color]# Collections workoptional:unique_colors,type:Set[Color]# Duplicates discardedendget'/stuff'do# params[:color] is already a Color.params[:color].valueend
Alternatively, a custom coercion method may be supplied for any type of parameter usingcoerce_with
. Any class or object may be given that implements aparse
orcall
method, in that order of precedence. The method must accept a single string parameter, and the return value must match the giventype
.
paramsdorequires:passwd,type:String,coerce_with:Base64.method(:decode64)requires:loud_color,type:Color,coerce_with:->(c){Color.parse(c.downcase)}requires:obj,type:Hash,coerce_with:JSONdorequires:words,type:Array[String],coerce_with:->(val){val.split(/\s+/)}optional:time,type:Time,coerce_with:Chronicendend
Note that, anil
value will call the custom coercion method, while a missing parameter will not.
Example of use ofcoerce_with
with a lambda (a class with aparse
method could also have been used)It will parse a string and return an Array of Integers, matching theArray[Integer]
type
.
paramsdorequires:values,type:Array[Integer],coerce_with:->(val){val.split(/\s+/).map(&:to_i)}end
Grape will assert that coerced values match the giventype
, and will reject the request if they do not. To override this behaviour, custom types may implement aparsed?
method that should accept a single argument and returntrue
if the value passes type validation.
classSecureUridefself.parse(value)URI.parsevalueenddefself.parsed?(value)value.is_a?URI::HTTPSendendparamsdorequires:secure_uri,type:SecureUriend
Grape makes use ofRack::Request
's built-in support for multipart file parameters. Such parameters can be declared withtype: File
:
paramsdorequires:avatar,type:Fileendpost'/'doparams[:avatar][:filename]# => 'avatar.png'params[:avatar][:type]# => 'image/png'params[:avatar][:tempfile]# => #<File>end
Grape supports complex parameters given as JSON-formatted strings using the specialtype: JSON
declaration. JSON objects and arrays of objects are accepted equally, with nested validation rules applied to all objects in either case:
paramsdorequires:json,type:JSONdorequires:int,type:Integer,values:[1,2,3]endendget'/'doparams[:json].inspectendclient.get('/',json:'{"int":1}')# => "{:int=>1}"client.get('/',json:'[{"int":"1"}]')# => "[{:int=>1}]"client.get('/',json:'{"int":4}')# => HTTP 400client.get('/',json:'[{"int":4}]')# => HTTP 400
Additionallytype: 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.
paramsdorequires:json,type:Array[JSON]dorequires:int,type:Integerendendget'/'doparams[:json].each{ |obj| ...}# always worksend
For stricter control over the type of JSON structure which may be supplied, usetype: Array, coerce_with: JSON
ortype: Hash, coerce_with: JSON
.
Variant-type parameters can be declared using thetypes
option rather thantype
:
paramsdorequires:status_code,types:[Integer,String,Array[Integer,String]]endget'/'doparams[:status_code].inspectendclient.get('/',status_code:'OK_GOOD')# => "OK_GOOD"client.get('/',status_code:300)# => 300client.get('/',status_code:%w(404NOTFOUND))# => [404, "NOT", "FOUND"]
As a special case, variant-member-type collections may also be declared, by passing aSet
orArray
with more than one member totype
:
paramsdorequires:status_codes,type:Array[Integer,String]endget'/'doparams[:status_codes].inspectendclient.get('/',status_codes:%w(1two))# => [1, "two"]
Parameters can be nested usinggroup
or by callingrequires
oroptional
with a block.In theabove example, this meansparams[:media][:url]
is required along withparams[:id]
, andparams[:audio][:format]
is required only ifparams[:audio]
is present.With a block,group
,requires
andoptional
accept an additional optiontype
which can be eitherArray
orHash
, and defaults toArray
. 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
Suppose some of your parameters are only relevant if another parameter is given; Grape allows you to express this relationship through thegiven
method in your parameters block, like so:
paramsdooptional:shelf_id,type:Integergiven:shelf_iddorequires:bin_id,type:Integerendend
In the example above Grape will useblank?
to check whether theshelf_id
param is present.
given
also takes aProc
with custom code. Below, the paramdescription
is required only if the value ofcategory
is equalfoo
:
paramsdooptional:categorygivencategory:->(val){val =='foo'}dorequires:descriptionendend
You can rename parameters:
paramsdooptional:category,as::typegiventype:->(val){val =='foo'}dorequires:descriptionendend
Note: param ingiven
should be the renamed one. In the example, it should betype
, notcategory
.
Parameters options can be grouped. It can be useful if you want to extract common validation or types for several parameters.Within these groups, individual parameters can extend or selectively override the common settings, allowing you to maintain the defaults at the group level while still applying parameter-specific rules where necessary.
The example below presents a typical case when parameters share common options.
paramsdorequires:first_name,type:String,regexp:/w+/,desc:'First name',documentation:{in:'body'}optional:middle_name,type:String,regexp:/w+/,desc:'Middle name',documentation:{in:'body',x:{nullable:true}}requires:last_name,type:String,regexp:/w+/,desc:'Last name',documentation:{in:'body'}end
Grape allows you to present the same logic through thewith
method in your parameters block, like so:
paramsdowith(type:String,regexp:/w+/,documentation:{in:'body'})dorequires:first_name,desc:'First name'optional:middle_name,desc:'Middle name',documentation:{x:{nullable:true}}requires:last_name,desc:'Last name'endend
You can organize settings into layers using nested `with' blocks. Each layer can use, add to, or change the settings of the layer above it. This helps to keep complex parameters organized and consistent, while still allowing for specific customizations to be made.
paramsdowith(documentation:{in:'body'})do# Applies documentation to all nested parameterswith(type:String,regexp:/\w+/)do# Applies type and validation to namesrequires:first_name,desc:'First name'requires:last_name,desc:'Last name'endoptional:age,type:Integer,desc:'Age',documentation:{x:{nullable:true}}# Specific settings for 'age'endend
You can rename parameters usingas
, which can be useful when refactoring existing APIs:
resource:usersdoparamsdorequires:email_address,as::emailrequires:passwordendpostdoUser.create!(declared(params))# User takes email and passwordendend
The value passed toas
will be the key when callingdeclared(params)
.
Parameters can be defined asallow_blank
, ensuring that they contain a value. By default,requires
only validates that a parameter was sent in the request, regardless its value. Withallow_blank: false
, empty values or whitespace only values are invalid.
allow_blank
can be combined with bothrequires
andoptional
. 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
Parameters can be restricted to a specific set of values with the:values
option.
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 (usingRange#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 endless ranges are also supported with ActiveSupport >= 6.0, but they require that the type be provided.
paramsdorequires:minimum,type:Integer,values:10..optional:maximum,type:Integer,values: ..10end
Note thatboth 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:
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 aProc
, 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 theHashTag
model.
paramsdorequires:hashtag,type:String,values:->{Hashtag.all.map(&:tag)}end
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. The parameter will be considered invalid if the Proc returns a falsy value or if it raises a StandardError.
paramsdorequires:number,type:Integer,values:->(v){v.even? &&v <25}end
While Procs are convenient for single cases, consider usingCustom Validators in cases where a validation is used more than once.
Note thatallow_blank validator applies while using:values
. In the following example the absence of:allow_blank
does not prevent:state
from receiving blank values because:allow_blank
defaults totrue
.
paramsdorequires:state,type:Symbol,values:[:active,:inactive]end
Parameters can be restricted from having a specific set of values with the:except_values
option.
Theexcept_values
validator behaves similarly to thevalues
validator in that it accepts either an Array, a Range, or a Proc. Unlike thevalues
validator, however,except_values
only accepts Procs with arity zero.
paramsdorequires:browser,except_values:['ie6','ie7','ie8']requires:port,except_values:{value:0..1024,message:'is not allowed'}requires:hashtag,except_values:->{Hashtag.FORBIDDEN_LIST}end
Asame_as
option can be given to ensure that values of parameters match.
paramsdorequires:passwordrequires:password_confirmation,same_as::passwordend
Parameters with types that support#length
method can be restricted to have a specific length with the:length
option.
The validator accepts:min
or:max
or both options or only:is
to validate that the value of the parameter is within the given limits.
paramsdorequires:code,type:String,length:{is:2}requires:str,type:String,length:{min:3}requires:list,type:[Integer],length:{min:3,max:5}requires:hash,type:Hash,length:{max:5}end
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 bothrequires
andoptional
parameters.
paramsdorequires:email,regexp:/.+@.+/end
The validator will pass if the parameter was sent without value. To ensure that the parameter contains a value, useallow_blank: false
.
paramsdorequires:email,allow_blank:false,regexp:/.+@.+/end
Parameters can be defined asmutually_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.
Parameters can be defined as 'exactly_one_of', ensuring that exactly one parameter gets selected.
paramsdooptional:beeroptional:wineexactly_one_of:beer,:wineend
Note that using:default
withmutually_exclusive
will cause multiple parameters to always have a default value and raise aGrape::Exceptions::Validation
mutually exclusive exception.
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
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
All of these methods can be used at any nested level.
paramsdorequires:food,type:Hashdooptional:meatoptional:fishoptional:riceat_least_one_of:meat,:fish,:riceendgroup:drink,type:Hashdooptional:beeroptional:wineoptional:juiceexactly_one_of:beer,:wine,:juiceendoptional:dessert,type:Hashdooptional:cakeoptional:icecreammutually_exclusive:cake,:icecreamendoptional:recipe,type:Hashdooptional:oiloptional:meatall_or_none_of:oil,:meatendend
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
Thenamespace
method has a number of aliases, including:group
,resource
,resources
, andsegment
. Use whichever reads the best for your API.
You can conveniently define a route parameter as a namespace usingroute_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
You can also define a route parameter type by passing toroute_param
's options.
namespace:arithmeticdoroute_param:n,type:Integerdodesc'Returns in power'get'power'doparams[:n] **params[:n]endendend
classAlphaNumeric <Grape::Validations::Validators::Basedefvalidate_param!(attr_name,params)unlessparams[attr_name] =~/\A[[:alnum:]]+\z/raiseGrape::Exceptions::Validation.newparams:[@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::Validators::Basedefvalidate_param!(attr_name,params)unlessparams[attr_name].length <=@optionraiseGrape::Exceptions::Validation.newparams:[@scope.full_name(attr_name)],message:"must be at the most#{@option} characters long"endendend
paramsdorequires:text,length:140end
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.
classAdmin <Grape::Validations::Validators::Basedefvalidate(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]returnunlessrequest.params.key?(@attrs.first)# check if admin flag is set to truereturnunless@option# check if user is admin or not# as an example get a token from request and check if it's admin or notraiseGrape::Exceptions::Validation.newparams:@attrs,message:'Can not set admin-only field.'unlessrequest.headers['X-Access-Token'] =='admin'endend
And use it in your endpoint definition as:
paramsdooptional:admin_field,type:String,admin:trueoptional:non_admin_field,type:Stringoptional:admin_false_field,type:String,admin:falseend
Every validation will have its own instance of the validator, which means that the validator can have a state.
Validation and coercion errors are collected and an exception of typeGrape::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 viaGrape::Exceptions::ValidationErrors#errors
.
The default response from aGrape::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 aGrape::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 followingrescue_from
example produces[{"params":["beer","wine"],"messages":["are mutually exclusive"]}]
.
format:jsonsubject.rescue_fromGrape::Exceptions::ValidationErrorsdo |e|error!e,400end
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 useGrape::Exceptions::ValidationErrors#full_messages
.
format:jsonsubject.rescue_fromGrape::Exceptions::ValidationErrorsdo |e|error!({messages:e.full_messages},400)end
Grape returns all validation and coercion errors found by default.To skip all subsequent validation checks when a specific param is found invalid, usefail_fast: true
.
The following example will not check if:wine
is present unless it finds:beer
.
paramsdorequired:beer,fail_fast:truerequired:wineend
The result of empty params would be a singleGrape::Exceptions::ValidationErrors
error.
Similarly, no regular expression test will be performed if:blah
is blank in the following example.
paramsdorequired:blah,allow_blank:false,regexp:/blah/,fail_fast:trueend
Grape supports I18n for parameter-related error messages, but will fallback to English if translations for the default locale have not been provided. Seeen.yml for message keys.
In case your app enforces available locales only and :en is not included in your available locales, Grape cannot fall back to English and will return the translation key for the error message. To avoid this behaviour, either provide a translation for your default locale or add :en to your available locales.
Grape supports custom validation messages for parameter-related and coerce-related error messages.
paramsdorequires: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'end
paramsdorequires:passwordrequires:password_confirmation,same_as:{value::password,message:'not match'}end
paramsdorequires:code,type:String,length:{is:2,message:'code is expected to be exactly 2 characters long'}requires:str,type:String,length:{min:5,message:'str is expected to be at least 5 characters long'}requires:list,type:[Integer],length:{min:2,max:3,message:'list is expected to have between 2 and 3 elements'}end
paramsdooptional:beeroptional:wineoptional:juiceall_or_none_of:beer,:wine,:juice,message:"all params are required or none is required"end
paramsdooptional:beeroptional:wineoptional:juicemutually_exclusive:beer,:wine,:juice,message:"are mutually exclusive cannot pass both params"end
paramsdooptional:beeroptional:wineoptional:juiceexactly_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"}end
paramsdooptional:beeroptional:wineoptional:juiceat_least_one_of:beer,:wine,:juice,message:"are missing, please specify at least one param"end
paramsdorequires:int,type:{value:Integer,message:"type cast is invalid"}end
paramsdorequires:name,values:{value:->{(1..10).to_a},message:'not in range from 1 to 10'}end
You can pass a symbol if you want i18n translations for your custom validation messages.
paramsdorequires:name,message::name_requiredend
# en.ymlen:grape:errors:format: !'%{attributes} %{message}'messages:name_required:'must be present'
You can also override attribute names.
# en.ymlen:grape:errors:format: !'%{attributes} %{message}'messages:name_required:'must be present'attributes:name:'Oops! Name'
Will produce 'Oops! Name must be present'
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 theincompatible_option_values
message key insideen.yml
paramsdorequires:name,values:{value:->{(1..10).to_a},message:'not in range from 1 to 10'},default:5end
As an alternative to theparams
DSL described above, you can use a schema ordry-validation
contract to describe an endpoint's parameters. This can be especially useful if you use the above already in some other parts of your application. If not, you'll need to adddry-validation
ordry-schema
to yourGemfile
.
Then callcontract
with a contract or schema defined previously:
CreateOrdersSchema=Dry::Schema.Paramsdorequired(:orders).array(:hash)dorequired(:name).filled(:string)optional(:volume).maybe(:integer,lt?:9)endend# ...contractCreateOrdersSchema
or with a block, using theschema definition syntax:
contractdorequired(:orders).array(:hash)dorequired(:name).filled(:string)optional(:volume).maybe(:integer,lt?:9)endend
The latter will define a coercing schema (Dry::Schema.Params
). When using the former approach, it's up to you to decide whether the input will need coercing.
Theparams
andcontract
declarations can also be used together in the same API, e.g. to describe different parts of a nested namespace for an endpoint.
Request headers are available through theheaders
helper or fromenv
in their original form.
getdoerror!('Unauthorized',401)unlessheaders['Secret-Password'] =='swordfish'end
getdoerror!('Unauthorized',401)unlessenv['HTTP_SECRET_PASSWORD'] =='swordfish'end
The above example may have been requested as follows:
curl -H"secret_PassWord: swordfish" ...
The header name will have been normalized for you.
- In the
header
helper names will be coerced into a downcased kebab case assecret-password
if using Rack 3. - In the
header
helper names will be coerced into a capitalized kebab case asSecret-PassWord
if using Rack < 3. - In the
env
collection they appear in all uppercase, in snake case, and prefixed with 'HTTP_' asHTTP_SECRET_PASSWORD
The header name will have been normalized per HTTP standards defined inRFC2616 Section 4.2 regardless of what is being sent by a client.
You can set a response header withheader
inside an API.
header'X-Robots-Tag','noindex'
When raisingerror!
, pass additional headers as arguments. Additional headers will be merged with headers set beforeerror!
call.
error!'Unauthorized',401,'X-Error-Detail'=>'Invalid token.'
To define routes you can use theroute
method or the shorthands for the HTTP verbs. To define a route that accepts any route set to:any
.Parts of the path that are denoted with a colon will be interpreted as route parameters.
route:get,'status'doend# is the same asget'status'doend# is the same asget:statusdoend# is NOT the same asget':status'do# this makes params[:status] availableend# This will make both params[:status_id] and params[:id] availableget'statuses/:status_id/reviews/:id'doend
To declare a namespace that prefixes all routes within, use thenamespace
method.group
,resource
,resources
andsegment
are aliases to this method. Any endpoints within will share their parent context as well as any configuration done in the namespace context.
Theroute_param
method is a convenient method for defining a parameter route segment. If you define a type, it will add a validation for this parameter.
route_param:id,type:Integerdoget'status'doendend# is the same asnamespace':id'doparamsdorequires:id,type:Integerendget'status'doendend
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
You can define helper methods that your endpoints can use with thehelpers
macro by either giving a block or an array of modules.
moduleStatusHelpersdefuser_info(user)"#{user} has statused#{user.statuses} status(s)"endendmoduleHttpCodesHelpersdefunauthorized401endendclassAPI <Grape::API# define helpers with a blockhelpersdodefcurrent_userUser.find(params[:user_id])endend# or mix in an array of moduleshelpersStatusHelpers,HttpCodesHelpersbeforedoerror!('Access Denied',unauthorized)unlesscurrent_userendget'info'do# helpers available in your endpoint and filtersuser_info(current_user)endend
You can define reusableparams
usinghelpers
.
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 reusableparams
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 byid
orcreated_at
inasc
ordesc
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
If you need methods for generating paths inside your endpoints, please see thegrape-route-helpers gem.
You can attach additional documentation toparams
using adocumentation
hash.
paramsdooptional:first_name,type:String,documentation:{example:'Jim'}requires:last_name,type:String,documentation:{example:'Smith'}end
If documentation isn't needed (for instance, it is an internal API), documentation can be disabled.
classAPI <Grape::APIdo_not_document!# endpoints...end
In this case, Grape won't create objects related to documentation which are retained in RAM forever.
You can set, get and delete your cookies very simply usingcookies
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 withdelete
.
cookies.delete:status_count
Specify an optional path.
cookies.delete:status_count,path:'/'
By default Grape returns a 201 forPOST
-Requests, 204 forDELETE
-Requests that don't return any content, and 200 status code for all other Requests.You can usestatus
to query and set the actual HTTP Status Code
postdostatus202ifstatus ==200# do some thingendend
You can also use one of status codes symbols that are provided byRack utils
postdostatus:no_contentend
You can redirect to a new url temporarily (302) or permanently (301).
redirect'/statuses'
redirect'/statuses',permanent:true
You can recognize the endpoint matched with given path.
This API returns an instance ofGrape::Endpoint
.
classAPI <Grape::APIget'/statuses'doendendAPI.recognize_path'/statuses'
Since version2.1.0
, therecognize_path
method takes into account the parameters type to determine which endpoint should match with given path.
classBooks <Grape::APIresource:booksdoroute_param:id,type:Integerdo# GET /books/:idgetdo#...endendresource:sharedo# POST /books/sharepostdo# ....endendendendAPI.recognize_path'/books/1'# => /books/:idAPI.recognize_path'/books/share'# => /books/shareAPI.recognize_path'/books/other'# => nil
When you add aGET
route for a resource, a route for theHEAD
method will also be added automatically. You can disable this behavior withdo_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 theOPTIONS
method will also be added. The response to an OPTIONS request will include an "Allow" header listing the supported methods. If the resource hasbefore
andafter
callbacks they will be executed, but no other callbacks will run.
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 withdo_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 hasbefore
callbacks they will be executed, but no other callbacks will run.
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
You can abort the execution of an API method by raising errors witherror!
.
error!'Access Denied',401
Anything that responds to#to_s
can be given as a first argument toerror!
.
error!:not_found,404
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 set additional headers for the response. They will be merged with headers set beforeerror!
call.
error!('Something went wrong',500,'X-Error-Detail'=>'Invalid token.')
You can present documented errors with a Grape entity using the thegrape-entity gem.
moduleAPIclassError <Grape::Entityexpose:codeexpose:messageendend
The following example specifies the entity to use in thehttp_codes
definition.
desc'My Route'dofailure[[408,'Unauthorized',API::Error]]enderror!({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)
By default Grape returns a 500 status code fromerror!
. You can change this withdefault_error_status
.
classAPI <Grape::APIdefault_error_status400get'/example'doerror!'This should have http status code 400'endend
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 todefine this endpoint at the very end of your API, as it literally accepts every request.
Grape can be told to rescue allStandardError
exceptions and return them in the API format.
classTwitter::API <Grape::APIrescue_from:allend
This mimicsdefaultrescue
behaviour when an exception type is not provided.Any other exception should be rescued explicitly, seebelow.
Grape can also rescue from all exceptions and still use the built-in exception handing.This will give the same behavior asrescue_from :all
with the addition that Grape will use the exception handling defined by all Exception classes that inheritGrape::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.
classTwitter::API <Grape::APIrescue_from:grape_exceptionsend
If you want to customize the shape of grape exceptions returned to the user, to match your:all
handler for example, you can pass a block torescue_from :grape_exceptions
.
rescue_from:grape_exceptionsdo |e|error!(e,e.status)end
You can also rescue specific exceptions.
classTwitter::API <Grape::APIrescue_fromArgumentError,UserDefinedErrorend
In this caseUserDefinedError
must be inherited fromStandardError
.
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.
classTwitter::API <Grape::APIrescue_fromGrape::Exceptions::ValidationErrorsdo |e|error!(e,400)endrescue_from:allend
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,->(message,backtrace,options,env,original_exception){"error:#{message} from#{backtrace}"}end
You can also use a module or class.
moduleCustomFormatterdefself.call(message,backtrace,options,env,original_exception){message:message,backtrace:backtrace}endendclassTwitter::API <Grape::APIerror_formatter:custom,CustomFormatterend
You can rescue all exceptions with a code block. Theerror!
wrapper automatically sets the default error code and content-type.
classTwitter::API <Grape::APIrescue_from:alldo |e|error!("rescued from#{e.class.name}")endend
Optionally, you can set the format, status code and headers.
classTwitter::API <Grape::APIformat:jsonrescue_from:alldo |e|error!({error:'Server error.'},500,{'Content-Type'=>'text/error'})endend
You can also rescue all 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'})endend
Or rescue specific exceptions.
classTwitter::API <Grape::APIrescue_fromArgumentErrordo |e|error!("ArgumentError:#{e.message}")endrescue_fromNoMethodErrordo |e|error!("NoMethodError:#{e.message}")endend
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 followingrescue_from
clause will rescue exceptions of typeAPIErrors::ParentError
and its subclasses (in this caseAPIErrors::ChildError
).
rescue_fromAPIErrors::ParentErrordo |e|error!({error:"#{e.class} error",message:e.message},e.status)end
To only rescue the base exception class, setrescue_subclasses: false
.The code below will rescue exceptions of typeRuntimeError
butnot its subclasses.
rescue_fromRuntimeError,rescue_subclasses:falsedo |e|error!({status:e.status,message:e.message,errors:e.errors},e.status)end
Helpers are also available insiderescue_from
.
classTwitter::API <Grape::APIformat:jsonhelpersdodefserver_error!error!({error:'Server error.'},500,{'Content-Type'=>'text/error'})endendrescue_from:alldo |e|server_error!endend
Therescue_from
handler must return aRack::Response
object, callerror!
, or raise an exception (either the original exception or another custom one). The exception raised inrescue_from
will be handled outside Grape. For example, if you mount Grape in Rails, the exception will be handle byRails Action Controller.
Alternately, use thewith
option inrescue_from
to specify a method or aproc
.
classTwitter::API <Grape::APIformat:jsonhelpersdodefserver_error!error!({error:'Server error.'},500,{'Content-Type'=>'text/error'})endendrescue_from:all,with::server_error!rescue_fromArgumentError,with:->{Rack::Response.new('rescued with a method',400)}end
Inside therescue_from
block, the environment of the original controller method(.self
receiver) is accessible through the#context
method.
classTwitter::API <Grape::APIrescue_from:alldo |e|user_id=context.params[:user_id]error!("error for#{user_id}")endend
You could putrescue_from
clauses inside a namespace and they will take precedence over onesdefined in the root scope:
classTwitter::API <Grape::APIrescue_fromArgumentErrordo |e|error!("outer")endnamespace:statusesdorescue_fromArgumentErrordo |e|error!("inner")endgetdoraiseArgumentError.newendendend
Here'inner'
will be result of handling occurredArgumentError
.
Grape::Exceptions::InvalidVersionHeader
, which is raised when the version in the request header doesn't match the currently evaluated version for the endpoint, willnever be rescued from arescue_from
block (even arescue_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.
Any exception that is not subclass ofStandardError
should be rescued explicitly.Usually it is not a case for an application logic as such errors point to problems in Ruby runtime.This is followingstandard recommendations for exceptions handling.
Grape::API
provides alogger
method which by default will return an instance of theLogger
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'dologger.info"#{current_user} has statused"endend
To change the logger level.
classAPI <Grape::APIself.logger.level=Logger::INFOend
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
For similar to Rails request logging try thegrape_logging orgrape-middleware-logger gems.
Your API can declare which content-types to support by usingcontent_type
. If you do not specify any, Grape will supportXML,JSON,BINARY, andTXT content-types. The default format is:txt
; you can change this withdefault_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 anycontent_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 newdefault_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 callto_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 anAccept: */*
header) does not have an extension or aformat
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 recognizedformat
parameter, so it will respond with XML.GET /hello.xml?format=json
has a recognized extension (which takes precedence over theformat
parameter), so it will respond with XML.GET /hello.xls
(with anAccept: */*
header) has an extension, but that extension is not recognized, so it will respond with JSON (the default format).GET /hello.xls
with anAccept: application/xml
header has an unrecognized extension, but theAccept
header corresponds to a recognized format, so it will respond with XML.GET /hello.xls
with anAccept: text/plain
header has an unrecognized extensionand an unrecognizedAccept
header, so it will respond with JSON (the default format).
You can override this process explicitly by callingapi_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_sapi_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].readendend
You can have your API only respond to a single format withformat
. If you use this, the API willnot respond to file extensions other than specified informat
. For example, consider the following API.
classSingleFormatAPI <Grape::APIformat:jsonget:hellodo{hello:'world'}endend
GET /hello
will respond with JSON.GET /hello.json
will respond with JSON.GET /hello.xml
,GET /hello.foobar
, orany 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 anAccept: 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 thanapplication/json
,application/x-www-form-urlencoded
,multipart/form-data
,multipart/related
andmultipart/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 unlessdefault_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 combineformat
withrescue_from :all
, errors will be rendered using the same format.If you do not want this behavior, set the default error formatter withdefault_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,->(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'sto_json
when available, otherwise callMultiJson.dump
:xml
: use object'sto_xml
when available, usually viaMultiXml
:txt
: use object'sto_txt
when available, otherwiseto_s
:serializable_hash
: use object'sserializable_hash
when available, otherwise fallback to:json
:binary
: data will be returned "as is"
If a body is present in a request to an API, with a Content-Type header value that is of an unsupported type a "415 Unsupported Media Type" error code will be returned by Grape.
Response statuses that indicate no content as defined byRackhere will bypass serialization and the body entity - though there should be none - will not be modified.
Grape supports JSONP viaRack::JSONP, part of therack-contrib gem. Addrack-contrib
to yourGemfile
.
require'rack/contrib'classAPI <Grape::APIuseRack::JSONPformat:jsonget'/'do'Hello World'endend
Grape supports CORS viaRack::CORS, part of therack-cors gem. Addrack-cors
to yourGemfile
, then use the middleware in your config.ru file.
require'rack/cors'useRack::Corsdoallowdoorigins'*'resource'*',headers::any,methods::getendendrunTwitter::API
Content-type is set by the formatter. You can override the content-type of the response at runtime by setting theContent-Type
header.
classAPI <Grape::APIget'/home_timeline_js'docontent_type'application/javascript'"var statuses = ...;"endend
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 viacontent_type
and optionally supply a parser viaparser
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" inenv['api.request.body']
.Without a parser, data is available "as-is" and inenv['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 viaparams[: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 withnil
. For example,parser :json, nil
will disable JSON parsing altogether. The request data is then available as-is inenv['api.request.body']
.
Grape usesJSON
andActiveSupport::XmlMini
for JSON and XML parsing by default. It also detects and supportsmulti_json andmulti_xml. Adding those gems to your Gemfile and requiring them will enable them and allow you to swap the JSON and XML back-ends.
Grape supports a range of ways to present your data with some help from a genericpresent
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.
Add thegrape-entity gem to your Gemfile.Please refer to thegrape-entity documentationfor 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:->(status,options){status.user.public?}expose:digestdo |status,options|Digest::MD5.hexdigest(status.txt)endexpose: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 withusing: 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 theEntity
class and use it to present your models. In this example, if you addedpresent Status.new
to your endpoint, Grape will automatically detect that there is aStatus::Entity
class and use that as the representative entity. This can still be overridden by using the:with
option or an explicitrepresents
call.
You can presenthash
withGrape::Presenters::Presenter
to keep things consistent.
get'/users'dopresent{id:10,name::dgz},with:Grape::Presenters::Presenterend
The response will be
{id:10,name:'dgz'}
It has the same result with
get'/users'dopresent:id,10present:name,:dgzend
You can useRoar to render HAL or Collection+JSON with the help ofgrape-roar, which defines a custom JSON formatter and enables presenting entities with Grape'spresent
keyword.
You can useRabl templates with the help of thegrape-rabl gem, which defines a custom Grape Rabl formatter.
You can useActive Model Serializers serializers with the help of thegrape-active_model_serializers gem, which defines a custom Grape AMS formatter.
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 set the response body explicitly withbody
.
classAPI <Grape::APIget'/'docontent_type'text/plain'body'Hello World'# return value ignoredendend
Usebody false
to return204 No Content
without any data or content-type.
If you want to empty the body with an HTTP status code other than204 No Content
, you can override the status code after specifyingbody false
as follows
classAPI <Grape::APIget'/'dobodyfalsestatus304endend
You can also set the response to a file withsendfile
. This works with theRack::Sendfile middleware to optimally send the file through your web server software.
classAPI <Grape::APIget'/'dosendfile'/path/to/file'endend
To stream a file in chunks usestream
classAPI <Grape::APIget'/'dostream'/path/to/file'endend
If you want to stream non-file data use thestream
method and aStream
object.This is an object that responds toeach
and yields for each chunk to send to the client.Each chunk will be sent as it is yielded instead of waiting for all of the content to be available.
classMyStreamdefeachyield'part 1'yield'part 2'yield'part 3'endendclassAPI <Grape::APIget'/'dostreamMyStream.newendend
Grape has built-in Basic authentication (the givenblock
is executed in the context of the currentEndpoint
). Authentication applies to the current namespace and any children, but not parents.
http_basicdo |username,password|# verify user's password here# IMPORTANT: make sure you use a comparison method which isn't prone to a timing attackend
Grape can use custom Middleware for authentication. How to implement these Middleware have a look atRack::Auth::Basic
or similar implementations.
For registering a Middleware you need the following options:
label
- the name for your authenticator to use it laterMiddlewareClass
- the MiddlewareClass to use for authenticationoption_lookup_proc
- A Proc with one Argument to lookup the options at runtime (return value is anArray
as Parameter 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
UseDoorkeeper,warden-oauth2 orrack-oauth2 for OAuth2 support.
You can access the controller params, headers, and helpers through the context with the#context
method inside any auth middleware inherited fromGrape::Middleware::Auth::Base
.
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 aprefix
,version
,namespace
,method
andparams
. You can add custom route settings to the route metadata withroute_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].version# => 'v1'TwitterAPI::routes[0].description# => 'Includes custom settings.'TwitterAPI::routes[0].settings[:custom]# => { key: 'value' }
Note thatRoute#route_xyz
methods have been deprecated since 0.15.0 and removed since 2.0.1.
Please useRoute#xyz
instead.
Note that difference ofRoute#options
andRoute#settings
.
Theoptions
can be referred from your route, it should be set by specifying key and value on verb methods such asget
,post
andput
.Thesettings
can also be referred from your route, but it should be set by specifying key and value onroute_setting
.
It's possible to retrieve the information about the current route from within an API call withroute
.
classMyAPI <Grape::APIdesc'Returns a description of a parameter.'paramsdorequires:id,type:Integer,desc:'Identity.'endget'params/:id'doroute.params[params[:id]]# yields the parameter descriptionendend
The current endpoint responding to the request isself
within the API block orenv['api.endpoint']
elsewhere. The endpoint has some interesting properties, such assource
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
Blocks can be executed before or after every API call, usingbefore
,after
,before_validation
andafter_validation
.If the API fails theafter
call will not be triggered, if you need code to execute for sure use thefinally
.
Before and after callbacks execute in the following order:
before
before_validation
- validations
after_validation
(upon successful validation)- the API call (upon successful validation)
after
(upon successful validation and API call)finally
(always)
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) onlybefore
callbacks will be executed. The remaining callbacks will be bypassed.
If a request for a resource is made that triggers the built-inOPTIONS
handler, onlybefore
andafter
callbacks will be executed. The remaining callbacks will be bypassed.
For example, using a simplebefore
block to set a header.
beforedoheader'X-Robots-Tag','noindex'end
You can ensure a block of code runs after every request (including failures) withfinally
:
finallydo# this code will run after every request (successful or failed)end
Namespaces
Callbacks apply to each 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 behavior is then:
GET /# 'root - 'GET /foo# 'root - foo - blah'GET /foo/bar# 'root - foo - bar - blah'
Params on anamespace
(or whichever alias you are using) will also be available when usingbefore_validation
orafter_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 behavior is then:
GET /123# 'Integer'GET /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.
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 behavior is then:
GET /foo/v1# 'v1-hello'GET /foo/v2# 'v2-hello'
Altering Responses
Usingpresent
in any callback allows you to add data to a response:
classMyAPI <Grape::APIformat:jsonafter_validationdopresent:name,params[:name]ifparams[:name]endget'/greeting'dopresent:greeting,'Hello!'endend
The behavior is then:
GET /greeting# {"greeting":"Hello!"}GET /greeting?name=Alan# {"name":"Alan","greeting":"Hello!"}
Instead of altering a response, you can also terminate and rewrite it from any callback usingerror!
, includingafter
. This will cause all subsequent steps in the process to not be called.This includes the actual api call and any callbacks
Grape by default anchors all request paths, which means that the request URL should match from start to end to match, otherwise a404 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 aanchor: 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: theparams[: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 thePATH_INFO
Rack environment variable, usingenv['PATH_INFO']
. This will hold everything that comes after the '/statuses/' part.
You can use instance variables to pass information across the various stages of a request. An instance variable set within abefore
validator is accessible within the endpoint's code and can also be utilized within therescue_from
handler.
classTwitterAPI <Grape::APIbeforedo@var=1endget'/'doputs@var# => 1raiseendrescue_from:alldoputs@var# => 1endend
The values of instance variables cannot be shared among various endpoints within the same API. This limitation arises due to Grape generating a new instance for each request made. Consequently, instance variables set within an endpoint during one request differ from those set during a subsequent request, as they exist within separate instances.
classTwitterAPI <Grape::APIget'/first'do@var=1puts@var# => 1endget'/second'doputs@var# => nilendend
You can make a custom middleware by usingGrape::Middleware::Base
.It's inherited from some grape official middlewares in fact.
For example, you can write a middleware to log application exception.
classLoggingError <Grape::Middleware::Basedefafterreturnunless@app_response &&@app_response[0] ==500env['rack.logger'].error("Raised error on#{env['PATH_INFO']}")endend
Your middleware can overwrite application response as follows, except error case.
classOverwriter <Grape::Middleware::Basedefafter[200,{'Content-Type'=>'text/plain'},['Overwritten.']]endend
You can add your custom middleware withuse
, that push the middleware onto the stack, and you can also control where the middleware is inserted usinginsert
,insert_before
andinsert_after
.
classCustomOverwriter <Grape::Middleware::Basedefafter[200,{'Content-Type'=>'text/plain'},[@options[:message]]]endendclassAPI <Grape::APIuseOverwriterinsert_beforeOverwriter,CustomOverwriter,message:'Overwritten again.'insert0,CustomOverwriter,message:'Overwrites all other middleware.'get'/'doendend
You can access the controller params, headers, and helpers through the context with the#context
method inside any middleware inherited fromGrape::Middleware::Base
.
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 specificenv
variable.
If you are using a custom application that is inherited fromRails::Application
and need to insert a new middleware among the ones initiated via Rails, you will need to register it manually in your custom application class.
classCompany::Application <Rails::Applicationconfig.middleware.insert_before(Rack::Attack,Middleware::ApiLogger)end
By default you can access remote IP withrequest.ip
. This is the remote IP address implemented by Rack. Sometimes it is desirable to get the remote IPRails-style withActionDispatch::RemoteIp
.
Addgem 'actionpack'
to your Gemfile andrequire 'action_dispatch/middleware/remote_ip.rb'
. Use the middleware in your API and expose aclient_ip
helper. Seethis documentation for additional options.
classAPI <Grape::APIuseActionDispatch::RemoteIphelpersdodefclient_ipenv['action_dispatch.remote_ip'].to_sendendget:remote_ipdo{ip:client_ip}endend
Userack-test
and define your API asapp
.
You can test a Grape API with RSpec by making HTTP requests and examining the response.
describeTwitter::APIdoincludeRack::Test::MethodsdefappTwitter::APIendcontext'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[]endendcontext'GET /api/statuses/:id'doit'returns a status by id'dostatus=Status.create!get"/api/statuses/#{status.id}"expect(last_response.body).toeqstatus.to_jsonendendend
There's no standard way of sending arrays of objects via an HTTP GET, so POST JSON data and specify the correct content-type.
describeTwitter::APIdocontext'POST /api/statuses'doit'creates many statuses'dostatuses=[{text:'...'},{text:'...'}]post'/api/statuses',statuses.to_json,'CONTENT_TYPE'=>'application/json'expect(last_response.body).toeq201endendend
You can test with other RSpec-based frameworks, includingAirborne, which usesrack-test
to make requests.
require'airborne'Airborne.configuredo |config|config.rack_app=Twitter::APIenddescribeTwitter::APIdocontext'GET /api/statuses/:id'doit'returns a status by id'dostatus=Status.create!get"/api/statuses/#{status.id}"expect_json(status.as_json)endendend
require'test_helper'classTwitter::APITest <MiniTest::TestincludeRack::Test::MethodsdefappTwitter::APIenddeftest_get_api_statuses_public_timeline_returns_an_empty_array_of_statusesget'/api/statuses/public_timeline'assertlast_response.ok?assert_equal[],JSON.parse(last_response.body)enddeftest_get_api_statuses_id_returns_a_status_by_idstatus=Status.create!get"/api/statuses/#{status.id}"assert_equalstatus.to_json,last_response.bodyendend
describeTwitter::APIdocontext'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[]endendcontext'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 thespec/requests
group. You may want your API code to go intoapp/api
- you can match that layout underspec
by adding the following inspec/rails_helper.rb
.
RSpec.configuredo |config|config.includeRSpec::Rails::RequestExampleGroup,type::request,file_path:/spec\/api/end
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_equal[],JSON.parse(last_response.body)endtest'GET /api/statuses/:id returns a status by id'dostatus=Status.create!get"/api/statuses/#{status.id}"assert_equalstatus.to_json,last_response.bodyendend
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. TheGrape::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'stubs the helper'doendend
Usegrape-reload.
Add API paths toconfig/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','*')]
Createconfig/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
For Rails >= 5.1.4, change this:
ActionDispatch::Callbacks.to_preparedoapi_reloader.execute_if_updatedend
to this:
ActiveSupport::Reloader.to_preparedoapi_reloader.execute_if_updatedend
SeeStackOverflow #3282655 for more information.
Grape has built-in support forActiveSupport::Notifications which provides simple hook points to instrument key parts of your application.
The following are currently supported:
The main execution of an endpoint, includes filters and rendering.
- endpoint - The endpoint instance
The execution of the main content block of the endpoint.
- endpoint - The endpoint instance
- endpoint - The endpoint instance
- filters - The filters being executed
- type - The type of filters (before, before_validation, after_validation, after)
The execution of validators.
- endpoint - The endpoint instance
- validators - The validators being executed
- request - The request being validated
Serialization or template rendering.
- env - The request environment
- formatter - The formatter object (e.g.,
Grape::Formatter::Json
)
See theActiveSupport::Notifications documentation for information on how to subscribe to these events.
Grape integrates with following third-party tools:
- New Relic -built-in support from v3.10.0 of the officialnewrelic_rpm gem, alsonewrelic-grape gem
- Librato Metrics -grape-librato gem
- Skylight -skylight gem,documentation
- AppSignal -appsignal-ruby gem,documentation
- ElasticAPM -elastic-apm gem,documentation
- Datadog APM -ddtrace gem,documentation
Grape is work of hundreds of contributors. You're encouraged to submit pull requests, propose features and discuss issues.
SeeCONTRIBUTING.
SeeSECURITY for details.
MIT License. SeeLICENSE for details.
Copyright (c) 2010-2020 Michael Bleigh, Intridea Inc. and Contributors.
About
An opinionated framework for creating REST-like APIs in Ruby.
Topics
Resources
License
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.