{"id":7571,"date":"2015-08-14T00:37:52","date_gmt":"2015-08-14T00:37:52","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/08\/14\/intridea-grape\/"},"modified":"2015-08-14T00:37:52","modified_gmt":"2015-08-14T00:37:52","slug":"intridea-grape","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2015\/08\/14\/intridea-grape\/","title":{"rendered":"intridea\/grape"},"content":{"rendered":"<p><img decoding=\"async\" src=\"http:\/\/unknownerror.org\/opensource\/intridea\/grape\/grape.png\" \/><\/p>\n<p><img decoding=\"async\" src=\"http:\/\/img.shields.io\/gem\/v\/grape.svg\" \/> <img decoding=\"async\" src=\"http:\/\/img.shields.io\/travis\/intridea\/grape.svg\" \/> <img decoding=\"async\" src=\"http:\/\/gemnasium.com\/intridea\/grape.svg\" \/> <img decoding=\"async\" src=\"http:\/\/codeclimate.com\/github\/intridea\/grape.svg\" \/> <img decoding=\"async\" src=\"http:\/\/inch-ci.org\/github\/intridea\/grape.svg\" \/><\/p>\n<h2>Table of Contents<\/h2>\n<h2>What is Grape?<\/h2>\n<p>Grape is a REST-like API micro-framework for Ruby. It\u2019s 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.<\/p>\n<h2>Stable Release<\/h2>\n<p>You\u2019re reading the documentation for the next release of Grape, which should be 0.11.1. Please read UPGRADING when upgrading from a previous version. The current stable release is 0.11.0.<\/p>\n<h2>Project Resources<\/h2>\n<ul>\n<li>Need help? Grape Google Group<\/li>\n<li>Grape Wiki<\/li>\n<\/ul>\n<h2>Installation<\/h2>\n<p>Grape is available as a gem, to install it just install the gem:<\/p>\n<pre><code>gem install grape\n<\/code><\/pre>\n<p>If you\u2019re using Bundler, add the gem to Gemfile.<\/p>\n<pre><code>gem 'grape'\n<\/code><\/pre>\n<p>Run <code>bundle install<\/code>.<\/p>\n<h2>Basic Usage<\/h2>\n<p>Grape APIs are Rack applications that are created by subclassing <code>Grape::API<\/code>. Below is a simple example showing some of the more common features of Grape in the context of recreating parts of the Twitter API.<\/p>\n<pre><code>module Twitter\n  class API &lt; Grape::API\n    version 'v1', using: :header, vendor: 'twitter'\n    format :json\n    prefix :api\n\n    helpers do\n      def current_user\n        @current_user ||= User.authorize!(env)\n      end\n\n      def authenticate!\n        error!('401 Unauthorized', 401) unless current_user\n      end\n    end\n\n    resource :statuses do\n      desc \"Return a public timeline.\"\n      get :public_timeline do\n        Status.limit(20)\n      end\n\n      desc \"Return a personal timeline.\"\n      get :home_timeline do\n        authenticate!\n        current_user.statuses.limit(20)\n      end\n\n      desc \"Return a status.\"\n      params do\n        requires :id, type: Integer, desc: \"Status id.\"\n      end\n      route_param :id do\n        get do\n          Status.find(params[:id])\n        end\n      end\n\n      desc \"Create a status.\"\n      params do\n        requires :status, type: String, desc: \"Your status.\"\n      end\n      post do\n        authenticate!\n        Status.create!({\n          user: current_user,\n          text: params[:status]\n        })\n      end\n\n      desc \"Update a status.\"\n      params do\n        requires :id, type: String, desc: \"Status ID.\"\n        requires :status, type: String, desc: \"Your status.\"\n      end\n      put ':id' do\n        authenticate!\n        current_user.statuses.find(params[:id]).update({\n          user: current_user,\n          text: params[:status]\n        })\n      end\n\n      desc \"Delete a status.\"\n      params do\n        requires :id, type: String, desc: \"Status ID.\"\n      end\n      delete ':id' do\n        authenticate!\n        current_user.statuses.find(params[:id]).destroy\n      end\n    end\n  end\nend\n<\/code><\/pre>\n<h2>Mounting<\/h2>\n<h3>Rack<\/h3>\n<p>The above sample creates a Rack application that can be run from a rackup <code>config.ru<\/code> file with <code>rackup<\/code>:<\/p>\n<pre><code>run Twitter::API\n<\/code><\/pre>\n<p>And would respond to the following routes:<\/p>\n<pre><code>GET \/api\/statuses\/public_timeline\nGET \/api\/statuses\/home_timeline\nGET \/api\/statuses\/:id\nPOST \/api\/statuses\nPUT \/api\/statuses\/:id\nDELETE \/api\/statuses\/:id\n<\/code><\/pre>\n<p>Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.<\/p>\n<h3>ActiveRecord without Rails<\/h3>\n<p>If you want to use ActiveRecord within Grape, you will need to make sure that ActiveRecord\u2019s connection pool is handled correctly.<\/p>\n<p>The easiest way to achieve that is by using ActiveRecord\u2019s <code>ConnectionManagement<\/code> middleware in your <code>config.ru<\/code> before mounting Grape, e.g.:<\/p>\n<pre><code>use ActiveRecord::ConnectionAdapters::ConnectionManagement\n\nrun Twitter::API\n<\/code><\/pre>\n<h3>Alongside Sinatra (or other frameworks)<\/h3>\n<p>If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using <code>Rack::Cascade<\/code>:<\/p>\n<pre><code># Example config.ru\n\nrequire 'sinatra'\nrequire 'grape'\n\nclass API &lt; Grape::API\n  get :hello do\n    { hello: \"world\" }\n  end\nend\n\nclass Web &lt; Sinatra::Base\n  get '\/' do\n    \"Hello world.\"\n  end\nend\n\nuse Rack::Session::Cookie\nrun Rack::Cascade.new [API, Web]\n<\/code><\/pre>\n<h3>Rails<\/h3>\n<p>Place API files into <code>app\/api<\/code>. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory for <code>Twitter::API<\/code> should be <code>app\/api\/twitter\/api.rb<\/code>.<\/p>\n<p>Modify <code>application.rb<\/code>:<\/p>\n<pre><code>config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')\nconfig.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]\n<\/code><\/pre>\n<p>Modify <code>config\/routes<\/code>:<\/p>\n<pre><code>mount Twitter::API =&gt; '\/'\n<\/code><\/pre>\n<p>Additionally, if the version of your Rails is 4.0+ and the application uses the default model layer of ActiveRecord, you will want to use the hashie-forbidden_attributes gem. This gem disables the security feature of <code>strong_params<\/code> at the model layer, allowing you the use of Grape\u2019s own params validation instead.<\/p>\n<pre><code># Gemfile\ngem \"hashie-forbidden_attributes\"\n<\/code><\/pre>\n<p>See below for additional code that enables reloading of API changes in development.<\/p>\n<h3>Modules<\/h3>\n<p>You can mount multiple API implementations inside another one. These don\u2019t have to be different versions, but may be components of the same API.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  mount Twitter::APIv1\n  mount Twitter::APIv2\nend\n<\/code><\/pre>\n<p>You can also mount on a path, which is similar to using <code>prefix<\/code> inside the mounted API itself.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  mount Twitter::APIv1 =&gt; '\/v1'\nend\n<\/code><\/pre>\n<h2>Versioning<\/h2>\n<p>There are four strategies in which clients can reach your API\u2019s endpoints: <code>:path<\/code>, <code>:header<\/code>, <code>:accept_version_header<\/code> and <code>:param<\/code>. The default strategy is <code>:path<\/code>.<\/p>\n<h3>Path<\/h3>\n<pre><code>version 'v1', using: :path\n<\/code><\/pre>\n<p>Using this versioning strategy, clients should pass the desired version in the URL.<\/p>\n<pre><code>curl http:\/\/localhost:9292\/v1\/statuses\/public_timeline\n<\/code><\/pre>\n<h3>Header<\/h3>\n<pre><code>version 'v1', using: :header, vendor: 'twitter'\n<\/code><\/pre>\n<p>Using this versioning strategy, clients should pass the desired version in the HTTP <code>Accept<\/code> head.<\/p>\n<pre><code>curl -H Accept:application\/vnd.twitter-v1+json http:\/\/localhost:9292\/statuses\/public_timeline\n<\/code><\/pre>\n<p>By default, the first matching version is used when no <code>Accept<\/code> header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the <code>:strict<\/code> option. When this option is set to <code>true<\/code>, a <code>406 Not Acceptable<\/code> error is returned when no correct <code>Accept<\/code> header is supplied.<\/p>\n<p>When an invalid <code>Accept<\/code> header is supplied, a <code>406 Not Acceptable<\/code> error is returned if the <code>:cascade<\/code> option is set to <code>false<\/code>. Otherwise a <code>404 Not Found<\/code> error is returned by Rack if no other route matches.<\/p>\n<h3>HTTP Status Code<\/h3>\n<p>By default Grape returns a 200 status code for <code>GET<\/code>-Requests and 201 for <code>POST<\/code>-Requests. You can use <code>status<\/code> to query and set the actual HTTP Status Code<\/p>\n<pre><code>post do\n  status 202\n\n  if status == 200\n     # do some thing\n  end\nend\n<\/code><\/pre>\n<p>You can also use one of status codes symbols that are provided by Rack utils<\/p>\n<pre><code>post do\n  status :no_content\nend\n<\/code><\/pre>\n<h3>Accept-Version Header<\/h3>\n<pre><code>version 'v1', using: :accept_version_header\n<\/code><\/pre>\n<p>Using this versioning strategy, clients should pass the desired version in the HTTP <code>Accept-Version<\/code> header.<\/p>\n<pre><code>curl -H \"Accept-Version:v1\" http:\/\/localhost:9292\/statuses\/public_timeline\n<\/code><\/pre>\n<p>By default, the first matching version is used when no <code>Accept-Version<\/code> header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the <code>:strict<\/code> option. When this option is set to <code>true<\/code>, a <code>406 Not Acceptable<\/code> error is returned when no correct <code>Accept<\/code> header is supplied.<\/p>\n<h3>Param<\/h3>\n<pre><code>version 'v1', using: :param\n<\/code><\/pre>\n<p>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.<\/p>\n<pre><code>curl http:\/\/localhost:9292\/statuses\/public_timeline?apiver=v1\n<\/code><\/pre>\n<p>The default name for the query parameter is \u2018apiver\u2019 but can be specified using the <code>:parameter<\/code> option.<\/p>\n<pre><code>version 'v1', using: :param, parameter: \"v\"\n<\/code><\/pre>\n<pre><code>curl http:\/\/localhost:9292\/statuses\/public_timeline?v=v1\n<\/code><\/pre>\n<h2>Describing Methods<\/h2>\n<p>You can add a description to API methods and namespaces.<\/p>\n<pre><code>desc \"Returns your public timeline.\" do\n  detail 'more details'\n  params  API::Entities::Status.documentation\n  success API::Entities::Entity\n  failure [[401, 'Unauthorized', \"Entities::Error\"]]\n  named 'My named route'\n  headers [XAuthToken: {\n             description: 'Valdates your identity',\n             required: true\n           },\n           XOptionalHeader: {\n             description: 'Not really needed',\n            required: false\n           }\n          ]\nend\nget :public_timeline do\n  Status.limit(20)\nend\n<\/code><\/pre>\n<ul>\n<li><code>detail<\/code>: A more enhanced description<\/li>\n<li><code>params<\/code>: Define parameters directly from an <code>Entity<\/code><\/li>\n<li><code>success<\/code>: (former entity) The <code>Entity<\/code> to be used to present by default this route<\/li>\n<li><code>failure<\/code>: (former http_codes) A definition of the used failure HTTP Codes and Entities<\/li>\n<li><code>named<\/code>: A helper to give a route a name and find it with this name in the documentation Hash<\/li>\n<li><code>headers<\/code>: A definition of the used Headers<\/li>\n<\/ul>\n<h2>Parameters<\/h2>\n<p>Request parameters are available through the <code>params<\/code> hash object. This includes <code>GET<\/code>, <code>POST<\/code> and <code>PUT<\/code> parameters, along with any named parameters you specify in your route strings.<\/p>\n<pre><code>get :public_timeline do\n  Status.order(params[:sort_by])\nend\n<\/code><\/pre>\n<p>Parameters are automatically populated from the request body on <code>POST<\/code> and <code>PUT<\/code> for form input, JSON and XML content-types.<\/p>\n<p>The request:<\/p>\n<pre><code>curl -d '{\"text\": \"140 characters\"}' 'http:\/\/localhost:9292\/statuses' -H Content-Type:application\/json -v\n<\/code><\/pre>\n<p>The Grape endpoint:<\/p>\n<pre><code>post '\/statuses' do\n  Status.create!(text: params[:text])\nend\n<\/code><\/pre>\n<p>Multipart POSTs and PUTs are supported as well.<\/p>\n<p>The request:<\/p>\n<pre><code>curl --form image_file='@image.jpg;type=image\/jpg' http:\/\/localhost:9292\/upload\n<\/code><\/pre>\n<p>The Grape endpoint:<\/p>\n<pre><code>post \"upload\" do\n  # file in params[:image_file]\nend\n<\/code><\/pre>\n<p>In the case of conflict between either of:<\/p>\n<ul>\n<li>route string parameters<\/li>\n<li><code>GET<\/code>, <code>POST<\/code> and <code>PUT<\/code> parameters<\/li>\n<li>the contents of the request body on <code>POST<\/code> and <code>PUT<\/code><\/li>\n<\/ul>\n<p>route string parameters will have precedence.<\/p>\n<h4>Declared<\/h4>\n<p>Grape allows you to access only the parameters that have been declared by your <code>params<\/code> block. It filters out the params that have been passed, but are not allowed. Let\u2019s have the following api:<\/p>\n<pre><code>format :json\n\npost 'users\/signup' do\n  { \"declared_params\" =&gt; declared(params) }\nend\n<\/code><\/pre>\n<p>If we do not specify any params, declared will return an empty Hashie::Mash instance.<\/p>\n<p><strong>Request<\/strong><\/p>\n<pre><code>curl -X POST -H \"Content-Type: application\/json\" localhost:9292\/users\/signup -d '{\"user\": {\"first_name\":\"first name\", \"last_name\": \"last name\"}}'\n<\/code><\/pre>\n<p><strong>Response<\/strong><\/p>\n<pre><code>{\n  \"declared_params\": {}\n}\n\n<\/code><\/pre>\n<p>Once we add parameters requirements, grape will start returning only the declared params.<\/p>\n<pre><code>format :json\n\nparams do\n  requires :user, type: Hash do\n    requires :first_name, type: String\n    requires :last_name, type: String\n  end\nend\n\npost 'users\/signup' do\n  { \"declared_params\" =&gt; declared(params) }\nend\n<\/code><\/pre>\n<p><strong>Request<\/strong><\/p>\n<pre><code>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\"}}'\n<\/code><\/pre>\n<p><strong>Response<\/strong><\/p>\n<pre><code>{\n  \"declared_params\": {\n    \"user\": {\n      \"first_name\": \"first name\",\n      \"last_name\": \"last name\"\n    }\n  }\n}\n<\/code><\/pre>\n<p>Returned hash is a Hashie::Mash instance so you can access parameters via dot notation:<\/p>\n<pre><code>  declared(params).user == declared(params)[\"user\"]\n<\/code><\/pre>\n<h4>Include missing<\/h4>\n<p>By default <code>declared(params)<\/code> returns parameters that has <code>nil<\/code> value. If you want to return only the parameters that have any value, you can use the <code>include_missing<\/code> option. By default it is <code>true<\/code>. Let\u2019s have the following api:<\/p>\n<pre><code>format :json\n\nparams do\n  requires :first_name, type: String\n  optional :last_name, type: String\nend\n\npost 'users\/signup' do\n  { \"declared_params\" =&gt; declared(params, include_missing: false) }\nend\n<\/code><\/pre>\n<p><strong>Request<\/strong><\/p>\n<pre><code>curl -X POST -H \"Content-Type: application\/json\" localhost:9292\/users\/signup -d '{\"user\": {\"first_name\":\"first name\", \"random\": \"never shown\"}}'\n<\/code><\/pre>\n<p><strong>Response with include_missing:false<\/strong><\/p>\n<pre><code>{\n  \"declared_params\": {\n    \"user\": {\n      \"first_name\": \"first name\"\n    }\n  }\n}\n<\/code><\/pre>\n<p><strong>Response with include_missing:true<\/strong><\/p>\n<pre><code>{\n  \"declared_params\": {\n    \"first_name\": \"first name\",\n    \"last_name\": null\n  }\n}\n<\/code><\/pre>\n<p>It also works on nested hashes:<\/p>\n<pre><code>format :json\n\nparams do\n  requires :user, :type =&gt; Hash do\n    requires :first_name, type: String\n    optional :last_name, type: String\n    requires :address, :type =&gt; Hash do\n      requires :city, type: String\n      optional :region, type: String\n    end\n  end\nend\n\npost 'users\/signup' do\n  { \"declared_params\" =&gt; declared(params, include_missing: false) }\nend\n<\/code><\/pre>\n<p><strong>Request<\/strong><\/p>\n<pre><code>curl -X POST -H \"Content-Type: application\/json\" localhost:9292\/users\/signup -d '{\"user\": {\"first_name\":\"first name\", \"random\": \"never shown\", \"address\": { \"city\": \"SF\"}}}'\n<\/code><\/pre>\n<p><strong>Response with include_missing:false<\/strong><\/p>\n<pre><code>{\n  \"declared_params\": {\n    \"user\": {\n      \"first_name\": \"first name\",\n      \"address\": {\n        \"city\": \"SF\"\n      }\n    }\n  }\n}\n<\/code><\/pre>\n<p><strong>Response with include_missing:true<\/strong><\/p>\n<pre><code>{\n  \"declared_params\": {\n    \"user\": {\n      \"first_name\": \"first name\",\n      \"last_name\": null,\n      \"address\": {\n        \"city\": \"Zurich\",\n        \"region\": null\n      }\n    }\n  }\n}\n<\/code><\/pre>\n<p>Note that an attribute with a <code>nil<\/code> value is not considered <em>missing<\/em> and will also be returned when <code>include_missing<\/code> is set to <code>false<\/code>:<\/p>\n<p><strong>Request<\/strong><\/p>\n<pre><code>curl -X POST -H \"Content-Type: application\/json\" localhost:9292\/users\/signup -d '{\"user\": {\"first_name\":\"first name\", \"last_name\": null, \"address\": { \"city\": \"SF\"}}}'\n<\/code><\/pre>\n<p><strong>Response with include_missing:false<\/strong><\/p>\n<pre><code>{\n  \"declared_params\": {\n    \"user\": {\n      \"first_name\": \"first name\",\n      \"last_name\": null,\n      \"address\": { \"city\": \"SF\"}\n    }\n  }\n}\n<\/code><\/pre>\n<h2>Parameter Validation and Coercion<\/h2>\n<p>You can define validations and coercion options for your parameters using a <code>params<\/code> block.<\/p>\n<pre><code>params do\n  requires :id, type: Integer\n  optional :text, type: String, regexp: \/^[a-z]+$\/\n  group :media do\n    requires :url\n  end\n  optional :audio do\n    requires :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3\n  end\n  mutually_exclusive :media, :audio\nend\nput ':id' do\n  # params[:id] is an Integer\nend\n<\/code><\/pre>\n<p>When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.<\/p>\n<p>Optional parameters can have a default value.<\/p>\n<pre><code>params do\n  optional :color, type: String, default: 'blue'\n  optional :random_number, type: Integer, default: -&gt; { Random.rand(1..100) }\n  optional :non_random_number, type: Integer, default:  Random.rand(1..100)\nend\n<\/code><\/pre>\n<p>Note that default values will be passed through to any validation options specified. The following example will always fail if <code>:color<\/code> is not explicitly provided.<\/p>\n<pre><code>params do\n  optional :color, type: String, default: 'blue', values: ['red', 'green']\nend\n<\/code><\/pre>\n<p>The correct implementation is to ensure the default value passes all validations.<\/p>\n<pre><code>params do\n  optional :color, type: String, default: 'blue', values: ['blue', 'red', 'green']\nend\n<\/code><\/pre>\n<h4>Validation of Nested Parameters<\/h4>\n<p>Parameters can be nested using <code>group<\/code> or by calling <code>requires<\/code> or <code>optional<\/code> with a block. In the above example, this means <code>params[:media][:url]<\/code> is required along with <code>params[:id]<\/code>, and <code>params[:audio][:format]<\/code> is required only if <code>params[:audio]<\/code> is present. With a block, <code>group<\/code>, <code>requires<\/code> and <code>optional<\/code> accept an additional option <code>type<\/code> which can be either <code>Array<\/code> or <code>Hash<\/code>, and defaults to <code>Array<\/code>. Depending on the value, the nested parameters will be treated either as values of a hash or as values of hashes in an array.<\/p>\n<pre><code>params do\n  optional :preferences, type: Array do\n    requires :key\n    requires :value\n  end\n\n  requires :name, type: Hash do\n    requires :first_name\n    requires :last_name\n  end\nend\n<\/code><\/pre>\n<h3>Built-in Validators<\/h3>\n<h4><code>allow_blank<\/code><\/h4>\n<p>Parameters can be defined as <code>allow_blank<\/code>, ensuring that they contain a value. By default, <code>requires<\/code> only validates that a parameter was sent in the request, regardless its value. With <code>allow_blank: false<\/code>, empty values or whitespace only values are invalid.<\/p>\n<p><code>allow_blank<\/code> can be combined with both <code>requires<\/code> and <code>optional<\/code>. If the parameter is required, it has to contain a value. If it\u2019s optional, it\u2019s possible to not send it in the request, but if it\u2019s being sent, it has to have some value, and not an empty string\/only whitespaces.<\/p>\n<pre><code>params do\n  requires :username, allow_blank: false\n  optional :first_name, allow_blank: false\nend\n<\/code><\/pre>\n<h4><code>values<\/code><\/h4>\n<p>Parameters can be restricted to a specific set of values with the <code>:values<\/code> option.<\/p>\n<p>Default values are eagerly evaluated. Above <code>:non_random_number<\/code> will evaluate to the same number for each call to the endpoint of this <code>params<\/code> block. To have the default evaluate lazily with each request use a lambda, like <code>:random_number<\/code> above.<\/p>\n<pre><code>params do\n  requires :status, type: Symbol, values: [:not_started, :processing, :done]\n  optional :numbers, type: Array[Integer], default: 1, values: [1, 2, 3, 5, 8]\nend\n<\/code><\/pre>\n<p>Supplying a range to the <code>:values<\/code> option ensures that the parameter is (or parameters are) included in that range (using <code>Range#include?<\/code>).<\/p>\n<pre><code>params do\n  requires :latitude, type: Float, values: -90.0..+90.0\n  requires :longitude, type: Float, values: -180.0..+180.0\n  optional :letters, type: Array[String], values: 'a'..'z'\nend\n<\/code><\/pre>\n<p>Note that <em>both<\/em> range endpoints have to be a <code>#kind_of?<\/code> your <code>:type<\/code> option (if you don\u2019t supplied the <code>:type<\/code> option, it will be guessed to be equal to the class of the range\u2019s first endpoint). So the following is invalid:<\/p>\n<pre><code>params do\n  requires :invalid1, type: Float, values: 0..10 # 0.kind_of?(Float) =&gt; false\n  optional :invalid2, values: 0..10.0 # 10.0.kind_of?(0.class) =&gt; false\nend\n<\/code><\/pre>\n<p>The <code>:values<\/code> option can also be supplied with a <code>Proc<\/code>, evaluated lazily with each request. For example, given a status model you may want to restrict by hashtags that you have previously defined in the <code>HashTag<\/code> model.<\/p>\n<pre><code>params do\n  requires :hashtag, type: String, values: -&gt; { Hashtag.all.map(&amp;:tag) }\nend\n<\/code><\/pre>\n<h4><code>regexp<\/code><\/h4>\n<p>Parameters can be restricted to match a specific regular expression with the <code>:regexp<\/code> option. If the value does not match the regular expression an error will be returned. Note that this is true for both <code>requires<\/code> and <code>optional<\/code> parameters.<\/p>\n<pre><code>params do\n  requires :email, regexp: \/.+@.+\/\nend\n<\/code><\/pre>\n<p>The validator will pass if the parameter was sent without value. To ensure that the parameter contains a value, use <code>allow_blank: false<\/code>.<\/p>\n<pre><code>params do\n  requires :email, allow_blank: false, regexp: \/.+@.+\/\nend\n<\/code><\/pre>\n<h4><code>mutually_exclusive<\/code><\/h4>\n<p>Parameters can be defined as <code>mutually_exclusive<\/code>, ensuring that they aren\u2019t present at the same time in a request.<\/p>\n<pre><code>params do\n  optional :beer\n  optional :wine\n  mutually_exclusive :beer, :wine\nend\n<\/code><\/pre>\n<p>Multiple sets can be defined:<\/p>\n<pre><code>params do\n  optional :beer\n  optional :wine\n  mutually_exclusive :beer, :wine\n  optional :scotch\n  optional :aquavit\n  mutually_exclusive :scotch, :aquavit\nend\n<\/code><\/pre>\n<p><strong>Warning<\/strong>: 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.<\/p>\n<h4><code>exactly_one_of<\/code><\/h4>\n<p>Parameters can be defined as \u2018exactly_one_of\u2019, ensuring that exactly one parameter gets selected.<\/p>\n<pre><code>params do\n  optional :beer\n  optional :wine\n  exactly_one_of :beer, :wine\nend\n<\/code><\/pre>\n<h4><code>at_least_one_of<\/code><\/h4>\n<p>Parameters can be defined as \u2018at_least_one_of\u2019, ensuring that at least one parameter gets selected.<\/p>\n<pre><code>params do\n  optional :beer\n  optional :wine\n  optional :juice\n  at_least_one_of :beer, :wine, :juice\nend\n<\/code><\/pre>\n<h4><code>all_or_none_of<\/code><\/h4>\n<p>Parameters can be defined as \u2018all_or_none_of\u2019, ensuring that all or none of parameters gets selected.<\/p>\n<pre><code>params do\n  optional :beer\n  optional :wine\n  optional :juice\n  all_or_none_of :beer, :wine, :juice\nend\n<\/code><\/pre>\n<h4>Nested <code>mutually_exclusive<\/code>, <code>exactly_one_of<\/code>, <code>at_least_one_of<\/code>, <code>all_or_none_of<\/code><\/h4>\n<p>All of these methods can be used at any nested level.<\/p>\n<pre><code>params do\n  requires :food do\n    optional :meat\n    optional :fish\n    optional :rice\n    at_least_one_of :meat, :fish, :rice\n  end\n  group :drink do\n    optional :beer\n    optional :wine\n    optional :juice\n    exactly_one_of :beer, :wine, :juice\n  end\n  optional :dessert do\n    optional :cake\n    optional :icecream\n    mutually_exclusive :cake, :icecream\n  end\n  optional :recipe do\n    optional :oil\n    optional :meat\n    all_or_none_of :oil, :meat\n  end\nend\n<\/code><\/pre>\n<h3>Namespace Validation and Coercion<\/h3>\n<p>Namespaces allow parameter definitions and apply to every method within the namespace.<\/p>\n<pre><code>namespace :statuses do\n  params do\n    requires :user_id, type: Integer, desc: \"A user ID.\"\n  end\n  namespace \":user_id\" do\n    desc \"Retrieve a user's status.\"\n    params do\n      requires :status_id, type: Integer, desc: \"A status ID.\"\n    end\n    get \":status_id\" do\n      User.find(params[:user_id]).statuses.find(params[:status_id])\n    end\n  end\nend\n<\/code><\/pre>\n<p>The <code>namespace<\/code> method has a number of aliases, including: <code>group<\/code>, <code>resource<\/code>, <code>resources<\/code>, and <code>segment<\/code>. Use whichever reads the best for your API.<\/p>\n<p>You can conveniently define a route parameter as a namespace using <code>route_param<\/code>.<\/p>\n<pre><code>namespace :statuses do\n  route_param :id do\n    desc \"Returns all replies for a status.\"\n    get 'replies' do\n      Status.find(params[:id]).replies\n    end\n    desc \"Returns a status.\"\n    get do\n      Status.find(params[:id])\n    end\n  end\nend\n<\/code><\/pre>\n<h3>Custom Validators<\/h3>\n<pre><code>class AlphaNumeric &lt; Grape::Validations::Base\n  def validate_param!(attr_name, params)\n    unless params[attr_name] =~ \/^[[:alnum:]]+$\/\n      fail Grape::Exceptions::Validation, params: [@scope.full_name(attr_name)], message: \"must consist of alpha-numeric characters\"\n    end\n  end\nend\n<\/code><\/pre>\n<pre><code>params do\n  requires :text, alpha_numeric: true\nend\n<\/code><\/pre>\n<p>You can also create custom classes that take parameters.<\/p>\n<pre><code>class Length &lt; Grape::Validations::Base\n  def validate_param!(attr_name, params)\n    unless params[attr_name].length  'Invalid token.'\n<\/code><\/pre>\n<h2>Routes<\/h2>\n<p>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.<\/p>\n<pre><code>get ':id', requirements: { id: \/[0-9]*\/ } do\n  Status.find(params[:id])\nend\n\nnamespace :outer, requirements: { id: \/[0-9]*\/ } do\n  get :id do\n  end\n\n  get \":id\/edit\" do\n  end\nend\n<\/code><\/pre>\n<h2>Helpers<\/h2>\n<p>You can define helper methods that your endpoints can use with the <code>helpers<\/code> macro by either giving a block or a module.<\/p>\n<pre><code>module StatusHelpers\n  def user_info(user)\n    \"#{user} has statused #{user.statuses} status(s)\"\n  end\nend\n\nclass API &lt; Grape::API\n  # define helpers with a block\n  helpers do\n    def current_user\n      User.find(params[:user_id])\n    end\n  end\n\n  # or mix in a module\n  helpers StatusHelpers\n\n  get 'info' do\n    # helpers available in your endpoint and filters\n    user_info(current_user)\n  end\nend\n<\/code><\/pre>\n<p>You can define reusable <code>params<\/code> using <code>helpers<\/code>.<\/p>\n<pre><code>class API &lt; Grape::API\n  helpers do\n    params :pagination do\n      optional :page, type: Integer\n      optional :per_page, type: Integer\n    end\n  end\n\n  desc \"Get collection\"\n  params do\n    use :pagination # aliases: includes, use_scope\n  end\n  get do\n    Collection.page(params[:page]).per(params[:per_page])\n  end\nend\n<\/code><\/pre>\n<p>You can also define reusable <code>params<\/code> using shared helpers.<\/p>\n<pre><code>module SharedParams\n  extend Grape::API::Helpers\n\n  params :period do\n    optional :start_date\n    optional :end_date\n  end\n\n  params :pagination do\n    optional :page, type: Integer\n    optional :per_page, type: Integer\n  end\nend\n\nclass API &lt; Grape::API\n  helpers SharedParams\n\n  desc \"Get collection.\"\n  params do\n    use :period, :pagination\n  end\n\n  get do\n    Collection\n      .from(params[:start_date])\n      .to(params[:end_date])\n      .page(params[:page])\n      .per(params[:per_page])\n  end\nend\n<\/code><\/pre>\n<p>Helpers support blocks that can help set default values. The following API can return a collection sorted by <code>id<\/code> or <code>created_at<\/code> in <code>asc<\/code> or <code>desc<\/code> order.<\/p>\n<pre><code>module SharedParams\n  extend Grape::API::Helpers\n\n  params :order do |options|\n    optional :order_by, type:Symbol, values:options[:order_by], default:options[:default_order_by]\n    optional :order, type:Symbol, values:%i(asc desc), default:options[:default_order]\n  end\nend\n\nclass API &lt; Grape::API\n  helpers SharedParams\n\n  desc \"Get a sorted collection.\"\n  params do\n    use :order, order_by:%i(id created_at), default_order_by: :created_at, default_order: :asc\n  end\n\n  get do\n    Collection.send(params[:order], params[:order_by])\n  end\nend\n<\/code><\/pre>\n<h2>Parameter Documentation<\/h2>\n<p>You can attach additional documentation to <code>params<\/code> using a <code>documentation<\/code> hash.<\/p>\n<pre><code>params do\n  optional :first_name, type: String, documentation: { example: 'Jim' }\n  requires :last_name, type: String, documentation: { example: 'Smith' }\nend\n<\/code><\/pre>\n<h2>Cookies<\/h2>\n<p>You can set, get and delete your cookies very simply using <code>cookies<\/code> method.<\/p>\n<pre><code>class API &lt; Grape::API\n  get 'status_count' do\n    cookies[:status_count] ||= 0\n    cookies[:status_count] += 1\n    { status_count: cookies[:status_count] }\n  end\n\n  delete 'status_count' do\n    { status_count: cookies.delete(:status_count) }\n  end\nend\n<\/code><\/pre>\n<p>Use a hash-based syntax to set more than one value.<\/p>\n<pre><code>cookies[:status_count] = {\n  value: 0,\n  expires: Time.tomorrow,\n  domain: '.twitter.com',\n  path: '\/'\n}\n\ncookies[:status_count][:value] +=1\n<\/code><\/pre>\n<p>Delete a cookie with <code>delete<\/code>.<\/p>\n<pre><code>cookies.delete :status_count\n<\/code><\/pre>\n<p>Specify an optional path.<\/p>\n<pre><code>cookies.delete :status_count, path: '\/'\n<\/code><\/pre>\n<h2>Redirecting<\/h2>\n<p>You can redirect to a new url temporarily (302) or permanently (301).<\/p>\n<pre><code>redirect '\/statuses'\n<\/code><\/pre>\n<pre><code>redirect '\/statuses', permanent: true\n<\/code><\/pre>\n<h2>Allowed Methods<\/h2>\n<p>When you add a <code>GET<\/code> route for a resource, a route for the <code>HEAD<\/code> method will also be added automatically. You can disable this behavior with <code>do_not_route_head!<\/code>.<\/p>\n<pre><code>class API &lt; Grape::API\n  do_not_route_head!\n\n  get '\/example' do\n    # only responds to GET\n  end\nend\n<\/code><\/pre>\n<p>When you add a route for a resource, a route for the <code>OPTIONS<\/code> method will also be added. The response to an OPTIONS request will include an \u201cAllow\u201d header listing the supported methods.<\/p>\n<pre><code>class API &lt; Grape::API\n  get '\/rt_count' do\n    { rt_count: current_user.rt_count }\n  end\n\n  params do\n    requires :value, type: Integer, desc: 'Value to add to the rt count.'\n  end\n  put '\/rt_count' do\n    current_user.rt_count += params[:value].to_i\n    { rt_count: current_user.rt_count }\n  end\nend\n<\/code><\/pre>\n<pre><code>curl -v -X OPTIONS http:\/\/localhost:3000\/rt_count\n\n&gt; OPTIONS \/rt_count HTTP\/1.1\n&gt;\n&lt; HTTP\/1.1 204 No Content\n&lt; Allow: OPTIONS, GET, PUT\n<\/code><\/pre>\n<p>You can disable this behavior with <code>do_not_route_options!<\/code>.<\/p>\n<p>If a request for a resource is made with an unsupported HTTP method, an HTTP 405 (Method Not Allowed) response will be returned.<\/p>\n<pre><code>curl -X DELETE -v http:\/\/localhost:3000\/rt_count\/\n\n&gt; DELETE \/rt_count\/ HTTP\/1.1\n&gt; Host: localhost:3000\n&gt;\n&lt; HTTP\/1.1 405 Method Not Allowed\n&lt; Allow: OPTIONS, GET, PUT\n<\/code><\/pre>\n<h2>Raising Exceptions<\/h2>\n<p>You can abort the execution of an API method by raising errors with <code>error!<\/code>.<\/p>\n<pre><code>error! 'Access Denied', 401\n<\/code><\/pre>\n<p>You can also return JSON formatted objects by raising error! and passing a hash instead of a message.<\/p>\n<pre><code>error!({ error: \"unexpected error\", detail: \"missing widget\" }, 500)\n<\/code><\/pre>\n<p>You can present documented errors with a Grape entity using the the grape-entity gem.<\/p>\n<pre><code>module API\n  class Error &lt; Grape::Entity\n    expose :code\n    expose :message\n  end\nend\n<\/code><\/pre>\n<p>The following example specifies the entity to use in the <code>http_codes<\/code> definition.<\/p>\n<pre><code>desc 'My Route' do\n failure [[408, 'Unauthorized', API::Error]]\nend\nerror!({ message: 'Unauthorized' }, 408)\n<\/code><\/pre>\n<p>The following example specifies the presented entity explicitly in the error message.<\/p>\n<pre><code>desc 'My Route' do\n failure [[408, 'Unauthorized']]\nend\nerror!({ message: 'Unauthorized', with: API::Error }, 408)\n<\/code><\/pre>\n<h3>Default Error HTTP Status Code<\/h3>\n<p>By default Grape returns a 500 status code from <code>error!<\/code>. You can change this with <code>default_error_status<\/code>.<\/p>\n<pre><code>class API &lt; Grape::API\n  default_error_status 400\n  get '\/example' do\n    error! \"This should have http status code 400\"\n  end\nend\n<\/code><\/pre>\n<h3>Handling 404<\/h3>\n<p>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:<\/p>\n<pre><code>route :any, '*path' do\n  error! # or something else\nend\n<\/code><\/pre>\n<p>It is very crucial to <strong>define this endpoint at the very end of your API<\/strong>, as it literally accepts every request.<\/p>\n<h2>Exception Handling<\/h2>\n<p>Grape can be told to rescue all exceptions and return them in the API format.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  rescue_from :all\nend\n<\/code><\/pre>\n<p>You can also rescue specific exceptions.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  rescue_from ArgumentError, UserDefinedError\nend\n<\/code><\/pre>\n<p>In this case <code>UserDefinedError<\/code> must be inherited from <code>StandardError<\/code>.<\/p>\n<p>The error format will match the request format. See \u201cContent-Types\u201d below.<\/p>\n<p>Custom error formatters for existing and additional types can be defined with a proc.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  error_formatter :txt, lambda { |message, backtrace, options, env|\n    \"error: #{message} from #{backtrace}\"\n  }\nend\n<\/code><\/pre>\n<p>You can also use a module or class.<\/p>\n<pre><code>module CustomFormatter\n  def self.call(message, backtrace, options, env)\n    { message: message, backtrace: backtrace }\n  end\nend\n\nclass Twitter::API &lt; Grape::API\n  error_formatter :custom, CustomFormatter\nend\n<\/code><\/pre>\n<p>You can rescue all exceptions with a code block. The <code>error!<\/code> wrapper automatically sets the default error code and content-type.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  rescue_from :all do |e|\n    error!(\"rescued from #{e.class.name}\")\n  end\nend\n<\/code><\/pre>\n<p>Optionally, you can set the format, status code and headers.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  format :json\n  rescue_from :all do |e|\n    error!({ error: \"Server error.\", 500, { 'Content-Type' =&gt; 'text\/error' } })\n  end\nend\n<\/code><\/pre>\n<p>You can also rescue specific exceptions with a code block and handle the Rack response at the lowest level.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  rescue_from :all do |e|\n    Rack::Response.new([ e.message ], 500, { \"Content-type\" =&gt; \"text\/error\" }).finish\n  end\nend\n<\/code><\/pre>\n<p>Or rescue specific exceptions.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  rescue_from ArgumentError do |e|\n    error!(\"ArgumentError: #{e.message}\")\n  end\n\n  rescue_from NotImplementedError do |e|\n    error!(\"NotImplementedError: #{e.message}\")\n  end\nend\n<\/code><\/pre>\n<p>By default, <code>rescue_from<\/code> will rescue the exceptions listed and all their subclasses.<\/p>\n<p>Assume you have the following exception classes defined.<\/p>\n<pre><code>module APIErrors\n  class ParentError &lt; StandardError; end\n  class ChildError &lt; ParentError; end\nend\n<\/code><\/pre>\n<p>Then the following <code>rescue_from<\/code> clause will rescue exceptions of type <code>APIErrors::ParentError<\/code> and its subclasses (in this case <code>APIErrors::ChildError<\/code>).<\/p>\n<pre><code>rescue_from APIErrors::ParentError do |e|\n    error!({\n      error: \"#{e.class} error\",\n      message: e.message\n    }, e.status)\nend\n<\/code><\/pre>\n<p>To only rescue the base exception class, set <code>rescue_subclasses: false<\/code>. The code below will rescue exceptions of type <code>RuntimeError<\/code> but <em>not<\/em> its subclasses.<\/p>\n<pre><code>rescue_from RuntimeError, rescue_subclasses: false do |e|\n    error!({\n      status: e.status,\n      message: e.message,\n      errors: e.errors\n    }, e.status)\nend\n<\/code><\/pre>\n<h4>Rails 3.x<\/h4>\n<p>When mounted inside containers, such as Rails 3.x, errors like \u201c404 Not Found\u201d or \u201c406 Not Acceptable\u201d will likely be handled and rendered by Rails handlers. For instance, accessing a nonexistent route \u201c\/api\/foo\u201d raises a 404, which inside rails will ultimately be translated to an <code>ActionController::RoutingError<\/code>, which most likely will get rendered to a HTML error page.<\/p>\n<p>Most APIs will enjoy preventing downstream handlers from handling errors. You may set the <code>:cascade<\/code> option to <code>false<\/code> for the entire API or separately on specific <code>version<\/code> definitions, which will remove the <code>X-Cascade: true<\/code> header from API responses.<\/p>\n<pre><code>cascade false\n<\/code><\/pre>\n<pre><code>version 'v1', using: :header, vendor: 'twitter', cascade: false\n<\/code><\/pre>\n<h2>Logging<\/h2>\n<p><code>Grape::API<\/code> provides a <code>logger<\/code> method which by default will return an instance of the <code>Logger<\/code> class from Ruby\u2019s standard library.<\/p>\n<p>To log messages from within an endpoint, you need to define a helper to make the logger available in the endpoint context.<\/p>\n<pre><code>class API &lt; Grape::API\n  helpers do\n    def logger\n      API.logger\n    end\n  end\n  post '\/statuses' do\n    # ...\n    logger.info \"#{current_user} has statused\"\n  end\nend\n<\/code><\/pre>\n<p>You can also set your own logger.<\/p>\n<pre><code>class MyLogger\n  def warning(message)\n    puts \"this is a warning: #{message}\"\n  end\nend\n\nclass API &lt; Grape::API\n  logger MyLogger.new\n  helpers do\n    def logger\n      API.logger\n    end\n  end\n  get '\/statuses' do\n    logger.warning \"#{current_user} has statused\"\n  end\nend\n<\/code><\/pre>\n<p>For similar to Rails request logging try the grape_logging gem.<\/p>\n<h2>API Formats<\/h2>\n<p>Your API can declare which content-types to support by using <code>content_type<\/code>. If you do not specify any, Grape will support <em>XML<\/em>, <em>JSON<\/em>, <em>BINARY<\/em>, and <em>TXT<\/em> content-types. The default format is <code>:txt<\/code>; you can change this with <code>default_format<\/code>. Essentially, the two APIs below are equivalent.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  # no content_type declarations, so Grape uses the defaults\nend\n\nclass Twitter::API &lt; Grape::API\n  # the following declarations are equivalent to the defaults\n\n  content_type :xml, 'application\/xml'\n  content_type :json, 'application\/json'\n  content_type :binary, 'application\/octet-stream'\n  content_type :txt, 'text\/plain'\n\n  default_format :txt\nend\n<\/code><\/pre>\n<p>If you declare any <code>content_type<\/code> whatsoever, the Grape defaults will be overridden. For example, the following API will only support the <code>:xml<\/code> and <code>:rss<\/code> content-types, but not <code>:txt<\/code>, <code>:json<\/code>, or <code>:binary<\/code>. Importantly, this means the <code>:txt<\/code> default format is not supported! So, make sure to set a new <code>default_format<\/code>.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  content_type :xml, 'application\/xml'\n  content_type :rss, 'application\/xml+rss'\n\n  default_format :xml\nend\n<\/code><\/pre>\n<p>Serialization takes place automatically. For example, you do not have to call <code>to_json<\/code> in each JSON API endpoint implementation. The response format (and thus the automatic serialization) is determined in the following order:<\/p>\n<ul>\n<li>Use the file extension, if specified. If the file is .json, choose the JSON format.<\/li>\n<li>Use the value of the <code>format<\/code> parameter in the query string, if specified.<\/li>\n<li>Use the format set by the <code>format<\/code> option, if specified.<\/li>\n<li>Attempt to find an acceptable format from the <code>Accept<\/code> header.<\/li>\n<li>Use the default format, if specified by the <code>default_format<\/code> option.<\/li>\n<li>Default to <code>:txt<\/code>.<\/li>\n<\/ul>\n<p>For example, consider the following API.<\/p>\n<pre><code>class MultipleFormatAPI &lt; Grape::API\n  content_type :xml, 'application\/xml'\n  content_type :json, 'application\/json'\n\n  default_format :json\n\n  get :hello do\n    { hello: 'world' }\n  end\nend\n<\/code><\/pre>\n<ul>\n<li><code>GET \/hello<\/code> (with an <code>Accept: *\/*<\/code> header) does not have an extension or a <code>format<\/code> parameter, so it will respond with JSON (the default format).<\/li>\n<li><code>GET \/hello.xml<\/code> has a recognized extension, so it will respond with XML.<\/li>\n<li><code>GET \/hello?format=xml<\/code> has a recognized <code>format<\/code> parameter, so it will respond with XML.<\/li>\n<li><code>GET \/hello.xml?format=json<\/code> has a recognized extension (which takes precedence over the <code>format<\/code> parameter), so it will respond with XML.<\/li>\n<li><code>GET \/hello.xls<\/code> (with an <code>Accept: *\/*<\/code> header) has an extension, but that extension is not recognized, so it will respond with JSON (the default format).<\/li>\n<li><code>GET \/hello.xls<\/code> with an <code>Accept: application\/xml<\/code> header has an unrecognized extension, but the <code>Accept<\/code> header corresponds to a recognized format, so it will respond with XML.<\/li>\n<li><code>GET \/hello.xls<\/code> with an <code>Accept: text\/plain<\/code> header has an unrecognized extension <em>and<\/em> an unrecognized <code>Accept<\/code> header, so it will respond with JSON (the default format).<\/li>\n<\/ul>\n<p>You can override this process explicitly by specifying <code>env['api.format']<\/code> 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.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  post \"attachment\" do\n    filename = params[:file][:filename]\n    content_type MIME::Types.type_for(filename)[0].to_s\n    env['api.format'] = :binary # there's no formatter for :binary, data will be returned \"as is\"\n    header \"Content-Disposition\", \"attachment; filename*=UTF-8''#{URI.escape(filename)}\"\n    params[:file][:tempfile].read\n  end\nend\n<\/code><\/pre>\n<p>You can have your API only respond to a single format with <code>format<\/code>. If you use this, the API will <strong>not<\/strong> respond to file extensions other than specified in <code>format<\/code>. For example, consider the following API.<\/p>\n<pre><code>class SingleFormatAPI &lt; Grape::API\n  format :json\n\n  get :hello do\n    { hello: 'world' }\n  end\nend\n<\/code><\/pre>\n<ul>\n<li><code>GET \/hello<\/code> will respond with JSON.<\/li>\n<li><code>GET \/hello.json<\/code> will respond with JSON.<\/li>\n<li><code>GET \/hello.xml<\/code>, <code>GET \/hello.foobar<\/code>, or <em>any<\/em> other extension will respond with an HTTP 404 error code.<\/li>\n<li><code>GET \/hello?format=xml<\/code> will respond with an HTTP 406 error code, because the XML format specified by the request parameter is not supported.<\/li>\n<li><code>GET \/hello<\/code> with an <code>Accept: application\/xml<\/code> header will still respond with JSON, since it could not negotiate a recognized content-type from the headers and JSON is the effective default.<\/li>\n<\/ul>\n<p>The formats apply to parsing, too. The following API will only respond to the JSON content-type and will not parse any other input than <code>application\/json<\/code>, <code>application\/x-www-form-urlencoded<\/code>, <code>multipart\/form-data<\/code>, <code>multipart\/related<\/code> and <code>multipart\/mixed<\/code>. All other requests will fail with an HTTP 406 error code.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  format :json\nend\n<\/code><\/pre>\n<p>When the content-type is omitted, Grape will return a 406 error code unless <code>default_format<\/code> is specified. The following API will try to parse any data without a content-type using a JSON parser.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  format :json\n  default_format :json\nend\n<\/code><\/pre>\n<p>If you combine <code>format<\/code> with <code>rescue_from :all<\/code>, errors will be rendered using the same format. If you do not want this behavior, set the default error formatter with <code>default_error_formatter<\/code>.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  format :json\n  content_type :txt, \"text\/plain\"\n  default_error_formatter :txt\nend\n<\/code><\/pre>\n<p>Custom formatters for existing and additional types can be defined with a proc.<\/p>\n<pre><code>class Twitter::API &lt; Grape::API\n  content_type :xls, \"application\/vnd.ms-excel\"\n  formatter :xls, lambda { |object, env| object.to_xls }\nend\n<\/code><\/pre>\n<p>You can also use a module or class.<\/p>\n<pre><code>module XlsFormatter\n  def self.call(object, env)\n    object.to_xls\n  end\nend\n\nclass Twitter::API &lt; Grape::API\n  content_type :xls, \"application\/vnd.ms-excel\"\n  formatter :xls, XlsFormatter\nend\n<\/code><\/pre>\n<p>Built-in formatters are the following.<\/p>\n<ul>\n<li><code>:json<\/code>: use object\u2019s <code>to_json<\/code> when available, otherwise call <code>MultiJson.dump<\/code><\/li>\n<li><code>:xml<\/code>: use object\u2019s <code>to_xml<\/code> when available, usually via <code>MultiXml<\/code>, otherwise call <code>to_s<\/code><\/li>\n<li><code>:txt<\/code>: use object\u2019s <code>to_txt<\/code> when available, otherwise <code>to_s<\/code><\/li>\n<li><code>:serializable_hash<\/code>: use object\u2019s <code>serializable_hash<\/code> when available, otherwise fallback to <code>:json<\/code><\/li>\n<li><code>:binary<\/code>: data will be returned \u201cas is\u201d<\/li>\n<\/ul>\n<h3>JSONP<\/h3>\n<p>Grape supports JSONP via Rack::JSONP, part of the rack-contrib gem. Add <code>rack-contrib<\/code> to your <code>Gemfile<\/code>.<\/p>\n<pre><code>require 'rack\/contrib'\n\nclass API &lt; Grape::API\n  use Rack::JSONP\n  format :json\n  get '\/' do\n    'Hello World'\n  end\nend\n<\/code><\/pre>\n<h3>CORS<\/h3>\n<p>Grape supports CORS via Rack::CORS, part of the rack-cors gem. Add <code>rack-cors<\/code> to your <code>Gemfile<\/code>, then use the middleware in your config.ru file.<\/p>\n<pre><code>require 'rack\/cors'\n\nuse Rack::Cors do\n  allow do\n    origins '*'\n    resource '*', headers: :any, methods: :get\n  end\nend\n\nrun Twitter::API\n\n<\/code><\/pre>\n<h2>Content-type<\/h2>\n<p>Content-type is set by the formatter. You can override the content-type of the response at runtime by setting the <code>Content-Type<\/code> header.<\/p>\n<pre><code>class API &lt; Grape::API\n  get '\/home_timeline_js' do\n    content_type \"application\/javascript\"\n    \"var statuses = ...;\"\n  end\nend\n<\/code><\/pre>\n<h2>API Data Formats<\/h2>\n<p>Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters section above. It also supports custom data formats. You must declare additional content-types via <code>content_type<\/code> and optionally supply a parser via <code>parser<\/code> unless a parser is already available within Grape to enable a custom format. Such a parser can be a function or a class.<\/p>\n<p>With a parser, parsed data is available \u201cas-is\u201d in <code>env['api.request.body']<\/code>. Without a parser, data is available \u201cas-is\u201d and in <code>env['api.request.input']<\/code>.<\/p>\n<p>The following example is a trivial parser that will assign any input with the \u201ctext\/custom\u201d content-type to <code>:value<\/code>. The parameter will be available via <code>params[:value]<\/code> inside the API call.<\/p>\n<pre><code>module CustomParser\n  def self.call(object, env)\n    { value: object.to_s }\n  end\nend\n<\/code><\/pre>\n<pre><code>content_type :txt, \"text\/plain\"\ncontent_type :custom, \"text\/custom\"\nparser :custom, CustomParser\n\nput \"value\" do\n  params[:value]\nend\n<\/code><\/pre>\n<p>You can invoke the above API as follows.<\/p>\n<pre><code>curl -X PUT -d 'data' 'http:\/\/localhost:9292\/value' -H Content-Type:text\/custom -v\n<\/code><\/pre>\n<p>You can disable parsing for a content-type with <code>nil<\/code>. For example, <code>parser :json, nil<\/code> will disable JSON parsing altogether. The request data is then available as-is in <code>env['api.request.body']<\/code>.<\/p>\n<h2>RESTful Model Representations<\/h2>\n<p>Grape supports a range of ways to present your data with some help from a generic <code>present<\/code> method, which accepts two arguments: the object to be presented and the options associated with it. The options hash may include <code>:with<\/code>, which defines the entity to expose.<\/p>\n<h3>Grape Entities<\/h3>\n<p>Add the grape-entity gem to your Gemfile. Please refer to the grape-entity documentation for more details.<\/p>\n<p>The following example exposes statuses.<\/p>\n<pre><code>module API\n  module Entities\n    class Status &lt; Grape::Entity\n      expose :user_name\n      expose :text, documentation: { type: \"string\", desc: \"Status update text.\" }\n      expose :ip, if: { type: :full }\n      expose :user_type, :user_id, if: lambda { |status, options| status.user.public? }\n      expose :digest { |status, options| Digest::MD5.hexdigest(status.txt) }\n      expose :replies, using: API::Status, as: :replies\n    end\n  end\n\n  class Statuses &lt; Grape::API\n    version 'v1'\n\n    desc 'Statuses index' do\n      params: API::Entities::Status.documentation\n    end\n    get '\/statuses' do\n      statuses = Status.all\n      type = current_user.admin? ? :full : :default\n      present statuses, with: API::Entities::Status, type: type\n    end\n  end\nend\n<\/code><\/pre>\n<p>You can use entity documentation directly in the params block with <code>using: Entity.documentation<\/code>.<\/p>\n<pre><code>module API\n  class Statuses &lt; Grape::API\n    version 'v1'\n\n    desc 'Create a status'\n    params do\n      requires :all, except: [:ip], using: API::Entities::Status.documentation.except(:id)\n    end\n    post '\/status' do\n      Status.create! params\n    end\n  end\nend\n<\/code><\/pre>\n<p>You can present with multiple entities using an optional Symbol argument.<\/p>\n<pre><code>  get '\/statuses' do\n    statuses = Status.all.page(1).per(20)\n    present :total_page, 10\n    present :per_page, 20\n    present :statuses, statuses, with: API::Entities::Status\n  end\n<\/code><\/pre>\n<p>The response will be<\/p>\n<pre><code>  {\n    total_page: 10,\n    per_page: 20,\n    statuses: []\n  }\n<\/code><\/pre>\n<p>In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.<\/p>\n<pre><code>class Status\n  def entity\n    Entity.new(self)\n  end\n\n  class Entity &lt; Grape::Entity\n    expose :text, :user_id\n  end\nend\n<\/code><\/pre>\n<p>If you organize your entities this way, Grape will automatically detect the <code>Entity<\/code> class and use it to present your models. In this example, if you added <code>present Status.new<\/code> to your endpoint, Grape will automatically detect that there is a <code>Status::Entity<\/code> class and use that as the representative entity. This can still be overridden by using the <code>:with<\/code> option or an explicit <code>represents<\/code> call.<\/p>\n<p>You can present <code>hash<\/code> with <code>Grape::Presenters::Presenter<\/code> to keep things consistent.<\/p>\n<pre><code>get '\/users' do\n  present { id: 10, name: :dgz }, with: Grape::Presenters::Presenter\nend\n<\/code><\/pre>\n<p>The response will be<\/p>\n<pre><code>{\n  id:   10,\n  name: 'dgz'\n}\n<\/code><\/pre>\n<p>It has the same result with<\/p>\n<pre><code>get '\/users' do\n  present :id, 10\n  present :name, :dgz\nend\n<\/code><\/pre>\n<h3>Hypermedia and Roar<\/h3>\n<p>You can use Roar to render HAL or Collection+JSON with the help of grape-roar, which defines a custom JSON formatter and enables presenting entities with Grape\u2019s <code>present<\/code> keyword.<\/p>\n<h3>Rabl<\/h3>\n<p>You can use Rabl templates with the help of the grape-rabl gem, which defines a custom Grape Rabl formatter.<\/p>\n<h3>Active Model Serializers<\/h3>\n<p>You can use Active Model Serializers serializers with the help of the grape-active_model_serializers gem, which defines a custom Grape AMS formatter.<\/p>\n<h2>Sending Raw or No Data<\/h2>\n<p>In general, use the binary format to send raw data.<\/p>\n<pre><code>class API &lt; Grape::API\n  get '\/file' do\n    content_type 'application\/octet-stream'\n    File.binread 'file.bin'\n  end\nend\n<\/code><\/pre>\n<p>You can also set the response body explicitly with <code>body<\/code>.<\/p>\n<pre><code>class API &lt; Grape::API\n  get '\/' do\n    content_type 'text\/plain'\n    body 'Hello World'\n    # return value ignored\n  end\nend\n<\/code><\/pre>\n<p>Use <code>body false<\/code> to return <code>204 No Content<\/code> without any data or content-type.<\/p>\n<h2>Authentication<\/h2>\n<h3>Basic and Digest Auth<\/h3>\n<p>Grape has built-in Basic and Digest authentication (the given <code>block<\/code> is executed in the context of the current <code>Endpoint<\/code>). Authentication applies to the current namespace and any children, but not parents.<\/p>\n<pre><code>http_basic do |username, password|\n  # verify user's password here\n  { 'test' =&gt; 'password1' }[username] == password\nend\n<\/code><\/pre>\n<pre><code>http_digest({ realm: 'Test Api', opaque: 'app secret' }) do |username|\n  # lookup the user's password here\n  { 'user1' =&gt; 'password1' }[username]\nend\n<\/code><\/pre>\n<h3>Register custom middleware for authentication<\/h3>\n<p>Grape can use custom Middleware for authentication. How to implement these Middleware have a look at <code>Rack::Auth::Basic<\/code> or similar implementations.<\/p>\n<p>For registering a Middleware you need the following options:<\/p>\n<ul>\n<li><code>label<\/code> &#8211; the name for your authenticator to use it later<\/li>\n<li><code>MiddlewareClass<\/code> &#8211; the MiddlewareClass to use for authentication<\/li>\n<li><code>option_lookup_proc<\/code> &#8211; A Proc with one Argument to lookup the options at runtime (return value is an <code>Array<\/code> as Paramter for the Middleware).<\/li>\n<\/ul>\n<p>Example:<\/p>\n<pre><code>\nGrape::Middleware::Auth::Strategies.add(:my_auth, AuthMiddleware, -&gt;(options) { [options[:realm]] } )\n\n\nauth :my_auth, { realm: 'Test Api'} do |credentials|\n  # lookup the user's password here\n  { 'user1' =&gt; 'password1' }[username]\nend\n\n<\/code><\/pre>\n<p>Use warden-oauth2 or rack-oauth2 for OAuth2 support.<\/p>\n<h2>Describing and Inspecting an API<\/h2>\n<p>Grape routes can be reflected at runtime. This can notably be useful for generating documentation.<\/p>\n<p>Grape exposes arrays of API versions and compiled routes. Each route contains a <code>route_prefix<\/code>, <code>route_version<\/code>, <code>route_namespace<\/code>, <code>route_method<\/code>, <code>route_path<\/code> and <code>route_params<\/code>. You can add custom route settings to the route metadata with <code>route_setting<\/code>.<\/p>\n<pre><code>class TwitterAPI &lt; Grape::API\n  version 'v1'\n  desc \"Includes custom settings.\"\n  route_setting :custom, key: 'value'\n  get do\n\n  end\nend\n<\/code><\/pre>\n<p>Examine the routes at runtime.<\/p>\n<pre><code>TwitterAPI::versions # yields [ 'v1', 'v2' ]\nTwitterAPI::routes # yields an array of Grape::Route objects\nTwitterAPI::routes[0].route_version # =&gt; 'v1'\nTwitterAPI::routes[0].route_description # =&gt; 'Includes custom settings.'\nTwitterAPI::routes[0].route_settings[:custom] # =&gt; { key: 'value' }\n<\/code><\/pre>\n<h2>Current Route and Endpoint<\/h2>\n<p>It\u2019s possible to retrieve the information about the current route from within an API call with <code>route<\/code>.<\/p>\n<pre><code>class MyAPI &lt; Grape::API\n  desc \"Returns a description of a parameter.\"\n  params do\n    requires :id, type: Integer, desc: \"Identity.\"\n  end\n  get \"params\/:id\" do\n    route.route_params[params[:id]] # yields the parameter description\n  end\nend\n<\/code><\/pre>\n<p>The current endpoint responding to the request is <code>self<\/code> within the API block or <code>env['api.endpoint']<\/code> elsewhere. The endpoint has some interesting properties, such as <code>source<\/code> which gives you access to the original code block of the API implementation. This can be particularly useful for building a logger middleware.<\/p>\n<pre><code>class ApiLogger &lt; Grape::Middleware::Base\n  def before\n    file = env['api.endpoint'].source.source_location[0]\n    line = env['api.endpoint'].source.source_location[1]\n    logger.debug \"[api] #{file}:#{line}\"\n  end\nend\n<\/code><\/pre>\n<h2>Before and After<\/h2>\n<p>Blocks can be executed before or after every API call, using <code>before<\/code>, <code>after<\/code>, <code>before_validation<\/code> and <code>after_validation<\/code>.<\/p>\n<p>Before and after callbacks execute in the following order:<\/p>\n<ol>\n<li><code>before<\/code><\/li>\n<li><code>before_validation<\/code><\/li>\n<li><em>validations<\/em><\/li>\n<li><code>after_validation<\/code><\/li>\n<li><em>the API call<\/em><\/li>\n<li><code>after<\/code><\/li>\n<\/ol>\n<p>Steps 4, 5 and 6 only happen if validation succeeds.<\/p>\n<p>E.g. using <code>before<\/code>:<\/p>\n<pre><code>before do\n  header \"X-Robots-Tag\", \"noindex\"\nend\n<\/code><\/pre>\n<p>The block applies to every API call within and below the current namespace:<\/p>\n<pre><code>class MyAPI &lt; Grape::API\n  get '\/' do\n    \"root - #{@blah}\"\n  end\n\n  namespace :foo do\n    before do\n      @blah = 'blah'\n    end\n\n    get '\/' do\n      \"root - foo - #{@blah}\"\n    end\n\n    namespace :bar do\n      get '\/' do\n        \"root - foo - bar - #{@blah}\"\n      end\n    end\n  end\nend\n<\/code><\/pre>\n<p>The behaviour is then:<\/p>\n<pre><code>GET \/           # 'root - '\nGET \/foo        # 'root - foo - blah'\nGET \/foo\/bar    # 'root - foo - bar - blah'\n<\/code><\/pre>\n<p>Params on a <code>namespace<\/code> (or whatever alias you are using) also work when using <code>before_validation<\/code> or <code>after_validation<\/code>:<\/p>\n<pre><code>class MyAPI &lt; Grape::API\n  params do\n    requires :blah, type: Integer\n  end\n  resource ':blah' do\n    after_validation do\n      # if we reach this point validations will have passed\n      @blah = declared(params, include_missing: false)[:blah]\n    end\n\n    get '\/' do\n      @blah.class\n    end\n  end\nend\n<\/code><\/pre>\n<p>The behaviour is then:<\/p>\n<pre><code>GET \/123        # 'Fixnum'\nGET \/foo        # 400 error - 'blah is invalid'\n<\/code><\/pre>\n<p>When a callback is defined within a version block, it\u2019s only called for the routes defined in that block.<\/p>\n<pre><code>class Test &lt; Grape::API\n  resource :foo do\n    version 'v1', :using =&gt; :path do\n      before do\n        @output ||= 'v1-'\n      end\n      get '\/' do\n        @output += 'hello'\n      end\n    end\n\n    version 'v2', :using =&gt; :path do\n      before do\n        @output ||= 'v2-'\n      end\n      get '\/' do\n        @output += 'hello'\n      end\n    end\n  end\nend\n<\/code><\/pre>\n<p>The behaviour is then:<\/p>\n<pre><code>GET \/foo\/v1       # 'v1-hello'\nGET \/foo\/v2       # 'v2-hello'\n<\/code><\/pre>\n<h2>Anchoring<\/h2>\n<p>Grape by default anchors all request paths, which means that the request URL should match from start to end to match, otherwise a <code>404 Not Found<\/code> is returned. However, this is sometimes not what you want, because it is not always known upfront what can be expected from the call. This is because Rack-mount by default anchors requests to match from the start to the end, or not at all. Rails solves this problem by using a <code>anchor: false<\/code> option in your routes. In Grape this option can be used as well when a method is defined.<\/p>\n<p>For instance when your API needs to get part of an URL, for instance:<\/p>\n<pre><code>class TwitterAPI &lt; Grape::API\n  namespace :statuses do\n    get '\/(*:status)', anchor: false do\n\n    end\n  end\nend\n<\/code><\/pre>\n<p>This will match all paths starting with \u2018\/statuses\/\u2019. There is one caveat though: the <code>params[:status]<\/code> parameter only holds the first part of the request url. Luckily this can be circumvented by using the described above syntax for path specification and using the <code>PATH_INFO<\/code> Rack environment variable, using <code>env[\"PATH_INFO\"]<\/code>. This will hold everything that comes after the \u2018\/statuses\/\u2019 part.<\/p>\n<h2>Rails Middleware<\/h2>\n<p>Note that when you\u2019re using Grape mounted on Rails you don\u2019t have to use Rails middleware because it\u2019s already included into your middleware stack. You only have to implement the helpers to access the specific <code>env<\/code> variable.<\/p>\n<h3>Remote IP<\/h3>\n<p>By default you can access remote IP with <code>request.ip<\/code>. This is the remote IP address implemented by Rack. Sometimes it is desirable to get the remote IP Rails-style with <code>ActionDispatch::RemoteIp<\/code>.<\/p>\n<p>Add <code>gem 'actionpack'<\/code> to your Gemfile and <code>require 'action_dispatch\/middleware\/remote_ip.rb'<\/code>. Use the middleware in your API and expose a <code>client_ip<\/code> helper. See this documentation for additional options.<\/p>\n<pre><code>class API &lt; Grape::API\n  use ActionDispatch::RemoteIp\n\n  helpers do\n    def client_ip\n      env[\"action_dispatch.remote_ip\"].to_s\n    end\n  end\n\n  get :remote_ip do\n    { ip: client_ip }\n  end\nend\n<\/code><\/pre>\n<h2>Writing Tests<\/h2>\n<h3>Writing Tests with Rack<\/h3>\n<p>Use <code>rack-test<\/code> and define your API as <code>app<\/code>.<\/p>\n<h4>RSpec<\/h4>\n<p>You can test a Grape API with RSpec by making HTTP requests and examining the response.<\/p>\n<pre><code>require 'spec_helper'\n\ndescribe Twitter::API do\n  include Rack::Test::Methods\n\n  def app\n    Twitter::API\n  end\n\n  describe Twitter::API do\n    describe \"GET \/api\/statuses\/public_timeline\" do\n      it \"returns an empty array of statuses\" do\n        get \"\/api\/statuses\/public_timeline\"\n        expect(last_response.status).to eq(200)\n        expect(JSON.parse(last_response.body)).to eq []\n      end\n    end\n    describe \"GET \/api\/statuses\/:id\" do\n      it \"returns a status by id\" do\n        status = Status.create!\n        get \"\/api\/statuses\/#{status.id}\"\n        expect(last_response.body).to eq status.to_json\n      end\n    end\n  end\nend\n<\/code><\/pre>\n<h4>Airborne<\/h4>\n<p>You can test with other RSpec-based frameworks, including Airborne, which uses <code>rack-test<\/code> to make requests.<\/p>\n<pre><code>require 'airborne'\n\nAirborne.configure do |config|\n  config.rack_app = Twitter::API\nend\n\ndescribe Twitter::API do\n  describe \"GET \/api\/statuses\/:id\" do\n    it \"returns a status by id\" do\n      status = Status.create!\n      get \"\/api\/statuses\/#{status.id}\"\n      expect_json(status.as_json)\n    end\n  end\nend\n<\/code><\/pre>\n<h4>MiniTest<\/h4>\n<pre><code>require \"test_helper\"\n\nclass Twitter::APITest &lt; MiniTest::Test\n  include Rack::Test::Methods\n\n  def app\n    Twitter::API\n  end\n\n  def test_get_api_statuses_public_timeline_returns_an_empty_array_of_statuses\n    get \"\/api\/statuses\/public_timeline\"\n    assert last_response.ok?\n    assert_equal [], JSON.parse(last_response.body)\n  end\n\n  def test_get_api_statuses_id_returns_a_status_by_id\n    status = Status.create!\n    get \"\/api\/statuses\/#{status.id}\"\n    assert_equal status.to_json, last_response.body\n  end\nend\n<\/code><\/pre>\n<h3>Writing Tests with Rails<\/h3>\n<h4>RSpec<\/h4>\n<pre><code>describe Twitter::API do\n  describe \"GET \/api\/statuses\/public_timeline\" do\n    it \"returns an empty array of statuses\" do\n      get \"\/api\/statuses\/public_timeline\"\n      expect(response.status).to eq(200)\n      expect(JSON.parse(response.body)).to eq []\n    end\n  end\n  describe \"GET \/api\/statuses\/:id\" do\n    it \"returns a status by id\" do\n      status = Status.create!\n      get \"\/api\/statuses\/#{status.id}\"\n      expect(response.body).to eq status.to_json\n    end\n  end\nend\n<\/code><\/pre>\n<p>In Rails, HTTP request tests would go into the <code>spec\/requests<\/code> group. You may want your API code to go into <code>app\/api<\/code> &#8211; you can match that layout under <code>spec<\/code> by adding the following in <code>spec\/spec_helper.rb<\/code>.<\/p>\n<pre><code>RSpec.configure do |config|\n  config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: \/spec\\\/api\/\nend\n<\/code><\/pre>\n<h4>MiniTest<\/h4>\n<pre><code>class Twitter::APITest &lt; ActiveSupport::TestCase\n  include Rack::Test::Methods\n\n  def app\n    Rails.application\n  end\n\n  test \"GET \/api\/statuses\/public_timeline returns an empty array of statuses\" do\n    get \"\/api\/statuses\/public_timeline\"\n    assert last_response.ok?\n    assert_equal [], JSON.parse(last_response.body)\n  end\n\n  test \"GET \/api\/statuses\/:id returns a status by id\" do\n    status = Status.create!\n    get \"\/api\/statuses\/#{status.id}\"\n    assert_equal status.to_json, last_response.body\n  end\nend\n<\/code><\/pre>\n<h3>Stubbing Helpers<\/h3>\n<p>Because helpers are mixed in based on the context when an endpoint is defined, it can be difficult to stub or mock them for testing. The <code>Grape::Endpoint.before_each<\/code> method can help by allowing you to define behavior on the endpoint that will run before every request.<\/p>\n<pre><code>describe 'an endpoint that needs helpers stubbed' do\n  before do\n    Grape::Endpoint.before_each do |endpoint|\n      allow(endpoint).to receive(:helper_name).and_return('desired_value')\n    end\n  end\n\n  after do\n    Grape::Endpoint.before_each nil\n  end\n\n  it 'should properly stub the helper' do\n    # ...\n  end\nend\n<\/code><\/pre>\n<h2>Reloading API Changes in Development<\/h2>\n<h3>Reloading in Rack Applications<\/h3>\n<p>Use grape-reload.<\/p>\n<h3>Reloading in Rails Applications<\/h3>\n<p>Add API paths to <code>config\/application.rb<\/code>.<\/p>\n<pre><code># Auto-load API and its subdirectories\nconfig.paths.add File.join(\"app\", \"api\"), glob: File.join(\"**\", \"*.rb\")\nconfig.autoload_paths += Dir[Rails.root.join(\"app\", \"api\", \"*\")]\n<\/code><\/pre>\n<p>Create <code>config\/initializers\/reload_api.rb<\/code>.<\/p>\n<pre><code>if Rails.env.development?\n  ActiveSupport::Dependencies.explicitly_unloadable_constants<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Table of Contents What is Grape? Grape is a REST-like API micro-framework for Ruby. It\u2019s 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, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-7571","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7571","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=7571"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7571\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=7571"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=7571"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=7571"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}