grape 0.5.0 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +1223 -164
  3. data/CONTRIBUTING.md +148 -0
  4. data/LICENSE +1 -1
  5. data/README.md +3531 -675
  6. data/UPGRADING.md +1851 -0
  7. data/grape.gemspec +26 -32
  8. data/grape.png +0 -0
  9. data/lib/grape/api/instance.rb +194 -0
  10. data/lib/grape/api.rb +110 -485
  11. data/lib/grape/content_types.rb +28 -0
  12. data/lib/grape/cookies.rb +32 -25
  13. data/lib/grape/declared_params_handler.rb +118 -0
  14. data/lib/grape/dry_types.rb +54 -0
  15. data/lib/grape/dsl/callbacks.rb +19 -0
  16. data/lib/grape/dsl/declared.rb +35 -0
  17. data/lib/grape/dsl/desc.rb +65 -0
  18. data/lib/grape/dsl/headers.rb +21 -0
  19. data/lib/grape/dsl/helpers.rb +103 -0
  20. data/lib/grape/dsl/inside_route.rb +293 -0
  21. data/lib/grape/dsl/logger.rb +19 -0
  22. data/lib/grape/dsl/middleware.rb +36 -0
  23. data/lib/grape/dsl/parameters.rb +239 -0
  24. data/lib/grape/dsl/request_response.rb +168 -0
  25. data/lib/grape/dsl/routing.rb +288 -0
  26. data/lib/grape/dsl/settings.rb +67 -0
  27. data/lib/grape/dsl/validations.rb +51 -0
  28. data/lib/grape/endpoint.rb +287 -386
  29. data/lib/grape/env.rb +20 -0
  30. data/lib/grape/error_formatter/base.rb +56 -19
  31. data/lib/grape/error_formatter/json.rb +18 -7
  32. data/lib/grape/error_formatter/serializable_hash.rb +7 -0
  33. data/lib/grape/error_formatter/txt.rb +14 -11
  34. data/lib/grape/error_formatter/xml.rb +5 -11
  35. data/lib/grape/error_formatter.rb +15 -0
  36. data/lib/grape/exceptions/base.rb +31 -47
  37. data/lib/grape/exceptions/incompatible_option_values.rb +11 -0
  38. data/lib/grape/exceptions/invalid_accept_header.rb +11 -0
  39. data/lib/grape/exceptions/invalid_formatter.rb +3 -5
  40. data/lib/grape/exceptions/invalid_message_body.rb +11 -0
  41. data/lib/grape/exceptions/invalid_response.rb +11 -0
  42. data/lib/grape/exceptions/invalid_version_header.rb +11 -0
  43. data/lib/grape/exceptions/invalid_versioner_option.rb +3 -6
  44. data/lib/grape/exceptions/invalid_with_option_for_represent.rb +3 -7
  45. data/lib/grape/exceptions/method_not_allowed.rb +11 -0
  46. data/lib/grape/exceptions/missing_group_type.rb +11 -0
  47. data/lib/grape/exceptions/missing_mime_type.rb +3 -6
  48. data/lib/grape/exceptions/missing_vendor_option.rb +3 -5
  49. data/lib/grape/exceptions/request_error.rb +11 -0
  50. data/lib/grape/exceptions/unknown_auth_strategy.rb +11 -0
  51. data/lib/grape/exceptions/unknown_parameter.rb +11 -0
  52. data/lib/grape/exceptions/unknown_params_builder.rb +11 -0
  53. data/lib/grape/exceptions/unknown_validator.rb +3 -4
  54. data/lib/grape/exceptions/unsupported_group_type.rb +11 -0
  55. data/lib/grape/exceptions/validation.rb +20 -8
  56. data/lib/grape/exceptions/validation_array_errors.rb +14 -0
  57. data/lib/grape/exceptions/validation_errors.rb +59 -0
  58. data/lib/grape/formatter/base.rb +9 -26
  59. data/lib/grape/formatter/json.rb +6 -7
  60. data/lib/grape/formatter/serializable_hash.rb +24 -20
  61. data/lib/grape/formatter/txt.rb +5 -7
  62. data/lib/grape/formatter/xml.rb +6 -7
  63. data/lib/grape/formatter.rb +17 -0
  64. data/lib/grape/json.rb +10 -0
  65. data/lib/grape/locale/en.yml +47 -20
  66. data/lib/grape/middleware/auth/base.rb +25 -0
  67. data/lib/grape/middleware/auth/dsl.rb +38 -0
  68. data/lib/grape/middleware/auth/strategies.rb +25 -0
  69. data/lib/grape/middleware/auth/strategy_info.rb +15 -0
  70. data/lib/grape/middleware/base.rb +73 -19
  71. data/lib/grape/middleware/error.rb +104 -44
  72. data/lib/grape/middleware/filter.rb +5 -3
  73. data/lib/grape/middleware/formatter.rb +115 -105
  74. data/lib/grape/middleware/globals.rb +14 -0
  75. data/lib/grape/middleware/stack.rb +110 -0
  76. data/lib/grape/middleware/versioner/accept_version_header.rb +11 -40
  77. data/lib/grape/middleware/versioner/base.rb +76 -0
  78. data/lib/grape/middleware/versioner/header.rb +61 -78
  79. data/lib/grape/middleware/versioner/param.rb +9 -21
  80. data/lib/grape/middleware/versioner/path.rb +16 -31
  81. data/lib/grape/middleware/versioner.rb +10 -15
  82. data/lib/grape/namespace.rb +39 -10
  83. data/lib/grape/params_builder/base.rb +20 -0
  84. data/lib/grape/params_builder/hash.rb +11 -0
  85. data/lib/grape/params_builder/hash_with_indifferent_access.rb +11 -0
  86. data/lib/grape/params_builder/hashie_mash.rb +11 -0
  87. data/lib/grape/params_builder.rb +15 -0
  88. data/lib/grape/parser/base.rb +9 -24
  89. data/lib/grape/parser/json.rb +8 -7
  90. data/lib/grape/parser/xml.rb +8 -7
  91. data/lib/grape/parser.rb +15 -0
  92. data/lib/grape/path.rb +76 -0
  93. data/lib/grape/presenters/presenter.rb +11 -0
  94. data/lib/grape/railtie.rb +9 -0
  95. data/lib/grape/request.rb +182 -0
  96. data/lib/grape/router/base_route.rb +48 -0
  97. data/lib/grape/router/greedy_route.rb +26 -0
  98. data/lib/grape/router/pattern.rb +67 -0
  99. data/lib/grape/router/route.rb +58 -0
  100. data/lib/grape/router.rb +167 -0
  101. data/lib/grape/serve_stream/file_body.rb +36 -0
  102. data/lib/grape/serve_stream/sendfile_response.rb +21 -0
  103. data/lib/grape/serve_stream/stream_response.rb +23 -0
  104. data/lib/grape/util/api_description.rb +58 -0
  105. data/lib/grape/util/base_inheritable.rb +46 -0
  106. data/lib/grape/util/cache.rb +18 -0
  107. data/lib/grape/util/deep_freeze.rb +35 -0
  108. data/lib/grape/util/endpoint_configuration.rb +8 -0
  109. data/lib/grape/util/header.rb +13 -0
  110. data/lib/grape/util/inheritable_setting.rb +107 -0
  111. data/lib/grape/util/inheritable_values.rb +29 -0
  112. data/lib/grape/util/lazy/block.rb +29 -0
  113. data/lib/grape/util/lazy/value.rb +38 -0
  114. data/lib/grape/util/lazy/value_array.rb +21 -0
  115. data/lib/grape/util/lazy/value_enumerable.rb +34 -0
  116. data/lib/grape/util/lazy/value_hash.rb +21 -0
  117. data/lib/grape/util/media_type.rb +70 -0
  118. data/lib/grape/util/registry.rb +27 -0
  119. data/lib/grape/util/reverse_stackable_values.rb +15 -0
  120. data/lib/grape/util/stackable_values.rb +36 -0
  121. data/lib/grape/util/translation.rb +42 -0
  122. data/lib/grape/validations/attributes_iterator.rb +77 -0
  123. data/lib/grape/validations/contract_scope.rb +28 -0
  124. data/lib/grape/validations/multiple_attributes_iterator.rb +13 -0
  125. data/lib/grape/validations/param_scope_tracker.rb +57 -0
  126. data/lib/grape/validations/params_documentation.rb +50 -0
  127. data/lib/grape/validations/params_scope.rb +529 -0
  128. data/lib/grape/validations/single_attribute_iterator.rb +26 -0
  129. data/lib/grape/validations/types/array_coercer.rb +60 -0
  130. data/lib/grape/validations/types/custom_type_coercer.rb +164 -0
  131. data/lib/grape/validations/types/custom_type_collection_coercer.rb +56 -0
  132. data/lib/grape/validations/types/dry_type_coercer.rb +59 -0
  133. data/lib/grape/validations/types/file.rb +31 -0
  134. data/lib/grape/validations/types/invalid_value.rb +17 -0
  135. data/lib/grape/validations/types/json.rb +71 -0
  136. data/lib/grape/validations/types/multiple_type_coercer.rb +57 -0
  137. data/lib/grape/validations/types/primitive_coercer.rb +46 -0
  138. data/lib/grape/validations/types/set_coercer.rb +35 -0
  139. data/lib/grape/validations/types/variant_collection_coercer.rb +51 -0
  140. data/lib/grape/validations/types.rb +198 -0
  141. data/lib/grape/validations/validators/all_or_none_of_validator.rb +19 -0
  142. data/lib/grape/validations/validators/allow_blank_validator.rb +25 -0
  143. data/lib/grape/validations/validators/as_validator.rb +14 -0
  144. data/lib/grape/validations/validators/at_least_one_of_validator.rb +18 -0
  145. data/lib/grape/validations/validators/base.rb +158 -0
  146. data/lib/grape/validations/validators/coerce_validator.rb +55 -0
  147. data/lib/grape/validations/validators/contract_scope_validator.rb +45 -0
  148. data/lib/grape/validations/validators/default_validator.rb +31 -0
  149. data/lib/grape/validations/validators/exactly_one_of_validator.rb +24 -0
  150. data/lib/grape/validations/validators/except_values_validator.rb +33 -0
  151. data/lib/grape/validations/validators/length_validator.rb +48 -0
  152. data/lib/grape/validations/validators/multiple_params_base.rb +34 -0
  153. data/lib/grape/validations/validators/mutually_exclusive_validator.rb +18 -0
  154. data/lib/grape/validations/validators/presence_validator.rb +17 -0
  155. data/lib/grape/validations/validators/regexp_validator.rb +24 -0
  156. data/lib/grape/validations/validators/same_as_validator.rb +20 -0
  157. data/lib/grape/validations/validators/values_validator.rb +68 -0
  158. data/lib/grape/validations.rb +10 -226
  159. data/lib/grape/version.rb +4 -1
  160. data/lib/grape/xml.rb +10 -0
  161. data/lib/grape.rb +79 -77
  162. metadata +160 -306
  163. data/.gitignore +0 -38
  164. data/.rspec +0 -2
  165. data/.travis.yml +0 -9
  166. data/.yardopts +0 -2
  167. data/Gemfile +0 -19
  168. data/Guardfile +0 -15
  169. data/Rakefile +0 -64
  170. data/lib/grape/exceptions/missing_option.rb +0 -13
  171. data/lib/grape/exceptions/unknown_options.rb +0 -14
  172. data/lib/grape/http/request.rb +0 -28
  173. data/lib/grape/middleware/auth/basic.rb +0 -30
  174. data/lib/grape/middleware/auth/digest.rb +0 -30
  175. data/lib/grape/middleware/auth/oauth2.rb +0 -72
  176. data/lib/grape/route.rb +0 -23
  177. data/lib/grape/util/content_types.rb +0 -17
  178. data/lib/grape/util/deep_merge.rb +0 -23
  179. data/lib/grape/util/hash_stack.rb +0 -120
  180. data/lib/grape/validations/coerce.rb +0 -62
  181. data/lib/grape/validations/default.rb +0 -24
  182. data/lib/grape/validations/presence.rb +0 -12
  183. data/lib/grape/validations/regexp.rb +0 -14
  184. data/spec/grape/api_spec.rb +0 -2129
  185. data/spec/grape/endpoint_spec.rb +0 -605
  186. data/spec/grape/entity_spec.rb +0 -281
  187. data/spec/grape/exceptions/invalid_formatter_spec.rb +0 -18
  188. data/spec/grape/exceptions/invalid_versioner_option_spec.rb +0 -18
  189. data/spec/grape/exceptions/missing_mime_type_spec.rb +0 -24
  190. data/spec/grape/exceptions/missing_option_spec.rb +0 -18
  191. data/spec/grape/exceptions/unknown_options_spec.rb +0 -18
  192. data/spec/grape/exceptions/unknown_validator_spec.rb +0 -18
  193. data/spec/grape/middleware/auth/basic_spec.rb +0 -31
  194. data/spec/grape/middleware/auth/digest_spec.rb +0 -47
  195. data/spec/grape/middleware/auth/oauth2_spec.rb +0 -90
  196. data/spec/grape/middleware/base_spec.rb +0 -63
  197. data/spec/grape/middleware/error_spec.rb +0 -49
  198. data/spec/grape/middleware/exception_spec.rb +0 -164
  199. data/spec/grape/middleware/formatter_spec.rb +0 -244
  200. data/spec/grape/middleware/versioner/accept_version_header_spec.rb +0 -121
  201. data/spec/grape/middleware/versioner/header_spec.rb +0 -277
  202. data/spec/grape/middleware/versioner/param_spec.rb +0 -58
  203. data/spec/grape/middleware/versioner/path_spec.rb +0 -44
  204. data/spec/grape/middleware/versioner_spec.rb +0 -22
  205. data/spec/grape/util/hash_stack_spec.rb +0 -133
  206. data/spec/grape/validations/coerce_spec.rb +0 -143
  207. data/spec/grape/validations/default_spec.rb +0 -67
  208. data/spec/grape/validations/presence_spec.rb +0 -144
  209. data/spec/grape/validations/regexp_spec.rb +0 -33
  210. data/spec/grape/validations/zh-CN.yml +0 -9
  211. data/spec/grape/validations_spec.rb +0 -217
  212. data/spec/shared/versioning_examples.rb +0 -121
  213. data/spec/spec_helper.rb +0 -25
  214. data/spec/support/basic_auth_encode_helpers.rb +0 -4
  215. data/spec/support/versioned_helpers.rb +0 -48
data/README.md CHANGED
@@ -1,44 +1,49 @@
1
- ![grape logo](https://github.com/intridea/grape/wiki/grape_logo.png)
1
+ ![grape logo](grape.png)
2
+
3
+ [![Gem Version](https://badge.fury.io/rb/grape.svg)](http://badge.fury.io/rb/grape)
4
+ [![test](https://github.com/ruby-grape/grape/actions/workflows/test.yml/badge.svg)](https://github.com/ruby-grape/grape/actions/workflows/test.yml)
5
+ [![Coverage Status](https://coveralls.io/repos/github/ruby-grape/grape/badge.svg?branch=master)](https://coveralls.io/github/ruby-grape/grape?branch=master)
2
6
 
3
7
  ## What is Grape?
4
8
 
5
- Grape is a REST-like API micro-framework for Ruby. It's designed to run on Rack
6
- or complement existing web application frameworks such as Rails and Sinatra by
7
- providing a simple DSL to easily develop RESTful APIs. It has built-in support
8
- for common conventions, including multiple formats, subdomain/prefix restriction,
9
- content negotiation, versioning and much more.
9
+ 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.
10
+
11
+ ## Stable Release
10
12
 
11
- [![Build Status](https://travis-ci.org/intridea/grape.png?branch=master)](http://travis-ci.org/intridea/grape) [![Code Climate](https://codeclimate.com/github/intridea/grape.png)](https://codeclimate.com/github/intridea/grape)
13
+ You're reading the documentation for the stable release of Grape, 3.2.1.
12
14
 
13
15
  ## Project Resources
14
16
 
15
- * Need help? [Grape Google Group](http://groups.google.com/group/ruby-grape)
16
- * [Grape Wiki](https://github.com/intridea/grape/wiki)
17
+ * [Grape Website](http://www.ruby-grape.org)
18
+ * [Documentation](http://www.rubydoc.info/gems/grape)
19
+ * Need help? [Open an Issue](https://github.com/ruby-grape/grape/issues)
20
+ * [Follow us on Twitter](https://twitter.com/grapeframework)
17
21
 
18
- ## Installation
22
+ ## Grape for Enterprise
23
+
24
+ Available as part of the Tidelift Subscription.
19
25
 
20
- Grape is available as a gem, to install it just install the gem:
26
+ 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. Click [here](https://tidelift.com/subscription/request-a-demo?utm_source=rubygems-grape&utm_medium=referral&utm_campaign=enterprise) for more details.
21
27
 
22
- gem install grape
28
+ ## Installation
23
29
 
24
- If you're using Bundler, add the gem to Gemfile.
30
+ Ruby 3.2 or newer is required.
25
31
 
26
- gem 'grape'
32
+ Grape is available as a gem, to install it run:
27
33
 
28
- Run `bundle install`.
34
+ bundle add grape
29
35
 
30
36
  ## Basic Usage
31
37
 
32
38
  Grape APIs are Rack applications that are created by subclassing `Grape::API`.
33
- Below is a simple example showing some of the more common features of Grape in
34
- the context of recreating parts of the Twitter API.
39
+ Below is a simple example showing some of the more common features of Grape in the context of recreating parts of the Twitter API.
35
40
 
36
41
  ```ruby
37
42
  module Twitter
38
43
  class API < Grape::API
39
-
40
44
  version 'v1', using: :header, vendor: 'twitter'
41
45
  format :json
46
+ prefix :api
42
47
 
43
48
  helpers do
44
49
  def current_user
@@ -51,21 +56,20 @@ module Twitter
51
56
  end
52
57
 
53
58
  resource :statuses do
54
-
55
- desc "Return a public timeline."
59
+ desc 'Return a public timeline.'
56
60
  get :public_timeline do
57
61
  Status.limit(20)
58
62
  end
59
63
 
60
- desc "Return a personal timeline."
64
+ desc 'Return a personal timeline.'
61
65
  get :home_timeline do
62
66
  authenticate!
63
67
  current_user.statuses.limit(20)
64
68
  end
65
69
 
66
- desc "Return a status."
70
+ desc 'Return a status.'
67
71
  params do
68
- requires :id, type: Integer, desc: "Status id."
72
+ requires :id, type: Integer, desc: 'Status ID.'
69
73
  end
70
74
  route_param :id do
71
75
  get do
@@ -73,9 +77,9 @@ module Twitter
73
77
  end
74
78
  end
75
79
 
76
- desc "Create a status."
80
+ desc 'Create a status.'
77
81
  params do
78
- requires :status, type: String, desc: "Your status."
82
+ requires :status, type: String, desc: 'Your status.'
79
83
  end
80
84
  post do
81
85
  authenticate!
@@ -85,10 +89,10 @@ module Twitter
85
89
  })
86
90
  end
87
91
 
88
- desc "Update a status."
92
+ desc 'Update a status.'
89
93
  params do
90
- requires :id, type: String, desc: "Status ID."
91
- requires :status, type: String, desc: "Your status."
94
+ requires :id, type: String, desc: 'Status ID.'
95
+ requires :status, type: String, desc: 'Your status.'
92
96
  end
93
97
  put ':id' do
94
98
  authenticate!
@@ -98,46 +102,65 @@ module Twitter
98
102
  })
99
103
  end
100
104
 
101
- desc "Delete a status."
105
+ desc 'Delete a status.'
102
106
  params do
103
- requires :id, type: String, desc: "Status ID."
107
+ requires :id, type: String, desc: 'Status ID.'
104
108
  end
105
109
  delete ':id' do
106
110
  authenticate!
107
111
  current_user.statuses.find(params[:id]).destroy
108
112
  end
109
-
110
113
  end
111
114
  end
112
115
  end
113
116
  ```
114
117
 
118
+ ## Rails 7.1
119
+
120
+ Grape's [deprecator](https://api.rubyonrails.org/v7.1.0/classes/ActiveSupport/Deprecation.html) will be added to your application's deprecators [automatically](lib/grape/railtie.rb) as `:grape`, so that your application's configuration can be applied to it.
121
+
115
122
  ## Mounting
116
123
 
124
+ ### All
125
+
126
+
127
+ By default Grape will compile the routes on the first route, but it is possible to pre-load routes using the `compile!` method.
128
+
129
+ ```ruby
130
+ Twitter::API.compile!
131
+ ```
132
+
133
+ This can be added to your `config.ru` (if using rackup), `application.rb` (if using rails), or any file that loads your server.
134
+
117
135
  ### Rack
118
136
 
119
- The above sample creates a Rack application that can be run from a rackup `config.ru` file
120
- with `rackup`:
137
+ The above sample creates a Rack application that can be run from a rackup `config.ru` file with `rackup`:
138
+
139
+ ```ruby
140
+ run Twitter::API
141
+ ```
142
+
143
+ (With pre-loading you can use)
121
144
 
122
145
  ```ruby
146
+ Twitter::API.compile!
123
147
  run Twitter::API
124
148
  ```
125
149
 
126
150
  And would respond to the following routes:
127
151
 
128
- GET /statuses/public_timeline(.json)
129
- GET /statuses/home_timeline(.json)
130
- GET /statuses/:id(.json)
131
- POST /statuses(.json)
132
- PUT /statuses/:id(.json)
133
- DELETE /statuses/:id(.json)
152
+ GET /api/statuses/public_timeline
153
+ GET /api/statuses/home_timeline
154
+ GET /api/statuses/:id
155
+ POST /api/statuses
156
+ PUT /api/statuses/:id
157
+ DELETE /api/statuses/:id
134
158
 
135
159
  Grape will also automatically respond to HEAD and OPTIONS for all GET, and just OPTIONS for all other routes.
136
160
 
137
161
  ### Alongside Sinatra (or other frameworks)
138
162
 
139
- If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using
140
- `Rack::Cascade`:
163
+ If you wish to mount Grape alongside another Rack framework such as Sinatra, you can do so easily using `Rack::Cascade`:
141
164
 
142
165
  ```ruby
143
166
  # Example config.ru
@@ -147,41 +170,44 @@ require 'grape'
147
170
 
148
171
  class API < Grape::API
149
172
  get :hello do
150
- {hello: "world"}
173
+ { hello: 'world' }
151
174
  end
152
175
  end
153
176
 
154
177
  class Web < Sinatra::Base
155
178
  get '/' do
156
- "Hello world."
179
+ 'Hello world.'
157
180
  end
158
181
  end
159
182
 
160
183
  use Rack::Session::Cookie
161
- run Rack::Cascade.new [API, Web]
184
+ run Rack::Cascade.new [Web, API]
162
185
  ```
163
186
 
164
- ### Rails
187
+ Note that order of loading apps using `Rack::Cascade` matters. The grape application must be last if you want to raise custom 404 errors from grape (such as `error!('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](https://www.rubydoc.info/gems/rack/Rack/Cascade). This may lead to undesirable behavior showing the [wrong 404 page from the wrong app](https://github.com/ruby-grape/grape/issues/1515).
165
188
 
166
- Place API files into `app/api` and modify `application.rb`.
167
189
 
168
- ```ruby
169
- config.paths.add "app/api", glob: "**/*.rb"
170
- config.autoload_paths += Dir["#{Rails.root}/app/api/*"]
171
- ```
190
+ ### Rails
191
+
192
+ Place API files into `app/api`. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory for `Twitter::API` should be `app/api/twitter/api.rb`.
172
193
 
173
194
  Modify `config/routes`:
174
195
 
175
196
  ```ruby
176
197
  mount Twitter::API => '/'
177
198
  ```
199
+ #### Zeitwerk
200
+ Rails's default autoloader is `Zeitwerk`. By default, it inflects `api` as `Api` instead of `API`. To make our example work, you need to uncomment the lines at the bottom of `config/initializers/inflections.rb`, and add `API` as an acronym:
178
201
 
179
- See below for additional code that enables reloading of API changes in development.
202
+ ```ruby
203
+ ActiveSupport::Inflector.inflections(:en) do |inflect|
204
+ inflect.acronym 'API'
205
+ end
206
+ ```
180
207
 
181
208
  ### Modules
182
209
 
183
- You can mount multiple API implementations inside another one. These don't have to be
184
- different versions, but may be components of the same API.
210
+ 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.
185
211
 
186
212
  ```ruby
187
213
  class Twitter::API < Grape::API
@@ -198,1095 +224,3925 @@ class Twitter::API < Grape::API
198
224
  end
199
225
  ```
200
226
 
201
- ## Versioning
227
+ Declarations as `before/after/rescue_from` can be placed before or after `mount`. In any case they will be inherited.
228
+
229
+ ```ruby
230
+ class Twitter::API < Grape::API
231
+ before do
232
+ header 'X-Base-Header', 'will be defined for all APIs that are mounted below'
233
+ end
202
234
 
203
- There are four strategies in which clients can reach your API's endpoints: `:path`,
204
- `:header`, `:accept_version_header` and `:param`. The default strategy is `:path`.
235
+ rescue_from :all do
236
+ error!({ "error" => "Internal Server Error" }, 500)
237
+ end
205
238
 
206
- ### Path
239
+ mount Twitter::Users
240
+ mount Twitter::Search
207
241
 
208
- ```ruby
209
- version 'v1', using: :path
210
- ```
242
+ after do
243
+ clean_cache!
244
+ end
211
245
 
212
- Using this versioning strategy, clients should pass the desired version in the URL.
246
+ rescue_from ZeroDivisionError do
247
+ error!({ "error" => "Not found" }, 404)
248
+ end
249
+ end
250
+ ```
213
251
 
214
- curl -H http://localhost:9292/v1/statuses/public_timeline
252
+ ## Remounting
215
253
 
216
- ### Header
254
+ You can mount the same endpoints in two different locations.
217
255
 
218
256
  ```ruby
219
- version 'v1', using: :header, vendor: 'twitter'
220
- ```
257
+ class Voting::API < Grape::API
258
+ namespace 'votes' do
259
+ get do
260
+ # Your logic
261
+ end
221
262
 
222
- Using this versioning strategy, clients should pass the desired version in the HTTP `Accept` head.
263
+ post do
264
+ # Your logic
265
+ end
266
+ end
267
+ end
268
+
269
+ class Post::API < Grape::API
270
+ mount Voting::API
271
+ end
272
+
273
+ class Comment::API < Grape::API
274
+ mount Voting::API
275
+ end
276
+ ```
223
277
 
224
- curl -H Accept=application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline
278
+ Assuming that the post and comment endpoints are mounted in `/posts` and `/comments`, you should now be able to do `get /posts/votes`, `post /posts/votes`, `get /comments/votes` and `post /comments/votes`.
225
279
 
226
- By default, the first matching version is used when no `Accept` header is
227
- supplied. This behavior is similar to routing in Rails. To circumvent this default behavior,
228
- one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error
229
- is returned when no correct `Accept` header is supplied.
280
+ ### Mount Configuration
230
281
 
231
- ### Accept-Version Header
282
+ You can configure remountable endpoints to change how they behave according to where they are mounted.
232
283
 
233
284
  ```ruby
234
- version 'v1', using: :accept_version_header
285
+ class Voting::API < Grape::API
286
+ namespace 'votes' do
287
+ desc "Vote for your #{configuration[:votable]}"
288
+ get do
289
+ # Your logic
290
+ end
291
+ end
292
+ end
293
+
294
+ class Post::API < Grape::API
295
+ mount Voting::API, with: { votable: 'posts' }
296
+ end
297
+
298
+ class Comment::API < Grape::API
299
+ mount Voting::API, with: { votable: 'comments' }
300
+ end
235
301
  ```
236
302
 
237
- Using this versioning strategy, clients should pass the desired version in the HTTP `Accept-Version` header.
303
+ Note that if you're passing a hash as the first parameter to `mount`, you will need to explicitly put `()` around parameters:
304
+ ```ruby
305
+ # good
306
+ mount({ ::Some::Api => '/some/api' }, with: { condition: true })
238
307
 
239
- curl -H "Accept-Version=v1" http://localhost:9292/statuses/public_timeline
308
+ # bad
309
+ mount ::Some::Api => '/some/api', with: { condition: true }
310
+ ```
240
311
 
241
- By default, the first matching version is used when no `Accept-Version` header is
242
- supplied. This behavior is similar to routing in Rails. To circumvent this default behavior,
243
- one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error
244
- is returned when no correct `Accept` header is supplied.
312
+ You can access `configuration` on the class (to use as dynamic attributes), inside blocks (like namespace)
245
313
 
246
- ### Param
314
+ If you want logic happening given on an `configuration`, you can use the helper `given`.
247
315
 
248
316
  ```ruby
249
- version 'v1', using: :param
317
+ class ConditionalEndpoint::API < Grape::API
318
+ given configuration[:some_setting] do
319
+ get 'mount_this_endpoint_conditionally' do
320
+ configuration[:configurable_response]
321
+ end
322
+ end
323
+ end
250
324
  ```
251
325
 
252
- Using this versioning strategy, clients should pass the desired version as a request parameter,
253
- either in the URL query string or in the request body.
254
-
255
- curl -H http://localhost:9292/statuses/public_timeline?apiver=v1
326
+ If you want a block of logic running every time an endpoint is mounted (within which you can access the `configuration` Hash)
256
327
 
257
- The default name for the query parameter is 'apiver' but can be specified using the `:parameter` option.
258
328
 
259
329
  ```ruby
260
- version 'v1', using: :param, parameter: "v"
330
+ class ConditionalEndpoint::API < Grape::API
331
+ mounted do
332
+ YourLogger.info "This API was mounted at: #{Time.now}"
333
+
334
+ get configuration[:endpoint_name] do
335
+ configuration[:configurable_response]
336
+ end
337
+ end
338
+ end
261
339
  ```
262
340
 
263
- curl -H http://localhost:9292/statuses/public_timeline?v=v1
341
+ More complex results can be achieved by using `mounted` as an expression within which the `configuration` is already evaluated as a Hash.
264
342
 
343
+ ```ruby
344
+ class ExpressionEndpointAPI < Grape::API
345
+ get(mounted { configuration[:route_name] || 'default_name' }) do
346
+ # some logic
347
+ end
348
+ end
349
+ ```
265
350
 
266
- ## Describing Methods
351
+ ```ruby
352
+ class BasicAPI < Grape::API
353
+ desc 'Statuses index' do
354
+ params: (configuration[:entity] || API::Entities::Status).documentation
355
+ end
356
+ params do
357
+ requires :all, using: (configuration[:entity] || API::Entities::Status).documentation
358
+ end
359
+ get '/statuses' do
360
+ statuses = Status.all
361
+ type = current_user.admin? ? :full : :default
362
+ present statuses, with: (configuration[:entity] || API::Entities::Status), type: type
363
+ end
364
+ end
267
365
 
268
- You can add a description to API methods and namespaces.
366
+ class V1 < Grape::API
367
+ version 'v1'
368
+ mount BasicAPI, with: { entity: mounted { configuration[:entity] || API::Entities::Status } }
369
+ end
269
370
 
270
- ```ruby
271
- desc "Returns your public timeline."
272
- get :public_timeline do
273
- Status.limit(20)
371
+ class V2 < Grape::API
372
+ version 'v2'
373
+ mount BasicAPI, with: { entity: mounted { configuration[:entity] || API::Entities::V2::Status } }
274
374
  end
275
375
  ```
276
376
 
277
- ## Parameters
377
+ ## Versioning
278
378
 
279
- Request parameters are available through the `params` hash object. This includes `GET`, `POST`
280
- and `PUT` parameters, along with any named parameters you specify in your route strings.
379
+ You have the option to provide various versions of your API by establishing a separate `Grape::API` class for each offered version and then integrating them into a primary `Grape::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.
281
380
 
282
381
  ```ruby
283
- get :public_timeline do
284
- Status.order(params[:sort_by])
382
+ require 'v1'
383
+ require 'v2'
384
+ require 'v3'
385
+ class App < Grape::API
386
+ mount V3
387
+ mount V2
388
+ mount V1
285
389
  end
286
390
  ```
287
391
 
288
- Parameters are automatically populated from the request body on POST and PUT for form input, JSON and
289
- XML content-types.
392
+ To maintain the same endpoints from earlier API versions without rewriting them, you can indicate multiple versions within the previous API versions.
290
393
 
291
- The request:
394
+ ```ruby
395
+ class V1 < Grape::API
396
+ version 'v1', 'v2', 'v3'
397
+
398
+ get '/foo' do
399
+ # your code for GET /foo
400
+ end
401
+
402
+ get '/other' do
403
+ # your code for GET /other
404
+ end
405
+ end
292
406
 
407
+ class V2 < Grape::API
408
+ version 'v2', 'v3'
409
+
410
+ get '/var' do
411
+ # your code for GET /var
412
+ end
413
+ end
414
+
415
+ class V3 < Grape::API
416
+ version 'v3'
417
+
418
+ get '/foo' do
419
+ # your new code for GET /foo
420
+ end
421
+ end
293
422
  ```
294
- curl -d '{"text": "140 characters"}' 'http://localhost:9292/statuses' -H Content-Type:application/json -v
423
+
424
+ Using the example provided, the subsequent endpoints will be accessible across various versions:
425
+
426
+ ```shell
427
+ GET /v1/foo
428
+ GET /v1/other
429
+ GET /v2/foo # => Same behavior as v1
430
+ GET /v2/other # => Same behavior as v1
431
+ GET /v2/var # => New endpoint not available in v1
432
+ GET /v3/foo # => Different behavior to v1 and v2
433
+ GET /v3/other # => Same behavior as v1 and v2
434
+ GET /v3/var # => Same behavior as v2
295
435
  ```
296
436
 
297
- The Grape endpoint:
437
+ 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`.
438
+
439
+ ### Strategies
440
+
441
+ #### Path
298
442
 
299
443
  ```ruby
300
- post '/statuses' do
301
- Status.create!({ text: params[:text] })
302
- end
444
+ version 'v1', using: :path
303
445
  ```
304
446
 
305
- Multipart POSTs and PUTs are supported as well.
447
+ Using this versioning strategy, clients should pass the desired version in the URL.
306
448
 
307
- The request:
449
+ curl http://localhost:9292/v1/statuses/public_timeline
450
+
451
+ #### Header
452
+
453
+ ```ruby
454
+ version 'v1', using: :header, vendor: 'twitter'
455
+ ```
456
+
457
+ Currently, Grape only supports versioned media types in the following format:
308
458
 
309
459
  ```
310
- curl --form image_file=image.jpg http://localhost:9292/upload
460
+ vnd.vendor-and-or-resource-v1234+format
311
461
  ```
312
462
 
313
- The Grape endpoint:
463
+ Basically all tokens between the final `-` and the `+` will be interpreted as the version.
464
+
465
+ Using this versioning strategy, clients should pass the desired version in the HTTP `Accept` head.
466
+
467
+ curl -H Accept:application/vnd.twitter-v1+json http://localhost:9292/statuses/public_timeline
468
+
469
+ By default, the first matching version is used when no `Accept` header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error is returned when no correct `Accept` header is supplied.
470
+
471
+ When an invalid `Accept` header is supplied, a `406 Not Acceptable` error is returned if the `:cascade` option is set to `false`. Otherwise a `404 Not Found` error is returned by Rack if no other route matches.
472
+
473
+ 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:
474
+
475
+ curl -H "Accept: text/xml;q=0.8, application/json;q=0.9" localhost:1234/resource
476
+
477
+ #### Accept-Version Header
314
478
 
315
479
  ```ruby
316
- post "upload" do
317
- # file in params[:image_file]
318
- end
480
+ version 'v1', using: :accept_version_header
319
481
  ```
320
482
 
321
- ## Parameter Validation and Coercion
483
+ Using this versioning strategy, clients should pass the desired version in the HTTP `Accept-Version` header.
322
484
 
323
- You can define validations and coercion options for your parameters using a `params` block.
485
+ curl -H "Accept-Version:v1" http://localhost:9292/statuses/public_timeline
486
+
487
+ By default, the first matching version is used when no `Accept-Version` header is supplied. This behavior is similar to routing in Rails. To circumvent this default behavior, one could use the `:strict` option. When this option is set to `true`, a `406 Not Acceptable` error is returned when no correct `Accept` header is supplied and the `:cascade` option is set to `false`. Otherwise a `404 Not Found` error is returned by Rack if no other route matches.
488
+
489
+ #### Param
324
490
 
325
491
  ```ruby
326
- params do
327
- requires :id, type: Integer
328
- optional :text, type: String, regexp: /^[a-z]+$/
329
- group :media do
330
- requires :url
331
- end
332
- end
333
- put ':id' do
334
- # params[:id] is an Integer
335
- end
492
+ version 'v1', using: :param
336
493
  ```
337
494
 
338
- When a type is specified an implicit validation is done after the coercion to ensure
339
- the output type is the one declared.
495
+ 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.
340
496
 
341
- Optional parameters can have a default value.
497
+ curl http://localhost:9292/statuses/public_timeline?apiver=v1
498
+
499
+ The default name for the query parameter is 'apiver' but can be specified using the `:parameter` option.
342
500
 
343
501
  ```ruby
344
- params do
345
- optional :color, type: String, default: 'blue'
346
- end
502
+ version 'v1', using: :param, parameter: 'v'
347
503
  ```
348
504
 
349
- Parameters can be nested using `group`. In the above example, this means
350
- `params[:media][:url]` is required along with `params[:id]`.
505
+ curl http://localhost:9292/statuses/public_timeline?v=v1
351
506
 
352
- ### Namespace Validation and Coercion
353
507
 
354
- Namespaces allow parameter definitions and apply to every method within the namespace.
508
+ ## Linting
509
+
510
+ You can check whether your API is in conformance with the [Rack's specification](https://github.com/rack/rack/blob/main/SPEC.rdoc) by calling `lint!` at the API level or through [configuration](#configuration).
355
511
 
356
512
  ```ruby
357
- namespace :statuses do
358
- params do
359
- requires :user_id, type: Integer, desc: "A user ID."
360
- end
361
- namespace ":user_id" do
362
- desc "Retrieve a user's status."
363
- params do
364
- requires :status_id, type: Integer, desc: "A status ID."
365
- end
366
- get ":status_id" do
367
- User.find(params[:user_id]).statuses.find(params[:status_id])
368
- end
369
- end
513
+ class Api < Grape::API
514
+ lint!
370
515
  end
371
516
  ```
517
+ ```ruby
518
+ Grape.configure do |config|
519
+ config.lint = true
520
+ end
521
+ ```
522
+ ```ruby
523
+ Grape.config.lint = true
524
+ ```
372
525
 
373
- The `namespace` method has a number of aliases, including: `group`, `resource`,
374
- `resources`, and `segment`. Use whichever reads the best for your API.
526
+ ### Bug in Rack::ETag under Rack 3.X
527
+ If you're using Rack 3.X and the `Rack::Etag` middleware (used by [Rails](https://guides.rubyonrails.org/rails_on_rack.html#inspecting-middleware-stack)), a [bug](https://github.com/rack/rack/pull/2324) related to linting has been fixed in [3.1.13](https://github.com/rack/rack/blob/v3.1.13/CHANGELOG.md#3113---2025-04-13) and [3.0.15](https://github.com/rack/rack/blob/v3.1.13/CHANGELOG.md#3015---2025-04-13) respectively.
375
528
 
376
- ### Custom Validators
529
+ ## Describing Methods
530
+
531
+ You can add a description to API methods and namespaces. The description would be used by [grape-swagger][grape-swagger] to generate swagger compliant documentation.
532
+
533
+ Note: Description block is only for documentation and won't affects API behavior.
377
534
 
378
535
  ```ruby
379
- class AlphaNumeric < Grape::Validations::Validator
380
- def validate_param!(attr_name, params)
381
- unless params[attr_name] =~ /^[[:alnum:]]+$/
382
- throw :error, status: 400, message: "#{attr_name}: must consist of alpha-numeric characters"
383
- end
384
- end
536
+ desc 'Returns your public timeline.' do
537
+ summary 'summary'
538
+ detail 'more details'
539
+ params API::Entities::Status.documentation
540
+ success API::Entities::Entity
541
+ failure [[401, 'Unauthorized', 'Entities::Error']]
542
+ default { code: 500, message: 'InvalidRequest', model: Entities::Error }
543
+ named 'My named route'
544
+ headers XAuthToken: {
545
+ description: 'Validates your identity',
546
+ required: true
547
+ },
548
+ XOptionalHeader: {
549
+ description: 'Not really needed',
550
+ required: false
551
+ }
552
+ hidden false
553
+ deprecated false
554
+ is_array true
555
+ nickname 'nickname'
556
+ produces ['application/json']
557
+ consumes ['application/json']
558
+ tags ['tag1', 'tag2']
559
+ end
560
+ get :public_timeline do
561
+ Status.limit(20)
385
562
  end
386
563
  ```
387
564
 
565
+ * `detail`: A more enhanced description
566
+ * `params`: Define parameters directly from an `Entity`
567
+ * `success`: (former entity) The `Entity` to be used to present the success response for this route.
568
+ * `failure`: (former http_codes) A definition of the used failure HTTP Codes and Entities.
569
+ * `default`: The definition and `Entity` used to present the default response for this route.
570
+ * `named`: A helper to give a route a name and find it with this name in the documentation Hash
571
+ * `headers`: A definition of the used Headers
572
+ * Other options can be found in [grape-swagger][grape-swagger]
573
+
574
+ [grape-swagger]: https://github.com/ruby-grape/grape-swagger
575
+
576
+ ## Configuration
577
+
578
+ Use `Grape.configure` to set up global settings at load time.
579
+ Currently the configurable settings are:
580
+
581
+ * `param_builder`: Sets the [Parameter Builder](#parameters), defaults to `Grape::Extensions::ActiveSupport::HashWithIndifferentAccess::ParamBuilder`.
582
+
583
+ To change a setting value make sure that at some point during load time the following code runs
584
+
388
585
  ```ruby
389
- params do
390
- requires :text, alpha_numeric: true
586
+ Grape.configure do |config|
587
+ config.setting = value
391
588
  end
392
589
  ```
393
590
 
394
- You can also create custom classes that take parameters.
591
+ For example, for the `param_builder`, the following code could run in an initializer:
395
592
 
396
593
  ```ruby
397
- class Length < Grape::Validations::SingleOptionValidator
398
- def validate_param!(attr_name, params)
399
- unless params[attr_name].length <= @option
400
- throw :error, status: 400, message: "#{attr_name}: must be at the most #{@option} characters long"
401
- end
402
- end
594
+ Grape.configure do |config|
595
+ config.param_builder = :hashie_mash
403
596
  end
404
597
  ```
405
598
 
599
+ Available parameter builders are `:hash`, `:hash_with_indifferent_access`, and `:hashie_mash`.
600
+ See [params_builder](lib/grape/params_builder).
601
+
602
+ You can also configure a single API:
603
+
406
604
  ```ruby
407
- params do
408
- requires :text, length: 140
605
+ API.configure do |config|
606
+ config[key] = value
409
607
  end
410
608
  ```
411
609
 
412
- ### Validation Errors
610
+ This will be available inside the API with `configuration`, as if it were [mount configuration](#mount-configuration).
413
611
 
414
- When validation and coercion errors occur an exception of type `Grape::Exceptions::Validation` is raised.
415
- If the exception goes uncaught it will respond with a status of 400 and an error message.
416
- You can rescue a `Grape::Exceptions::Validation` and respond with a custom response.
612
+ ## Parameters
613
+
614
+ Request parameters are available through the `params` hash object. This includes `GET`, `POST` and `PUT` parameters, along with any named parameters you specify in your route strings.
417
615
 
418
616
  ```ruby
419
- rescue_from Grape::Exceptions::Validation do |e|
420
- Rack::Response.new({
421
- 'status' => e.status,
422
- 'message' => e.message,
423
- 'param' => e.param
424
- }.to_json, e.status)
617
+ get :public_timeline do
618
+ Status.order(params[:sort_by])
425
619
  end
426
620
  ```
427
621
 
428
- ## Headers
622
+ Parameters are automatically populated from the request body on `POST` and `PUT` for form input, JSON and XML content-types.
429
623
 
430
- Request headers are available through the `headers` helper or from `env` in their original form.
624
+ The request:
431
625
 
432
- ```ruby
433
- get do
434
- error!('Unauthorized', 401) unless headers['Secret-Password'] == 'swordfish'
435
- end
436
626
  ```
627
+ curl -d '{"text": "140 characters"}' 'http://localhost:9292/statuses' -H Content-Type:application/json -v
628
+ ```
629
+
630
+ The Grape endpoint:
437
631
 
438
632
  ```ruby
439
- get do
440
- error!('Unauthorized', 401) unless env['HTTP_SECRET_PASSWORD'] == 'swordfish'
633
+ post '/statuses' do
634
+ Status.create!(text: params[:text])
441
635
  end
442
636
  ```
443
637
 
444
- You can set a response header with `header` inside an API.
638
+ Multipart POSTs and PUTs are supported as well.
639
+
640
+ The request:
641
+
642
+ ```
643
+ curl --form image_file='@image.jpg;type=image/jpg' http://localhost:9292/upload
644
+ ```
645
+
646
+ The Grape endpoint:
445
647
 
446
648
  ```ruby
447
- header "X-Robots-Tag", "noindex"
649
+ post 'upload' do
650
+ # file in params[:image_file]
651
+ end
448
652
  ```
449
653
 
450
- ## Routes
654
+ In the case of conflict between either of:
655
+
656
+ * route string parameters
657
+ * `GET`, `POST` and `PUT` parameters
658
+ * the contents of the request body on `POST` and `PUT`
659
+
660
+ Route string parameters will have precedence.
451
661
 
452
- Optionally, you can define requirements for your named route parameters using regular
453
- expressions on namespace or endpoint. The route will match only if all requirements are met.
662
+ ### Params Class
663
+
664
+ By default parameters are available as `ActiveSupport::HashWithIndifferentAccess`. This can be changed to, for example, Ruby `Hash` or `Hashie::Mash` for the entire API.
454
665
 
455
666
  ```ruby
456
- get ':id', requirements: { id: /[0-9]*/ } do
457
- Status.find(params[:id])
458
- end
667
+ class API < Grape::API
668
+ build_with :hashie_mash
459
669
 
460
- namespace :outer, requirements: { id: /[0-9]*/ } do
461
- get :id do
670
+ params do
671
+ optional :color, type: String
462
672
  end
463
-
464
- get ":id/edit" do
673
+ get do
674
+ params.color # instead of params[:color]
465
675
  end
466
- end
467
676
  ```
468
677
 
469
- ## Helpers
470
-
471
- You can define helper methods that your endpoints can use with the `helpers`
472
- macro by either giving a block or a module.
678
+ The class can also be overridden on individual parameter blocks using `build_with` as follows.
473
679
 
474
680
  ```ruby
475
- module StatusHelpers
476
- def user_info(user)
477
- "#{user} has statused #{user.statuses} status(s)"
478
- end
681
+ params do
682
+ build_with :hash
683
+ optional :color, type: String
479
684
  end
685
+ ```
480
686
 
481
- class API < Grape::API
482
- # define helpers with a block
687
+ In the example above, `params["color"]` will return `nil` since `params` is a plain `Hash`.
688
+
689
+ Available parameter builders are `:hash`, `:hash_with_indifferent_access`, and `:hashie_mash`.
690
+ See [params_builder](lib/grape/params_builder).
691
+
692
+ ### Declared
693
+
694
+ Grape allows you to access only the parameters that have been declared by your `params` block. It will:
695
+
696
+ * Filter out the params that have been passed, but are not allowed.
697
+ * Include any optional params that are declared but not passed.
698
+ * Perform any parameter renaming on the resulting hash.
699
+
700
+ Consider the following API endpoint:
701
+
702
+ ````ruby
703
+ format :json
704
+
705
+ post 'users/signup' do
706
+ { 'declared_params' => declared(params) }
707
+ end
708
+ ````
709
+
710
+ If you do not specify any parameters, `declared` will return an empty hash.
711
+
712
+ **Request**
713
+
714
+ ````bash
715
+ curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": "last name"}}'
716
+ ````
717
+
718
+ **Response**
719
+
720
+ ````json
721
+ {
722
+ "declared_params": {}
723
+ }
724
+
725
+ ````
726
+
727
+ Once we add parameters requirements, grape will start returning only the declared parameters.
728
+
729
+ ````ruby
730
+ format :json
731
+
732
+ params do
733
+ optional :user, type: Hash do
734
+ optional :first_name, type: String
735
+ optional :last_name, type: String
736
+ end
737
+ end
738
+
739
+ post 'users/signup' do
740
+ { 'declared_params' => declared(params) }
741
+ end
742
+ ````
743
+
744
+ **Request**
745
+
746
+ ````bash
747
+ 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"}}'
748
+ ````
749
+
750
+ **Response**
751
+
752
+ ````json
753
+ {
754
+ "declared_params": {
755
+ "user": {
756
+ "first_name": "first name",
757
+ "last_name": "last name"
758
+ }
759
+ }
760
+ }
761
+ ````
762
+
763
+ Missing params that are declared as type `Hash` or `Array` will be included.
764
+
765
+ ````ruby
766
+ format :json
767
+
768
+ params do
769
+ optional :user, type: Hash do
770
+ optional :first_name, type: String
771
+ optional :last_name, type: String
772
+ end
773
+ optional :widgets, type: Array
774
+ end
775
+
776
+ post 'users/signup' do
777
+ { 'declared_params' => declared(params) }
778
+ end
779
+ ````
780
+
781
+ **Request**
782
+
783
+ ````bash
784
+ curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{}'
785
+ ````
786
+
787
+ **Response**
788
+
789
+ ````json
790
+ {
791
+ "declared_params": {
792
+ "user": {
793
+ "first_name": null,
794
+ "last_name": null
795
+ },
796
+ "widgets": []
797
+ }
798
+ }
799
+ ````
800
+
801
+ The returned hash is an `ActiveSupport::HashWithIndifferentAccess`.
802
+
803
+ The `#declared` method is not available to `before` filters, as those are evaluated prior to parameter coercion.
804
+
805
+ ### Include Parent Namespaces
806
+
807
+ By default `declared(params)` includes parameters that were defined in all parent namespaces. If you want to return only parameters from your current namespace, you can set `include_parent_namespaces` option to `false`.
808
+
809
+ ````ruby
810
+ format :json
811
+
812
+ namespace :parent do
813
+ params do
814
+ requires :parent_name, type: String
815
+ end
816
+
817
+ namespace ':parent_name' do
818
+ params do
819
+ requires :child_name, type: String
820
+ end
821
+ get ':child_name' do
822
+ {
823
+ 'without_parent_namespaces' => declared(params, include_parent_namespaces: false),
824
+ 'with_parent_namespaces' => declared(params, include_parent_namespaces: true),
825
+ }
826
+ end
827
+ end
828
+ end
829
+ ````
830
+
831
+ **Request**
832
+
833
+ ````bash
834
+ curl -X GET -H "Content-Type: application/json" localhost:9292/parent/foo/bar
835
+ ````
836
+
837
+ **Response**
838
+
839
+ ````json
840
+ {
841
+ "without_parent_namespaces": {
842
+ "child_name": "bar"
843
+ },
844
+ "with_parent_namespaces": {
845
+ "parent_name": "foo",
846
+ "child_name": "bar"
847
+ },
848
+ }
849
+ ````
850
+
851
+ ### Include Missing
852
+
853
+ By default `declared(params)` includes parameters that have `nil` values. If you want to return only the parameters that are not `nil`, you can use the `include_missing` option. By default, `include_missing` is set to `true`. Consider the following API:
854
+
855
+ ````ruby
856
+ format :json
857
+
858
+ params do
859
+ requires :user, type: Hash do
860
+ requires :first_name, type: String
861
+ optional :last_name, type: String
862
+ end
863
+ end
864
+
865
+ post 'users/signup' do
866
+ { 'declared_params' => declared(params, include_missing: false) }
867
+ end
868
+ ````
869
+
870
+ **Request**
871
+
872
+ ````bash
873
+ curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "random": "never shown"}}'
874
+ ````
875
+
876
+ **Response with include_missing:false**
877
+
878
+ ````json
879
+ {
880
+ "declared_params": {
881
+ "user": {
882
+ "first_name": "first name"
883
+ }
884
+ }
885
+ }
886
+ ````
887
+
888
+ **Response with include_missing:true**
889
+
890
+ ````json
891
+ {
892
+ "declared_params": {
893
+ "user": {
894
+ "first_name": "first name",
895
+ "last_name": null
896
+ }
897
+ }
898
+ }
899
+ ````
900
+
901
+ It also works on nested hashes:
902
+
903
+ ````ruby
904
+ format :json
905
+
906
+ params do
907
+ requires :user, type: Hash do
908
+ requires :first_name, type: String
909
+ optional :last_name, type: String
910
+ requires :address, type: Hash do
911
+ requires :city, type: String
912
+ optional :region, type: String
913
+ end
914
+ end
915
+ end
916
+
917
+ post 'users/signup' do
918
+ { 'declared_params' => declared(params, include_missing: false) }
919
+ end
920
+ ````
921
+
922
+ **Request**
923
+
924
+ ````bash
925
+ curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "random": "never shown", "address": { "city": "SF"}}}'
926
+ ````
927
+
928
+ **Response with include_missing:false**
929
+
930
+ ````json
931
+ {
932
+ "declared_params": {
933
+ "user": {
934
+ "first_name": "first name",
935
+ "address": {
936
+ "city": "SF"
937
+ }
938
+ }
939
+ }
940
+ }
941
+ ````
942
+
943
+ **Response with include_missing:true**
944
+
945
+ ````json
946
+ {
947
+ "declared_params": {
948
+ "user": {
949
+ "first_name": "first name",
950
+ "last_name": null,
951
+ "address": {
952
+ "city": "Zurich",
953
+ "region": null
954
+ }
955
+ }
956
+ }
957
+ }
958
+ ````
959
+
960
+ Note that an attribute with a `nil` value is not considered *missing* and will also be returned when `include_missing` is set to `false`:
961
+
962
+ **Request**
963
+
964
+ ````bash
965
+ curl -X POST -H "Content-Type: application/json" localhost:9292/users/signup -d '{"user": {"first_name":"first name", "last_name": null, "address": { "city": "SF"}}}'
966
+ ````
967
+
968
+ **Response with include_missing:false**
969
+
970
+ ````json
971
+ {
972
+ "declared_params": {
973
+ "user": {
974
+ "first_name": "first name",
975
+ "last_name": null,
976
+ "address": { "city": "SF"}
977
+ }
978
+ }
979
+ }
980
+ ````
981
+
982
+ ### Evaluate Given
983
+
984
+ By default `declared(params)` will not evaluate `given` and return all parameters. Use `evaluate_given` to evaluate all `given` blocks and return only parameters that satisfy `given` conditions. Consider the following API:
985
+
986
+ ````ruby
987
+ format :json
988
+
989
+ params do
990
+ optional :child_id, type: Integer
991
+ given :child_id do
992
+ requires :father_id, type: Integer
993
+ end
994
+ end
995
+
996
+ post 'child' do
997
+ { 'declared_params' => declared(params, evaluate_given: true) }
998
+ end
999
+ ````
1000
+
1001
+ **Request**
1002
+
1003
+ ````bash
1004
+ curl -X POST -H "Content-Type: application/json" localhost:9292/child -d '{"father_id": 1}'
1005
+ ````
1006
+
1007
+ **Response with evaluate_given:false**
1008
+
1009
+ ````json
1010
+ {
1011
+ "declared_params": {
1012
+ "child_id": null,
1013
+ "father_id": 1
1014
+ }
1015
+ }
1016
+ ````
1017
+
1018
+ **Response with evaluate_given:true**
1019
+
1020
+ ````json
1021
+ {
1022
+ "declared_params": {
1023
+ "child_id": null
1024
+ }
1025
+ }
1026
+ ````
1027
+
1028
+ It also works on nested hashes:
1029
+
1030
+ ````ruby
1031
+ format :json
1032
+
1033
+ params do
1034
+ requires :child, type: Hash do
1035
+ optional :child_id, type: Integer
1036
+ given :child_id do
1037
+ requires :father_id, type: Integer
1038
+ end
1039
+ end
1040
+ end
1041
+
1042
+ post 'child' do
1043
+ { 'declared_params' => declared(params, evaluate_given: true) }
1044
+ end
1045
+ ````
1046
+
1047
+ **Request**
1048
+
1049
+ ````bash
1050
+ curl -X POST -H "Content-Type: application/json" localhost:9292/child -d '{"child": {"father_id": 1}}'
1051
+ ````
1052
+
1053
+ **Response with evaluate_given:false**
1054
+
1055
+ ````json
1056
+ {
1057
+ "declared_params": {
1058
+ "child": {
1059
+ "child_id": null,
1060
+ "father_id": 1
1061
+ }
1062
+ }
1063
+ }
1064
+ ````
1065
+
1066
+ **Response with evaluate_given:true**
1067
+
1068
+ ````json
1069
+ {
1070
+ "declared_params": {
1071
+ "child": {
1072
+ "child_id": null
1073
+ }
1074
+ }
1075
+ }
1076
+ ````
1077
+
1078
+ ### Parameter Precedence
1079
+
1080
+ Using `route_param` takes higher precedence over a regular parameter defined with same name:
1081
+
1082
+ ```ruby
1083
+ params do
1084
+ requires :foo, type: String
1085
+ end
1086
+ route_param :foo do
1087
+ get do
1088
+ { value: params[:foo] }
1089
+ end
1090
+ end
1091
+ ```
1092
+
1093
+ **Request**
1094
+
1095
+ ```bash
1096
+ curl -X POST -H "Content-Type: application/json" localhost:9292/bar -d '{"foo": "baz"}'
1097
+ ```
1098
+
1099
+ **Response**
1100
+
1101
+ ```json
1102
+ {
1103
+ "value": "bar"
1104
+ }
1105
+ ```
1106
+
1107
+ ## Parameter Validation and Coercion
1108
+
1109
+ You can define validations and coercion options for your parameters using a `params` block.
1110
+
1111
+ ```ruby
1112
+ params do
1113
+ requires :id, type: Integer
1114
+ optional :text, type: String, regexp: /\A[a-z]+\z/
1115
+ group :media, type: Hash do
1116
+ requires :url
1117
+ end
1118
+ optional :audio, type: Hash do
1119
+ requires :format, type: Symbol, values: [:mp3, :wav, :aac, :ogg], default: :mp3
1120
+ end
1121
+ mutually_exclusive :media, :audio
1122
+ end
1123
+ put ':id' do
1124
+ # params[:id] is an Integer
1125
+ end
1126
+ ```
1127
+
1128
+ When a type is specified an implicit validation is done after the coercion to ensure the output type is the one declared.
1129
+
1130
+ Optional parameters can have a default value.
1131
+
1132
+ ```ruby
1133
+ params do
1134
+ optional :color, type: String, default: 'blue'
1135
+ optional :random_number, type: Integer, default: -> { Random.rand(1..100) }
1136
+ optional :non_random_number, type: Integer, default: Random.rand(1..100)
1137
+ end
1138
+ ```
1139
+
1140
+ Default values are eagerly evaluated. Above `:non_random_number` will evaluate to the same number for each call to the endpoint of this `params` block. To have the default evaluate lazily with each request use a lambda, like `:random_number` above.
1141
+
1142
+ Note that default values will be passed through to any validation options specified.
1143
+ The following example will always fail if `:color` is not explicitly provided.
1144
+
1145
+ ```ruby
1146
+ params do
1147
+ optional :color, type: String, default: 'blue', values: ['red', 'green']
1148
+ end
1149
+ ```
1150
+
1151
+ The correct implementation is to ensure the default value passes all validations.
1152
+
1153
+ ```ruby
1154
+ params do
1155
+ optional :color, type: String, default: 'blue', values: ['blue', 'red', 'green']
1156
+ end
1157
+ ```
1158
+
1159
+ You can use the value of one parameter as the default value of some other parameter. In this case, if the `primary_color` parameter is not provided, it will have the same value as the `color` one. If both of them not provided, both of them will have `blue` value.
1160
+
1161
+ ```ruby
1162
+ params do
1163
+ optional :color, type: String, default: 'blue'
1164
+ optional :primary_color, type: String, default: -> (params) { params[:color] }
1165
+ end
1166
+ ```
1167
+
1168
+ ### Supported Parameter Types
1169
+
1170
+ The following are all valid types, supported out of the box by Grape:
1171
+
1172
+ * Integer
1173
+ * Float
1174
+ * BigDecimal
1175
+ * Numeric
1176
+ * Date
1177
+ * DateTime
1178
+ * Time
1179
+ * Boolean
1180
+ * String
1181
+ * Symbol
1182
+ * Rack::Multipart::UploadedFile (alias `File`)
1183
+ * JSON
1184
+
1185
+ ### Integer/Fixnum and Coercions
1186
+
1187
+ Please be aware that the behavior differs between Ruby 2.4 and earlier versions.
1188
+ In Ruby 2.4, values consisting of numbers are converted to Integer, but in earlier versions it will be treated as Fixnum.
1189
+
1190
+ ```ruby
1191
+ params do
1192
+ requires :integers, type: Hash do
1193
+ requires :int, coerce: Integer
1194
+ end
1195
+ end
1196
+ get '/int' do
1197
+ params[:integers][:int].class
1198
+ end
1199
+
1200
+ ...
1201
+
1202
+ get '/int' integers: { int: '45' }
1203
+ #=> Integer in ruby 2.4
1204
+ #=> Fixnum in earlier ruby versions
1205
+ ```
1206
+
1207
+ ### Custom Types and Coercions
1208
+
1209
+ 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-level `parse` 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 of `Grape::Types::InvalidValue` which optionally accepts a message to be returned in the response.
1210
+
1211
+ ```ruby
1212
+ class Color
1213
+ attr_reader :value
1214
+ def initialize(color)
1215
+ @value = color
1216
+ end
1217
+
1218
+ def self.parse(value)
1219
+ return new(value) if %w[blue red green].include?(value)
1220
+
1221
+ Grape::Types::InvalidValue.new('Unsupported color')
1222
+ end
1223
+ end
1224
+
1225
+ params do
1226
+ requires :color, type: Color, default: Color.new('blue')
1227
+ requires :more_colors, type: Array[Color] # Collections work
1228
+ optional :unique_colors, type: Set[Color] # Duplicates discarded
1229
+ end
1230
+
1231
+ get '/stuff' do
1232
+ # params[:color] is already a Color.
1233
+ params[:color].value
1234
+ end
1235
+ ```
1236
+
1237
+ Alternatively, a custom coercion method may be supplied for any type of parameter using `coerce_with`. Any class or object may be given that implements a `parse` or `call` method, in that order of precedence. The method must accept a single string parameter, and the return value must match the given `type`.
1238
+
1239
+ ```ruby
1240
+ params do
1241
+ requires :passwd, type: String, coerce_with: Base64.method(:decode64)
1242
+ requires :loud_color, type: Color, coerce_with: ->(c) { Color.parse(c.downcase) }
1243
+
1244
+ requires :obj, type: Hash, coerce_with: JSON do
1245
+ requires :words, type: Array[String], coerce_with: ->(val) { val.split(/\s+/) }
1246
+ optional :time, type: Time, coerce_with: Chronic
1247
+ end
1248
+ end
1249
+ ```
1250
+ Note that, a `nil` value will call the custom coercion method, while a missing parameter will not.
1251
+
1252
+ Example of use of `coerce_with` with a lambda (a class with a `parse` method could also have been used)
1253
+ It will parse a string and return an Array of Integers, matching the `Array[Integer]` `type`.
1254
+
1255
+ ```ruby
1256
+ params do
1257
+ requires :values, type: Array[Integer], coerce_with: ->(val) { val.split(/\s+/).map(&:to_i) }
1258
+ end
1259
+ ```
1260
+
1261
+ Grape will assert that coerced values match the given `type`, and will reject the request if they do not. To override this behaviour, custom types may implement a `parsed?` method that should accept a single argument and return `true` if the value passes type validation.
1262
+
1263
+ ```ruby
1264
+ class SecureUri
1265
+ def self.parse(value)
1266
+ URI.parse value
1267
+ end
1268
+
1269
+ def self.parsed?(value)
1270
+ value.is_a? URI::HTTPS
1271
+ end
1272
+ end
1273
+
1274
+ params do
1275
+ requires :secure_uri, type: SecureUri
1276
+ end
1277
+ ```
1278
+
1279
+ ### Multipart File Parameters
1280
+
1281
+ Grape makes use of `Rack::Request`'s built-in support for multipart file parameters. Such parameters can be declared with `type: File`:
1282
+
1283
+ ```ruby
1284
+ params do
1285
+ requires :avatar, type: File
1286
+ end
1287
+ post '/' do
1288
+ params[:avatar][:filename] # => 'avatar.png'
1289
+ params[:avatar][:type] # => 'image/png'
1290
+ params[:avatar][:tempfile] # => #<File>
1291
+ end
1292
+ ```
1293
+
1294
+ ### First-Class `JSON` Types
1295
+
1296
+ Grape supports complex parameters given as JSON-formatted strings using the special `type: JSON` declaration. JSON objects and arrays of objects are accepted equally, with nested validation rules applied to all objects in either case:
1297
+
1298
+ ```ruby
1299
+ params do
1300
+ requires :json, type: JSON do
1301
+ requires :int, type: Integer, values: [1, 2, 3]
1302
+ end
1303
+ end
1304
+ get '/' do
1305
+ params[:json].inspect
1306
+ end
1307
+
1308
+ client.get('/', json: '{"int":1}') # => "{:int=>1}"
1309
+ client.get('/', json: '[{"int":"1"}]') # => "[{:int=>1}]"
1310
+
1311
+ client.get('/', json: '{"int":4}') # => HTTP 400
1312
+ client.get('/', json: '[{"int":4}]') # => HTTP 400
1313
+ ```
1314
+
1315
+ Additionally `type: Array[JSON]` may be used, which explicitly marks the parameter as an array of objects. If a single object is supplied it will be wrapped.
1316
+
1317
+ ```ruby
1318
+ params do
1319
+ requires :json, type: Array[JSON] do
1320
+ requires :int, type: Integer
1321
+ end
1322
+ end
1323
+ get '/' do
1324
+ params[:json].each { |obj| ... } # always works
1325
+ end
1326
+ ```
1327
+ For stricter control over the type of JSON structure which may be supplied, use `type: Array, coerce_with: JSON` or `type: Hash, coerce_with: JSON`.
1328
+
1329
+ ### Multiple Allowed Types
1330
+
1331
+ Variant-type parameters can be declared using the `types` option rather than `type`:
1332
+
1333
+ ```ruby
1334
+ params do
1335
+ requires :status_code, types: [Integer, String, Array[Integer, String]]
1336
+ end
1337
+ get '/' do
1338
+ params[:status_code].inspect
1339
+ end
1340
+
1341
+ client.get('/', status_code: 'OK_GOOD') # => "OK_GOOD"
1342
+ client.get('/', status_code: 300) # => 300
1343
+ client.get('/', status_code: %w(404 NOT FOUND)) # => [404, "NOT", "FOUND"]
1344
+ ```
1345
+
1346
+ As a special case, variant-member-type collections may also be declared, by passing a `Set` or `Array` with more than one member to `type`:
1347
+
1348
+ ```ruby
1349
+ params do
1350
+ requires :status_codes, type: Array[Integer,String]
1351
+ end
1352
+ get '/' do
1353
+ params[:status_codes].inspect
1354
+ end
1355
+
1356
+ client.get('/', status_codes: %w(1 two)) # => [1, "two"]
1357
+ ```
1358
+
1359
+ ### Validation of Nested Parameters
1360
+
1361
+ Parameters can be nested using `group` or by calling `requires` or `optional` with a block.
1362
+ In the [above example](#parameter-validation-and-coercion), this means `params[:media][:url]` is required along with `params[:id]`, and `params[:audio][:format]` is required only if `params[:audio]` is present.
1363
+ With a block, `group`, `requires` and `optional` accept an additional option `type` which can be either `Array` or `Hash`, and defaults to `Array`. Depending on the value, the nested parameters will be treated either as values of a hash or as values of hashes in an array.
1364
+
1365
+ ```ruby
1366
+ params do
1367
+ optional :preferences, type: Array do
1368
+ requires :key
1369
+ requires :value
1370
+ end
1371
+
1372
+ requires :name, type: Hash do
1373
+ requires :first_name
1374
+ requires :last_name
1375
+ end
1376
+ end
1377
+ ```
1378
+
1379
+ ### Dependent Parameters
1380
+
1381
+ Suppose some of your parameters are only relevant if another parameter is given; Grape allows you to express this relationship through the `given` method in your parameters block, like so:
1382
+
1383
+ ```ruby
1384
+ params do
1385
+ optional :shelf_id, type: Integer
1386
+ given :shelf_id do
1387
+ requires :bin_id, type: Integer
1388
+ end
1389
+ end
1390
+ ```
1391
+
1392
+ In the example above Grape will use `blank?` to check whether the `shelf_id` param is present.
1393
+
1394
+ `given` also takes a `Proc` with custom code. Below, the param `description` is required only if the value of `category` is equal `foo`:
1395
+
1396
+ ```ruby
1397
+ params do
1398
+ optional :category
1399
+ given category: ->(val) { val == 'foo' } do
1400
+ requires :description
1401
+ end
1402
+ end
1403
+ ```
1404
+
1405
+ You can rename parameters:
1406
+
1407
+ ```ruby
1408
+ params do
1409
+ optional :category, as: :type
1410
+ given type: ->(val) { val == 'foo' } do
1411
+ requires :description
1412
+ end
1413
+ end
1414
+ ```
1415
+
1416
+ Note: param in `given` should be the renamed one. In the example, it should be `type`, not `category`.
1417
+
1418
+ ### Group Options
1419
+
1420
+ Parameters options can be grouped. It can be useful if you want to extract common validation or types for several parameters.
1421
+ 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.
1422
+
1423
+ The example below presents a typical case when parameters share common options.
1424
+
1425
+ ```ruby
1426
+ params do
1427
+ requires :first_name, type: String, regexp: /w+/, desc: 'First name', documentation: { in: 'body' }
1428
+ optional :middle_name, type: String, regexp: /w+/, desc: 'Middle name', documentation: { in: 'body', x: { nullable: true } }
1429
+ requires :last_name, type: String, regexp: /w+/, desc: 'Last name', documentation: { in: 'body' }
1430
+ end
1431
+ ```
1432
+
1433
+ Grape allows you to present the same logic through the `with` method in your parameters block, like so:
1434
+
1435
+ ```ruby
1436
+ params do
1437
+ with(type: String, regexp: /w+/, documentation: { in: 'body' }) do
1438
+ requires :first_name, desc: 'First name'
1439
+ optional :middle_name, desc: 'Middle name', documentation: { x: { nullable: true } }
1440
+ requires :last_name, desc: 'Last name'
1441
+ end
1442
+ end
1443
+ ```
1444
+
1445
+ 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.
1446
+
1447
+ ```ruby
1448
+ params do
1449
+ with(documentation: { in: 'body' }) do # Applies documentation to all nested parameters
1450
+ with(type: String, regexp: /\w+/) do # Applies type and validation to names
1451
+ requires :first_name, desc: 'First name'
1452
+ requires :last_name, desc: 'Last name'
1453
+ end
1454
+ optional :age, type: Integer, desc: 'Age', documentation: { x: { nullable: true } } # Specific settings for 'age'
1455
+ end
1456
+ end
1457
+ ```
1458
+
1459
+ ### Renaming
1460
+
1461
+ You can rename parameters using `as`, which can be useful when refactoring existing APIs:
1462
+
1463
+ ```ruby
1464
+ resource :users do
1465
+ params do
1466
+ requires :email_address, as: :email
1467
+ requires :password
1468
+ end
1469
+ post do
1470
+ User.create!(declared(params)) # User takes email and password
1471
+ end
1472
+ end
1473
+ ```
1474
+
1475
+ The value passed to `as` will be the key when calling `declared(params)`.
1476
+
1477
+ ### Built-in Validators
1478
+
1479
+ #### `allow_blank`
1480
+
1481
+ Parameters can be defined as `allow_blank`, ensuring that they contain a value. By default, `requires` only validates that a parameter was sent in the request, regardless its value. With `allow_blank: false`, empty values or whitespace only values are invalid.
1482
+
1483
+ `allow_blank` can be combined with both `requires` and `optional`. If the parameter is required, it has to contain a value. If it's optional, it's possible to not send it in the request, but if it's being sent, it has to have some value, and not an empty string/only whitespaces.
1484
+
1485
+
1486
+ ```ruby
1487
+ params do
1488
+ requires :username, allow_blank: false
1489
+ optional :first_name, allow_blank: false
1490
+ end
1491
+ ```
1492
+
1493
+ #### `values`
1494
+
1495
+ Parameters can be restricted to a specific set of values with the `:values` option.
1496
+
1497
+
1498
+ ```ruby
1499
+ params do
1500
+ requires :status, type: Symbol, values: [:not_started, :processing, :done]
1501
+ optional :numbers, type: Array[Integer], default: 1, values: [1, 2, 3, 5, 8]
1502
+ end
1503
+ ```
1504
+
1505
+ Supplying a range to the `:values` option ensures that the parameter is (or parameters are) included in that range (using `Range#include?`).
1506
+
1507
+ ```ruby
1508
+ params do
1509
+ requires :latitude, type: Float, values: -90.0..+90.0
1510
+ requires :longitude, type: Float, values: -180.0..+180.0
1511
+ optional :letters, type: Array[String], values: 'a'..'z'
1512
+ end
1513
+ ```
1514
+
1515
+ Note endless ranges are also supported with ActiveSupport >= 6.0, but they require that the type be provided.
1516
+
1517
+ ```ruby
1518
+ params do
1519
+ requires :minimum, type: Integer, values: 10..
1520
+ optional :maximum, type: Integer, values: ..10
1521
+ end
1522
+ ```
1523
+
1524
+ Note that *both* range endpoints have to be a `#kind_of?` your `:type` option (if you don't supply the `:type` option, it will be guessed to be equal to the class of the range's first endpoint). So the following is invalid:
1525
+
1526
+ ```ruby
1527
+ params do
1528
+ requires :invalid1, type: Float, values: 0..10 # 0.kind_of?(Float) => false
1529
+ optional :invalid2, values: 0..10.0 # 10.0.kind_of?(0.class) => false
1530
+ end
1531
+ ```
1532
+
1533
+ The `:values` option can also be supplied with a `Proc`, evaluated lazily with each request.
1534
+ 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.
1535
+
1536
+ For example, given a status model you may want to restrict by hashtags that you have previously defined in the `HashTag` model.
1537
+
1538
+ ```ruby
1539
+ params do
1540
+ requires :hashtag, type: String, values: -> { Hashtag.all.map(&:tag) }
1541
+ end
1542
+ ```
1543
+
1544
+ 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.
1545
+
1546
+ ```ruby
1547
+ params do
1548
+ requires :number, type: Integer, values: ->(v) { v.even? && v < 25 }
1549
+ end
1550
+ ```
1551
+
1552
+ While Procs are convenient for single cases, consider using [Custom Validators](#custom-validators) in cases where a validation is used more than once.
1553
+
1554
+ Note that [allow_blank](#allow_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 to `true`.
1555
+
1556
+ ```ruby
1557
+ params do
1558
+ requires :state, type: Symbol, values: [:active, :inactive]
1559
+ end
1560
+ ```
1561
+
1562
+ #### `except_values`
1563
+
1564
+ Parameters can be restricted from having a specific set of values with the `:except_values` option.
1565
+
1566
+ The `except_values` validator behaves similarly to the `values` validator in that it accepts either an Array, a Range, or a Proc. Unlike the `values` validator, however, `except_values` only accepts Procs with arity zero.
1567
+
1568
+ ```ruby
1569
+ params do
1570
+ requires :browser, except_values: [ 'ie6', 'ie7', 'ie8' ]
1571
+ requires :port, except_values: { value: 0..1024, message: 'is not allowed' }
1572
+ requires :hashtag, except_values: -> { Hashtag.FORBIDDEN_LIST }
1573
+ end
1574
+ ```
1575
+
1576
+ #### `same_as`
1577
+
1578
+ A `same_as` option can be given to ensure that values of parameters match.
1579
+
1580
+ ```ruby
1581
+ params do
1582
+ requires :password
1583
+ requires :password_confirmation, same_as: :password
1584
+ end
1585
+ ```
1586
+
1587
+ #### `length`
1588
+
1589
+ Parameters with types that support `#length` method can be restricted to have a specific length with the `:length` option.
1590
+
1591
+ 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.
1592
+
1593
+ ```ruby
1594
+ params do
1595
+ requires :code, type: String, length: { is: 2 }
1596
+ requires :str, type: String, length: { min: 3 }
1597
+ requires :list, type: [Integer], length: { min: 3, max: 5 }
1598
+ requires :hash, type: Hash, length: { max: 5 }
1599
+ end
1600
+ ```
1601
+
1602
+ #### `regexp`
1603
+
1604
+ Parameters can be restricted to match a specific regular expression with the `:regexp` option. If the value does not match the regular expression an error will be returned. Note that this is true for both `requires` and `optional` parameters.
1605
+
1606
+ ```ruby
1607
+ params do
1608
+ requires :email, regexp: /.+@.+/
1609
+ end
1610
+ ```
1611
+
1612
+ The validator will pass if the parameter was sent without value. To ensure that the parameter contains a value, use `allow_blank: false`.
1613
+
1614
+ ```ruby
1615
+ params do
1616
+ requires :email, allow_blank: false, regexp: /.+@.+/
1617
+ end
1618
+ ```
1619
+
1620
+ #### `mutually_exclusive`
1621
+
1622
+ Parameters can be defined as `mutually_exclusive`, ensuring that they aren't present at the same time in a request.
1623
+
1624
+ ```ruby
1625
+ params do
1626
+ optional :beer
1627
+ optional :wine
1628
+ mutually_exclusive :beer, :wine
1629
+ end
1630
+ ```
1631
+
1632
+ Multiple sets can be defined:
1633
+
1634
+ ```ruby
1635
+ params do
1636
+ optional :beer
1637
+ optional :wine
1638
+ mutually_exclusive :beer, :wine
1639
+ optional :scotch
1640
+ optional :aquavit
1641
+ mutually_exclusive :scotch, :aquavit
1642
+ end
1643
+ ```
1644
+
1645
+ **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.
1646
+
1647
+ #### `exactly_one_of`
1648
+
1649
+ Parameters can be defined as 'exactly_one_of', ensuring that exactly one parameter gets selected.
1650
+
1651
+ ```ruby
1652
+ params do
1653
+ optional :beer
1654
+ optional :wine
1655
+ exactly_one_of :beer, :wine
1656
+ end
1657
+ ```
1658
+
1659
+ Note that using `:default` with `mutually_exclusive` will cause multiple parameters to always have a default value and raise a `Grape::Exceptions::Validation` mutually exclusive exception.
1660
+
1661
+ #### `at_least_one_of`
1662
+
1663
+ Parameters can be defined as 'at_least_one_of', ensuring that at least one parameter gets selected.
1664
+
1665
+ ```ruby
1666
+ params do
1667
+ optional :beer
1668
+ optional :wine
1669
+ optional :juice
1670
+ at_least_one_of :beer, :wine, :juice
1671
+ end
1672
+ ```
1673
+
1674
+ #### `all_or_none_of`
1675
+
1676
+ Parameters can be defined as 'all_or_none_of', ensuring that all or none of parameters gets selected.
1677
+
1678
+ ```ruby
1679
+ params do
1680
+ optional :beer
1681
+ optional :wine
1682
+ optional :juice
1683
+ all_or_none_of :beer, :wine, :juice
1684
+ end
1685
+ ```
1686
+
1687
+ #### Nested `mutually_exclusive`, `exactly_one_of`, `at_least_one_of`, `all_or_none_of`
1688
+
1689
+ All of these methods can be used at any nested level.
1690
+
1691
+ ```ruby
1692
+ params do
1693
+ requires :food, type: Hash do
1694
+ optional :meat
1695
+ optional :fish
1696
+ optional :rice
1697
+ at_least_one_of :meat, :fish, :rice
1698
+ end
1699
+ group :drink, type: Hash do
1700
+ optional :beer
1701
+ optional :wine
1702
+ optional :juice
1703
+ exactly_one_of :beer, :wine, :juice
1704
+ end
1705
+ optional :dessert, type: Hash do
1706
+ optional :cake
1707
+ optional :icecream
1708
+ mutually_exclusive :cake, :icecream
1709
+ end
1710
+ optional :recipe, type: Hash do
1711
+ optional :oil
1712
+ optional :meat
1713
+ all_or_none_of :oil, :meat
1714
+ end
1715
+ end
1716
+ ```
1717
+
1718
+ ### Namespace Validation and Coercion
1719
+
1720
+ Namespaces allow parameter definitions and apply to every method within the namespace.
1721
+
1722
+ ```ruby
1723
+ namespace :statuses do
1724
+ params do
1725
+ requires :user_id, type: Integer, desc: 'A user ID.'
1726
+ end
1727
+ namespace ':user_id' do
1728
+ desc "Retrieve a user's status."
1729
+ params do
1730
+ requires :status_id, type: Integer, desc: 'A status ID.'
1731
+ end
1732
+ get ':status_id' do
1733
+ User.find(params[:user_id]).statuses.find(params[:status_id])
1734
+ end
1735
+ end
1736
+ end
1737
+ ```
1738
+
1739
+ The `namespace` method has a number of aliases, including: `group`, `resource`, `resources`, and `segment`. Use whichever reads the best for your API.
1740
+
1741
+ You can conveniently define a route parameter as a namespace using `route_param`.
1742
+
1743
+ ```ruby
1744
+ namespace :statuses do
1745
+ route_param :id do
1746
+ desc 'Returns all replies for a status.'
1747
+ get 'replies' do
1748
+ Status.find(params[:id]).replies
1749
+ end
1750
+ desc 'Returns a status.'
1751
+ get do
1752
+ Status.find(params[:id])
1753
+ end
1754
+ end
1755
+ end
1756
+ ```
1757
+
1758
+ You can also define a route parameter type by passing to `route_param`'s options.
1759
+
1760
+ ```ruby
1761
+ namespace :arithmetic do
1762
+ route_param :n, type: Integer do
1763
+ desc 'Returns in power'
1764
+ get 'power' do
1765
+ params[:n] ** params[:n]
1766
+ end
1767
+ end
1768
+ end
1769
+ ```
1770
+
1771
+ ### Custom Validators
1772
+
1773
+ ```ruby
1774
+ class AlphaNumeric < Grape::Validations::Validators::Base
1775
+ def validate_param!(attr_name, params)
1776
+ return if params[attr_name].match?(/\A[[:alnum:]]+\z/)
1777
+
1778
+ validation_error!(attr_name, 'must consist of alpha-numeric characters')
1779
+ end
1780
+ end
1781
+ ```
1782
+
1783
+ ```ruby
1784
+ params do
1785
+ requires :text, alpha_numeric: true
1786
+ end
1787
+ ```
1788
+
1789
+ You can also create custom classes that take parameters.
1790
+
1791
+ ```ruby
1792
+ class Length < Grape::Validations::Validators::Base
1793
+ def validate_param!(attr_name, params)
1794
+ return if params[attr_name].length <= @options
1795
+
1796
+ validation_error!(attr_name, "must be at the most #{@options} characters long")
1797
+ end
1798
+ end
1799
+ ```
1800
+
1801
+ ```ruby
1802
+ params do
1803
+ requires :text, length: 140
1804
+ end
1805
+ ```
1806
+
1807
+ 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.
1808
+
1809
+ ```ruby
1810
+ class Admin < Grape::Validations::Validators::Base
1811
+ def validate(request)
1812
+ # return if the param we are checking was not in request
1813
+ # @attrs is a list containing the attribute we are currently validating
1814
+ # in our sample case this method once will get called with
1815
+ # @attrs being [:admin_field] and once with @attrs being [:admin_false_field]
1816
+ return unless request.params.key?(@attrs.first)
1817
+ # check if admin flag is set to true
1818
+ return unless @options
1819
+ # check if user is admin or not
1820
+ # as an example get a token from request and check if it's admin or not
1821
+ validation_error!(@attrs, 'Can not set admin-only field.') unless request.headers['X-Access-Token'] == 'admin'
1822
+ end
1823
+ end
1824
+ ```
1825
+
1826
+ And use it in your endpoint definition as:
1827
+
1828
+ ```ruby
1829
+ params do
1830
+ optional :admin_field, type: String, admin: true
1831
+ optional :non_admin_field, type: String
1832
+ optional :admin_false_field, type: String, admin: false
1833
+ end
1834
+ ```
1835
+
1836
+ Each validator is instantiated once at route definition time and frozen. Any setup (option parsing, message building) should happen in `initialize`, not in `validate_param!` or `validate`.
1837
+
1838
+ #### Available helpers
1839
+
1840
+ The following protected/private helpers are available in any `Grape::Validations::Validators::Base` subclass:
1841
+
1842
+ | Helper | Description |
1843
+ |---|---|
1844
+ | `default_message_key(key)` | Class-level macro. Declares the default I18n key for `validation_error!`. A per-option `:message` override still takes precedence. |
1845
+ | `validation_error!(attr_name_or_params, message = @exception_message)` | Raises `Grape::Exceptions::Validation`. Accepts a single attribute name or a pre-computed array of full param names. |
1846
+ | `@options` | The validator option value, deep-frozen at initialization. |
1847
+ | `@attrs` | Frozen array of attribute names this validator applies to. |
1848
+ | `@scope` | The `ParamsScope` — use `@scope.full_name(attr_name)` for the fully-qualified param name. |
1849
+ | `option_value` | Returns `@options[:value]` if present, otherwise `@options`. |
1850
+ | `options_key?(key)` | Returns true if `@options` is a hash with a non-nil `key`. |
1851
+ | `hash_like?(obj)` | Returns true if `obj` responds to `key?`. |
1852
+ | `scrub(value)` | Returns `value` with invalid byte sequences scrubbed. |
1853
+ | `translate(key, **opts)` | I18n lookup with `:en` fallback and `grape.errors.messages` scope. Called at request time to respect per-request locale. |
1854
+
1855
+ Use `default_message_key` for a fixed I18n key. The message is resolved once at route definition time via `message`, so a per-option `:message` override still wins:
1856
+
1857
+ ```ruby
1858
+ class SpecialValidator < Grape::Validations::Validators::Base
1859
+ default_message_key :special
1860
+
1861
+ def validate_param!(attr_name, params)
1862
+ return if valid?(params[attr_name])
1863
+
1864
+ validation_error!(attr_name)
1865
+ end
1866
+ end
1867
+ ```
1868
+
1869
+ For interpolated messages that must respect per-request locale, call `translate` directly inside `validate_param!`:
1870
+
1871
+ ```ruby
1872
+ class SpecialValidator < Grape::Validations::Validators::Base
1873
+ def validate_param!(attr_name, params)
1874
+ return if valid?(params[attr_name])
1875
+
1876
+ validation_error!(attr_name, translate(:special, min: 2, max: 10))
1877
+ end
1878
+ end
1879
+ ```
1880
+
1881
+ ### Validation Errors
1882
+
1883
+ Validation and coercion errors are collected and an exception of type `Grape::Exceptions::ValidationErrors` is raised. If the exception goes uncaught it will respond with a status of 400 and an error message. The validation errors are grouped by parameter name and can be accessed via `Grape::Exceptions::ValidationErrors#errors`.
1884
+
1885
+
1886
+ The default response from a `Grape::Exceptions::ValidationErrors` is a humanly readable string, such as "beer, wine are mutually exclusive", in the following example.
1887
+
1888
+ ```ruby
1889
+ params do
1890
+ optional :beer
1891
+ optional :wine
1892
+ optional :juice
1893
+ exactly_one_of :beer, :wine, :juice
1894
+ end
1895
+ ```
1896
+
1897
+ You can rescue a `Grape::Exceptions::ValidationErrors` and respond with a custom response or turn the response into well-formatted JSON for a JSON API that separates individual parameters and the corresponding error messages. The following `rescue_from` example produces `[{"params":["beer","wine"],"messages":["are mutually exclusive"]}]`.
1898
+
1899
+ ```ruby
1900
+ format :json
1901
+ subject.rescue_from Grape::Exceptions::ValidationErrors do |e|
1902
+ error! e, 400
1903
+ end
1904
+ ```
1905
+
1906
+ `Grape::Exceptions::ValidationErrors#full_messages` returns the validation messages as an array. `Grape::Exceptions::ValidationErrors#message` joins the messages to one string.
1907
+
1908
+ For responding with an array of validation messages, you can use `Grape::Exceptions::ValidationErrors#full_messages`.
1909
+ ```ruby
1910
+ format :json
1911
+ subject.rescue_from Grape::Exceptions::ValidationErrors do |e|
1912
+ error!({ messages: e.full_messages }, 400)
1913
+ end
1914
+ ```
1915
+
1916
+ Grape returns all validation and coercion errors found by default.
1917
+ To skip all subsequent validation checks when a specific param is found invalid, use `fail_fast: true`.
1918
+
1919
+ The following example will not check if `:wine` is present unless it finds `:beer`.
1920
+ ```ruby
1921
+ params do
1922
+ required :beer, fail_fast: true
1923
+ required :wine
1924
+ end
1925
+ ```
1926
+ The result of empty params would be a single `Grape::Exceptions::ValidationErrors` error.
1927
+
1928
+ Similarly, no regular expression test will be performed if `:blah` is blank in the following example.
1929
+ ```ruby
1930
+ params do
1931
+ required :blah, allow_blank: false, regexp: /blah/, fail_fast: true
1932
+ end
1933
+ ```
1934
+
1935
+ ### I18n
1936
+
1937
+ Grape supports I18n for parameter-related error messages, but will fallback to English if translations for the default locale have not been provided. See [en.yml](lib/grape/locale/en.yml) for message keys.
1938
+
1939
+ 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.
1940
+
1941
+ Custom validators that inherit from `Grape::Validations::Validators::Base` have access to a `translate` helper (see `Grape::Util::Translation`) and should use it instead of calling `I18n` directly. It applies the same `:en` fallback as built-in validators, defaults `scope` to `'grape.errors.messages'`, and handles interpolation without needing `format`:
1942
+
1943
+ ```ruby
1944
+ # Good — scope defaults to 'grape.errors.messages', interpolation forwarded automatically
1945
+ translate(:special, min: 2, max: 10)
1946
+
1947
+ # Bad — format is unnecessary and risks conflicting with I18n reserved keys
1948
+ format I18n.t(:special, scope: 'grape.errors.messages'), min: 2, max: 10
1949
+ ```
1950
+
1951
+ Example custom validator using an interpolated i18n message:
1952
+
1953
+ ```ruby
1954
+ class SpecialValidator < Grape::Validations::Validators::Base
1955
+ def validate_param!(attr_name, params)
1956
+ return if valid?(params[attr_name])
1957
+
1958
+ validation_error!(attr_name, translate(:special, min: 2, max: 10))
1959
+ end
1960
+ end
1961
+ ```
1962
+
1963
+ ### Custom Validation messages
1964
+
1965
+ Grape supports custom validation messages for parameter-related and coerce-related error messages.
1966
+
1967
+ #### `presence`, `allow_blank`, `values`, `regexp`
1968
+
1969
+ ```ruby
1970
+ params do
1971
+ requires :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'
1972
+ end
1973
+ ```
1974
+
1975
+ #### `same_as`
1976
+
1977
+ ```ruby
1978
+ params do
1979
+ requires :password
1980
+ requires :password_confirmation, same_as: { value: :password, message: 'not match' }
1981
+ end
1982
+ ```
1983
+
1984
+ #### `length`
1985
+
1986
+ ```ruby
1987
+ params do
1988
+ requires :code, type: String, length: { is: 2, message: 'code is expected to be exactly 2 characters long' }
1989
+ requires :str, type: String, length: { min: 5, message: 'str is expected to be at least 5 characters long' }
1990
+ requires :list, type: [Integer], length: { min: 2, max: 3, message: 'list is expected to have between 2 and 3 elements' }
1991
+ end
1992
+ ```
1993
+
1994
+ #### `all_or_none_of`
1995
+
1996
+ ```ruby
1997
+ params do
1998
+ optional :beer
1999
+ optional :wine
2000
+ optional :juice
2001
+ all_or_none_of :beer, :wine, :juice, message: "all params are required or none is required"
2002
+ end
2003
+ ```
2004
+
2005
+ #### `mutually_exclusive`
2006
+
2007
+ ```ruby
2008
+ params do
2009
+ optional :beer
2010
+ optional :wine
2011
+ optional :juice
2012
+ mutually_exclusive :beer, :wine, :juice, message: "are mutually exclusive cannot pass both params"
2013
+ end
2014
+ ```
2015
+
2016
+ #### `exactly_one_of`
2017
+
2018
+ ```ruby
2019
+ params do
2020
+ optional :beer
2021
+ optional :wine
2022
+ optional :juice
2023
+ exactly_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" }
2024
+ end
2025
+ ```
2026
+
2027
+ #### `at_least_one_of`
2028
+
2029
+ ```ruby
2030
+ params do
2031
+ optional :beer
2032
+ optional :wine
2033
+ optional :juice
2034
+ at_least_one_of :beer, :wine, :juice, message: "are missing, please specify at least one param"
2035
+ end
2036
+ ```
2037
+
2038
+ #### `Coerce`
2039
+
2040
+ ```ruby
2041
+ params do
2042
+ requires :int, type: { value: Integer, message: "type cast is invalid" }
2043
+ end
2044
+ ```
2045
+
2046
+ #### `With Lambdas`
2047
+
2048
+ ```ruby
2049
+ params do
2050
+ requires :name, values: { value: -> { (1..10).to_a }, message: 'not in range from 1 to 10' }
2051
+ end
2052
+ ```
2053
+
2054
+ #### `Pass symbols for i18n translations`
2055
+
2056
+ You can pass a symbol if you want i18n translations for your custom validation messages.
2057
+
2058
+ ```ruby
2059
+ params do
2060
+ requires :name, message: :name_required
2061
+ end
2062
+ ```
2063
+ ```ruby
2064
+ # en.yml
2065
+
2066
+ en:
2067
+ grape:
2068
+ errors:
2069
+ format: ! '%{attributes} %{message}'
2070
+ messages:
2071
+ name_required: 'must be present'
2072
+ ```
2073
+
2074
+ #### Overriding Attribute Names
2075
+
2076
+ You can also override attribute names.
2077
+
2078
+ ```ruby
2079
+ # en.yml
2080
+
2081
+ en:
2082
+ grape:
2083
+ errors:
2084
+ format: ! '%{attributes} %{message}'
2085
+ messages:
2086
+ name_required: 'must be present'
2087
+ attributes:
2088
+ name: 'Oops! Name'
2089
+ ```
2090
+ Will produce 'Oops! Name must be present'
2091
+
2092
+ #### With Default
2093
+
2094
+ You cannot set a custom message option for Default as it requires interpolation `%{option1}: %{value1} is incompatible with %{option2}: %{value2}`. You can change the default error message for Default by changing the `incompatible_option_values` message key inside [en.yml](lib/grape/locale/en.yml)
2095
+
2096
+ ```ruby
2097
+ params do
2098
+ requires :name, values: { value: -> { (1..10).to_a }, message: 'not in range from 1 to 10' }, default: 5
2099
+ end
2100
+ ```
2101
+
2102
+ ### Using `dry-validation` or `dry-schema`
2103
+
2104
+ As an alternative to the `params` DSL described above, you can use a schema or `dry-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 add `dry-validation` or `dry-schema` to your `Gemfile`.
2105
+
2106
+ Then call `contract` with a contract or schema defined previously:
2107
+
2108
+ ```rb
2109
+ CreateOrdersSchema = Dry::Schema.Params do
2110
+ required(:orders).array(:hash) do
2111
+ required(:name).filled(:string)
2112
+ optional(:volume).maybe(:integer, lt?: 9)
2113
+ end
2114
+ end
2115
+
2116
+ # ...
2117
+
2118
+ contract CreateOrdersSchema
2119
+ ```
2120
+
2121
+ or with a block, using the [schema definition syntax](https://dry-rb.org/gems/dry-schema/1.13/#quick-start):
2122
+
2123
+ ```rb
2124
+ contract do
2125
+ required(:orders).array(:hash) do
2126
+ required(:name).filled(:string)
2127
+ optional(:volume).maybe(:integer, lt?: 9)
2128
+ end
2129
+ end
2130
+ ```
2131
+
2132
+ 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.
2133
+
2134
+ The `params` and `contract` declarations can also be used together in the same API, e.g. to describe different parts of a nested namespace for an endpoint.
2135
+
2136
+ ## Headers
2137
+
2138
+ ### Request
2139
+ Request headers are available through the `headers` helper or from `env` in their original form.
2140
+
2141
+ ```ruby
2142
+ get do
2143
+ error!('Unauthorized', 401) unless headers['Secret-Password'] == 'swordfish'
2144
+ end
2145
+ ```
2146
+
2147
+ ```ruby
2148
+ get do
2149
+ error!('Unauthorized', 401) unless env['HTTP_SECRET_PASSWORD'] == 'swordfish'
2150
+ end
2151
+ ```
2152
+
2153
+ #### Header Case Handling
2154
+
2155
+ The above example may have been requested as follows:
2156
+
2157
+ ``` shell
2158
+ curl -H "secret_PassWord: swordfish" ...
2159
+ ```
2160
+
2161
+ The header name will have been normalized for you.
2162
+
2163
+ - In the `header` helper names will be coerced into a downcased kebab case as `secret-password` if using Rack 3.
2164
+ - In the `header` helper names will be coerced into a capitalized kebab case as `Secret-PassWord` if using Rack < 3.
2165
+ - In the `env` collection they appear in all uppercase, in snake case, and prefixed with 'HTTP_' as `HTTP_SECRET_PASSWORD`
2166
+
2167
+ The header name will have been normalized per HTTP standards defined in [RFC2616 Section 4.2](https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2) regardless of what is being sent by a client.
2168
+
2169
+ ### Response
2170
+
2171
+ You can set a response header with `header` inside an API.
2172
+
2173
+ ```ruby
2174
+ header 'X-Robots-Tag', 'noindex'
2175
+ ```
2176
+
2177
+ When raising `error!`, pass additional headers as arguments. Additional headers will be merged with headers set before `error!` call.
2178
+
2179
+ ```ruby
2180
+ error! 'Unauthorized', 401, 'X-Error-Detail' => 'Invalid token.'
2181
+ ```
2182
+
2183
+ ## Routes
2184
+
2185
+ To define routes you can use the `route` method or the shorthands for the HTTP verbs. To define a route that accepts any route set to `:any`.
2186
+ Parts of the path that are denoted with a colon will be interpreted as route parameters.
2187
+
2188
+ ```ruby
2189
+ route :get, 'status' do
2190
+ end
2191
+
2192
+ # is the same as
2193
+
2194
+ get 'status' do
2195
+ end
2196
+
2197
+ # is the same as
2198
+
2199
+ get :status do
2200
+ end
2201
+
2202
+ # is NOT the same as
2203
+
2204
+ get ':status' do # this makes params[:status] available
2205
+ end
2206
+
2207
+ # This will make both params[:status_id] and params[:id] available
2208
+
2209
+ get 'statuses/:status_id/reviews/:id' do
2210
+ end
2211
+ ```
2212
+
2213
+ To declare a namespace that prefixes all routes within, use the `namespace` method. `group`, `resource`, `resources` and `segment` are aliases to this method. Any endpoints within will share their parent context as well as any configuration done in the namespace context.
2214
+
2215
+ The `route_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.
2216
+
2217
+ ```ruby
2218
+ route_param :id, type: Integer do
2219
+ get 'status' do
2220
+ end
2221
+ end
2222
+
2223
+ # is the same as
2224
+
2225
+ namespace ':id' do
2226
+ params do
2227
+ requires :id, type: Integer
2228
+ end
2229
+
2230
+ get 'status' do
2231
+ end
2232
+ end
2233
+ ```
2234
+
2235
+ 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.
2236
+
2237
+ ```ruby
2238
+ get ':id', requirements: { id: /[0-9]*/ } do
2239
+ Status.find(params[:id])
2240
+ end
2241
+
2242
+ namespace :outer, requirements: { id: /[0-9]*/ } do
2243
+ get :id do
2244
+ end
2245
+
2246
+ get ':id/edit' do
2247
+ end
2248
+ end
2249
+ ```
2250
+
2251
+ ## Helpers
2252
+
2253
+ You can define helper methods that your endpoints can use with the `helpers` macro by either giving a block or an array of modules.
2254
+
2255
+ ```ruby
2256
+ module StatusHelpers
2257
+ def user_info(user)
2258
+ "#{user} has statused #{user.statuses} status(s)"
2259
+ end
2260
+ end
2261
+
2262
+ module HttpCodesHelpers
2263
+ def unauthorized
2264
+ 401
2265
+ end
2266
+ end
2267
+
2268
+ class API < Grape::API
2269
+ # define helpers with a block
2270
+ helpers do
2271
+ def current_user
2272
+ User.find(params[:user_id])
2273
+ end
2274
+ end
2275
+
2276
+ # or mix in an array of modules
2277
+ helpers StatusHelpers, HttpCodesHelpers
2278
+
2279
+ before do
2280
+ error!('Access Denied', unauthorized) unless current_user
2281
+ end
2282
+
2283
+ get 'info' do
2284
+ # helpers available in your endpoint and filters
2285
+ user_info(current_user)
2286
+ end
2287
+ end
2288
+ ```
2289
+
2290
+ You can define reusable `params` using `helpers`.
2291
+
2292
+ ```ruby
2293
+ class API < Grape::API
2294
+ helpers do
2295
+ params :pagination do
2296
+ optional :page, type: Integer
2297
+ optional :per_page, type: Integer
2298
+ end
2299
+ end
2300
+
2301
+ desc 'Get collection'
2302
+ params do
2303
+ use :pagination # aliases: includes, use_scope
2304
+ end
2305
+ get do
2306
+ Collection.page(params[:page]).per(params[:per_page])
2307
+ end
2308
+ end
2309
+ ```
2310
+
2311
+ You can also define reusable `params` using shared helpers.
2312
+
2313
+ ```ruby
2314
+ module SharedParams
2315
+ extend Grape::API::Helpers
2316
+
2317
+ params :period do
2318
+ optional :start_date
2319
+ optional :end_date
2320
+ end
2321
+
2322
+ params :pagination do
2323
+ optional :page, type: Integer
2324
+ optional :per_page, type: Integer
2325
+ end
2326
+ end
2327
+
2328
+ class API < Grape::API
2329
+ helpers SharedParams
2330
+
2331
+ desc 'Get collection.'
2332
+ params do
2333
+ use :period, :pagination
2334
+ end
2335
+
2336
+ get do
2337
+ Collection
2338
+ .from(params[:start_date])
2339
+ .to(params[:end_date])
2340
+ .page(params[:page])
2341
+ .per(params[:per_page])
2342
+ end
2343
+ end
2344
+ ```
2345
+
2346
+ Helpers support blocks that can help set default values. The following API can return a collection sorted by `id` or `created_at` in `asc` or `desc` order.
2347
+
2348
+ ```ruby
2349
+ module SharedParams
2350
+ extend Grape::API::Helpers
2351
+
2352
+ params :order do |options|
2353
+ optional :order_by, type: Symbol, values: options[:order_by], default: options[:default_order_by]
2354
+ optional :order, type: Symbol, values: %i(asc desc), default: options[:default_order]
2355
+ end
2356
+ end
2357
+
2358
+ class API < Grape::API
2359
+ helpers SharedParams
2360
+
2361
+ desc 'Get a sorted collection.'
2362
+ params do
2363
+ use :order, order_by: %i(id created_at), default_order_by: :created_at, default_order: :asc
2364
+ end
2365
+
2366
+ get do
2367
+ Collection.send(params[:order], params[:order_by])
2368
+ end
2369
+ end
2370
+ ```
2371
+
2372
+ ## Path Helpers
2373
+
2374
+ If you need methods for generating paths inside your endpoints, please see the [grape-route-helpers](https://github.com/reprah/grape-route-helpers) gem.
2375
+
2376
+ ## Parameter Documentation
2377
+
2378
+ You can attach additional documentation to `params` using a `documentation` hash.
2379
+
2380
+ ```ruby
2381
+ params do
2382
+ optional :first_name, type: String, documentation: { example: 'Jim' }
2383
+ requires :last_name, type: String, documentation: { example: 'Smith' }
2384
+ end
2385
+ ```
2386
+
2387
+ If documentation isn't needed (for instance, it is an internal API), documentation can be disabled.
2388
+
2389
+ ```ruby
2390
+ class API < Grape::API
2391
+ do_not_document!
2392
+
2393
+ # endpoints...
2394
+ end
2395
+ ```
2396
+
2397
+ In this case, Grape won't create objects related to documentation which are retained in RAM forever.
2398
+
2399
+ ## Cookies
2400
+
2401
+ You can set, get and delete your cookies very simply using `cookies` method.
2402
+
2403
+ ```ruby
2404
+ class API < Grape::API
2405
+ get 'status_count' do
2406
+ cookies[:status_count] ||= 0
2407
+ cookies[:status_count] += 1
2408
+ { status_count: cookies[:status_count] }
2409
+ end
2410
+
2411
+ delete 'status_count' do
2412
+ { status_count: cookies.delete(:status_count) }
2413
+ end
2414
+ end
2415
+ ```
2416
+
2417
+ Use a hash-based syntax to set more than one value.
2418
+
2419
+ ```ruby
2420
+ cookies[:status_count] = {
2421
+ value: 0,
2422
+ expires: Time.tomorrow,
2423
+ domain: '.twitter.com',
2424
+ path: '/'
2425
+ }
2426
+
2427
+ cookies[:status_count][:value] +=1
2428
+ ```
2429
+
2430
+ Delete a cookie with `delete`.
2431
+
2432
+ ```ruby
2433
+ cookies.delete :status_count
2434
+ ```
2435
+
2436
+ Specify an optional path.
2437
+
2438
+ ```ruby
2439
+ cookies.delete :status_count, path: '/'
2440
+ ```
2441
+
2442
+ ## HTTP Status Code
2443
+
2444
+ By default Grape returns a 201 for `POST`-Requests, 204 for `DELETE`-Requests that don't return any content, and 200 status code for all other Requests.
2445
+ You can use `status` to query and set the actual HTTP Status Code
2446
+
2447
+ ```ruby
2448
+ post do
2449
+ status 202
2450
+
2451
+ if status == 200
2452
+ # do some thing
2453
+ end
2454
+ end
2455
+ ```
2456
+
2457
+ You can also use one of status codes symbols that are provided by [Rack utils](http://www.rubydoc.info/github/rack/rack/Rack/Utils#HTTP_STATUS_CODES-constant)
2458
+
2459
+ ```ruby
2460
+ post do
2461
+ status :no_content
2462
+ end
2463
+ ```
2464
+
2465
+ ## Redirecting
2466
+
2467
+ You can redirect to a new url temporarily (302) or permanently (301).
2468
+
2469
+ ```ruby
2470
+ redirect '/statuses'
2471
+ ```
2472
+
2473
+ ```ruby
2474
+ redirect '/statuses', permanent: true
2475
+ ```
2476
+
2477
+ ## Recognizing Path
2478
+
2479
+ You can recognize the endpoint matched with given path.
2480
+
2481
+ This API returns an instance of `Grape::Endpoint`.
2482
+
2483
+ ```ruby
2484
+ class API < Grape::API
2485
+ get '/statuses' do
2486
+ end
2487
+ end
2488
+
2489
+ API.recognize_path '/statuses'
2490
+ ```
2491
+
2492
+ Since version `2.1.0`, the `recognize_path` method takes into account the parameters type to determine which endpoint should match with given path.
2493
+
2494
+ ```ruby
2495
+ class Books < Grape::API
2496
+ resource :books do
2497
+ route_param :id, type: Integer do
2498
+ # GET /books/:id
2499
+ get do
2500
+ #...
2501
+ end
2502
+ end
2503
+
2504
+ resource :share do
2505
+ # POST /books/share
2506
+ post do
2507
+ # ....
2508
+ end
2509
+ end
2510
+ end
2511
+ end
2512
+
2513
+ API.recognize_path '/books/1' # => /books/:id
2514
+ API.recognize_path '/books/share' # => /books/share
2515
+ API.recognize_path '/books/other' # => nil
2516
+ ```
2517
+
2518
+
2519
+ ## Allowed Methods
2520
+
2521
+ When you add a `GET` route for a resource, a route for the `HEAD` method will also be added automatically. You can disable this behavior with `do_not_route_head!`.
2522
+
2523
+ ``` ruby
2524
+ class API < Grape::API
2525
+ do_not_route_head!
2526
+
2527
+ get '/example' do
2528
+ # only responds to GET
2529
+ end
2530
+ end
2531
+ ```
2532
+
2533
+ When you add a route for a resource, a route for the `OPTIONS` method will also be added. The response to an OPTIONS request will include an "Allow" header listing the supported methods. If the resource has `before` and `after` callbacks they will be executed, but no other callbacks will run.
2534
+
2535
+ ```ruby
2536
+ class API < Grape::API
2537
+ get '/rt_count' do
2538
+ { rt_count: current_user.rt_count }
2539
+ end
2540
+
2541
+ params do
2542
+ requires :value, type: Integer, desc: 'Value to add to the rt count.'
2543
+ end
2544
+ put '/rt_count' do
2545
+ current_user.rt_count += params[:value].to_i
2546
+ { rt_count: current_user.rt_count }
2547
+ end
2548
+ end
2549
+ ```
2550
+
2551
+ ``` shell
2552
+ curl -v -X OPTIONS http://localhost:3000/rt_count
2553
+
2554
+ > OPTIONS /rt_count HTTP/1.1
2555
+ >
2556
+ < HTTP/1.1 204 No Content
2557
+ < Allow: OPTIONS, GET, PUT
2558
+ ```
2559
+
2560
+ You can disable this behavior with `do_not_route_options!`.
2561
+
2562
+ If a request for a resource is made with an unsupported HTTP method, an HTTP 405 (Method Not Allowed) response will be returned. If the resource has `before` callbacks they will be executed, but no other callbacks will run.
2563
+
2564
+ ``` shell
2565
+ curl -X DELETE -v http://localhost:3000/rt_count/
2566
+
2567
+ > DELETE /rt_count/ HTTP/1.1
2568
+ > Host: localhost:3000
2569
+ >
2570
+ < HTTP/1.1 405 Method Not Allowed
2571
+ < Allow: OPTIONS, GET, PUT
2572
+ ```
2573
+
2574
+ ## Raising Exceptions
2575
+
2576
+ You can abort the execution of an API method by raising errors with `error!`.
2577
+
2578
+ ```ruby
2579
+ error! 'Access Denied', 401
2580
+ ```
2581
+
2582
+ Anything that responds to `#to_s` can be given as a first argument to `error!`.
2583
+
2584
+ ```ruby
2585
+ error! :not_found, 404
2586
+ ```
2587
+
2588
+ You can also return JSON formatted objects by raising error! and passing a hash instead of a message.
2589
+
2590
+ ```ruby
2591
+ error!({ error: 'unexpected error', detail: 'missing widget' }, 500)
2592
+ ```
2593
+
2594
+ You can set additional headers for the response. They will be merged with headers set before `error!` call.
2595
+
2596
+ ```ruby
2597
+ error!('Something went wrong', 500, 'X-Error-Detail' => 'Invalid token.')
2598
+ ```
2599
+
2600
+ You can present documented errors with a Grape entity using the the [grape-entity](https://github.com/ruby-grape/grape-entity) gem.
2601
+
2602
+ ```ruby
2603
+ module API
2604
+ class Error < Grape::Entity
2605
+ expose :code
2606
+ expose :message
2607
+ end
2608
+ end
2609
+ ```
2610
+
2611
+ The following example specifies the entity to use in the `http_codes` definition.
2612
+
2613
+ ```ruby
2614
+ desc 'My Route' do
2615
+ failure [[408, 'Unauthorized', API::Error]]
2616
+ end
2617
+ error!({ message: 'Unauthorized' }, 408)
2618
+ ```
2619
+
2620
+ The following example specifies the presented entity explicitly in the error message.
2621
+
2622
+ ```ruby
2623
+ desc 'My Route' do
2624
+ failure [[408, 'Unauthorized']]
2625
+ end
2626
+ error!({ message: 'Unauthorized', with: API::Error }, 408)
2627
+ ```
2628
+
2629
+ ### Default Error HTTP Status Code
2630
+
2631
+ By default Grape returns a 500 status code from `error!`. You can change this with `default_error_status`.
2632
+
2633
+ ``` ruby
2634
+ class API < Grape::API
2635
+ default_error_status 400
2636
+ get '/example' do
2637
+ error! 'This should have http status code 400'
2638
+ end
2639
+ end
2640
+ ```
2641
+
2642
+ ### Handling 404
2643
+
2644
+ For Grape to handle all the 404s for your API, it can be useful to use a catch-all.
2645
+ In its simplest form, it can be like:
2646
+
2647
+ ```ruby
2648
+ route :any, '*path' do
2649
+ error! # or something else
2650
+ end
2651
+ ```
2652
+
2653
+ It is very crucial to __define this endpoint at the very end of your API__, as it literally accepts every request.
2654
+
2655
+ ## Exception Handling
2656
+
2657
+ Grape can be told to rescue all `StandardError` exceptions and return them in the API format.
2658
+
2659
+ ```ruby
2660
+ class Twitter::API < Grape::API
2661
+ rescue_from :all
2662
+ end
2663
+ ```
2664
+
2665
+ This mimics [default `rescue` behaviour](https://ruby-doc.org/core/StandardError.html) when an exception type is not provided.
2666
+ Any other exception should be rescued explicitly, see [below](#exceptions-that-should-be-rescued-explicitly).
2667
+
2668
+ Grape can also rescue from all exceptions and still use the built-in exception handing.
2669
+ This will give the same behavior as `rescue_from :all` with the addition that Grape will use the exception handling defined by all Exception classes that inherit `Grape::Exceptions::Base`.
2670
+
2671
+ 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.
2672
+
2673
+ ```ruby
2674
+ class Twitter::API < Grape::API
2675
+ rescue_from :grape_exceptions
2676
+ end
2677
+ ```
2678
+
2679
+ 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 to `rescue_from :grape_exceptions`.
2680
+
2681
+ ```ruby
2682
+ rescue_from :grape_exceptions do |e|
2683
+ error!(e, e.status)
2684
+ end
2685
+ ```
2686
+
2687
+ You can also rescue specific exceptions.
2688
+
2689
+ ```ruby
2690
+ class Twitter::API < Grape::API
2691
+ rescue_from ArgumentError, UserDefinedError
2692
+ end
2693
+ ```
2694
+
2695
+ In this case ```UserDefinedError``` must be inherited from ```StandardError```.
2696
+
2697
+ 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.
2698
+
2699
+ ```ruby
2700
+ class Twitter::API < Grape::API
2701
+ rescue_from Grape::Exceptions::ValidationErrors do |e|
2702
+ error!(e, 400)
2703
+ end
2704
+
2705
+ rescue_from :all
2706
+ end
2707
+ ```
2708
+
2709
+ The error format will match the request format. See "Content-Types" below.
2710
+
2711
+ Custom error formatters for existing and additional types can be defined with a proc.
2712
+
2713
+ ```ruby
2714
+ class Twitter::API < Grape::API
2715
+ error_formatter :txt, ->(message, backtrace, options, env, original_exception) {
2716
+ "error: #{message} from #{backtrace}"
2717
+ }
2718
+ end
2719
+ ```
2720
+
2721
+ You can also use a module or class.
2722
+
2723
+ ```ruby
2724
+ module CustomFormatter
2725
+ def self.call(message, backtrace, options, env, original_exception)
2726
+ { message: message, backtrace: backtrace }
2727
+ end
2728
+ end
2729
+
2730
+ class Twitter::API < Grape::API
2731
+ error_formatter :custom, CustomFormatter
2732
+ end
2733
+ ```
2734
+
2735
+ You can rescue all exceptions with a code block. The `error!` wrapper automatically sets the default error code and content-type.
2736
+
2737
+ ```ruby
2738
+ class Twitter::API < Grape::API
2739
+ rescue_from :all do |e|
2740
+ error!("rescued from #{e.class.name}")
2741
+ end
2742
+ end
2743
+ ```
2744
+
2745
+ Optionally, you can set the format, status code and headers.
2746
+
2747
+ ```ruby
2748
+ class Twitter::API < Grape::API
2749
+ format :json
2750
+ rescue_from :all do |e|
2751
+ error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
2752
+ end
2753
+ end
2754
+ ```
2755
+
2756
+ You can also rescue all exceptions with a code block and handle the Rack response at the lowest level.
2757
+
2758
+ ```ruby
2759
+ class Twitter::API < Grape::API
2760
+ rescue_from :all do |e|
2761
+ Rack::Response.new([ e.message ], 500, { 'Content-type' => 'text/error' })
2762
+ end
2763
+ end
2764
+ ```
2765
+
2766
+ Or rescue specific exceptions.
2767
+
2768
+ ```ruby
2769
+ class Twitter::API < Grape::API
2770
+ rescue_from ArgumentError do |e|
2771
+ error!("ArgumentError: #{e.message}")
2772
+ end
2773
+
2774
+ rescue_from NoMethodError do |e|
2775
+ error!("NoMethodError: #{e.message}")
2776
+ end
2777
+ end
2778
+ ```
2779
+
2780
+ By default, `rescue_from` will rescue the exceptions listed and all their subclasses.
2781
+
2782
+ Assume you have the following exception classes defined.
2783
+
2784
+ ```ruby
2785
+ module APIErrors
2786
+ class ParentError < StandardError; end
2787
+ class ChildError < ParentError; end
2788
+ end
2789
+ ```
2790
+
2791
+ Then the following `rescue_from` clause will rescue exceptions of type `APIErrors::ParentError` and its subclasses (in this case `APIErrors::ChildError`).
2792
+
2793
+ ```ruby
2794
+ rescue_from APIErrors::ParentError do |e|
2795
+ error!({
2796
+ error: "#{e.class} error",
2797
+ message: e.message
2798
+ }, e.status)
2799
+ end
2800
+ ```
2801
+
2802
+ To only rescue the base exception class, set `rescue_subclasses: false`.
2803
+ The code below will rescue exceptions of type `RuntimeError` but _not_ its subclasses.
2804
+
2805
+ ```ruby
2806
+ rescue_from RuntimeError, rescue_subclasses: false do |e|
2807
+ error!({
2808
+ status: e.status,
2809
+ message: e.message,
2810
+ errors: e.errors
2811
+ }, e.status)
2812
+ end
2813
+ ```
2814
+
2815
+ Helpers are also available inside `rescue_from`.
2816
+
2817
+ ```ruby
2818
+ class Twitter::API < Grape::API
2819
+ format :json
483
2820
  helpers do
484
- def current_user
485
- User.find(params[:user_id])
2821
+ def server_error!
2822
+ error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
2823
+ end
2824
+ end
2825
+
2826
+ rescue_from :all do |e|
2827
+ server_error!
2828
+ end
2829
+ end
2830
+ ```
2831
+
2832
+ The `rescue_from` handler must return a `Rack::Response` object, call `error!`, or raise an exception (either the original exception or another custom one). The exception raised in `rescue_from` will be handled outside Grape. For example, if you mount Grape in Rails, the exception will be handle by [Rails Action Controller](https://guides.rubyonrails.org/action_controller_overview.html#rescue).
2833
+
2834
+ Alternately, use the `with` option in `rescue_from` to specify a method or a `proc`.
2835
+
2836
+ ```ruby
2837
+ class Twitter::API < Grape::API
2838
+ format :json
2839
+ helpers do
2840
+ def server_error!
2841
+ error!({ error: 'Server error.' }, 500, { 'Content-Type' => 'text/error' })
2842
+ end
2843
+ end
2844
+
2845
+ rescue_from :all, with: :server_error!
2846
+ rescue_from ArgumentError, with: -> { Rack::Response.new('rescued with a method', 400) }
2847
+ end
2848
+ ```
2849
+
2850
+ Inside the `rescue_from` block, the environment of the original controller method(`.self` receiver) is accessible through the `#context` method.
2851
+
2852
+ ```ruby
2853
+ class Twitter::API < Grape::API
2854
+ rescue_from :all do |e|
2855
+ user_id = context.params[:user_id]
2856
+ error!("error for #{user_id}")
2857
+ end
2858
+ end
2859
+ ```
2860
+
2861
+ #### Rescuing exceptions inside namespaces
2862
+
2863
+ You could put `rescue_from` clauses inside a namespace and they will take precedence over ones
2864
+ defined in the root scope:
2865
+
2866
+ ```ruby
2867
+ class Twitter::API < Grape::API
2868
+ rescue_from ArgumentError do |e|
2869
+ error!("outer")
2870
+ end
2871
+
2872
+ namespace :statuses do
2873
+ rescue_from ArgumentError do |e|
2874
+ error!("inner")
2875
+ end
2876
+ get do
2877
+ raise ArgumentError.new
486
2878
  end
487
2879
  end
2880
+ end
2881
+ ```
488
2882
 
489
- # or mix in a module
490
- helpers StatusHelpers
2883
+ Here `'inner'` will be result of handling occurred `ArgumentError`.
491
2884
 
492
- get 'info' do
493
- # helpers available in your endpoint and filters
494
- user_info(current_user)
2885
+ #### Unrescuable Exceptions
2886
+
2887
+ `Grape::Exceptions::InvalidVersionHeader`, which is raised when the version in the request header doesn't match the currently evaluated version for the endpoint, will _never_ be rescued from a `rescue_from` block (even a `rescue_from :all`) This is because Grape relies on Rack to catch that error and try the next versioned-route for cases where there exist identical Grape endpoints with different versions.
2888
+
2889
+ #### Exceptions that should be rescued explicitly
2890
+
2891
+ Any exception that is not subclass of `StandardError` should be rescued explicitly.
2892
+ Usually it is not a case for an application logic as such errors point to problems in Ruby runtime.
2893
+ This is following [standard recommendations for exceptions handling](https://ruby-doc.org/core/Exception.html).
2894
+
2895
+ ## Logging
2896
+
2897
+ `Grape::API` provides a `logger` method which by default will return an instance of the `Logger` class from Ruby's standard library.
2898
+
2899
+ To log messages from within an endpoint, you need to define a helper to make the logger available in the endpoint context.
2900
+
2901
+ ```ruby
2902
+ class API < Grape::API
2903
+ helpers do
2904
+ def logger
2905
+ API.logger
2906
+ end
2907
+ end
2908
+ post '/statuses' do
2909
+ logger.info "#{current_user} has statused"
495
2910
  end
496
2911
  end
497
2912
  ```
498
2913
 
499
- ## Cookies
2914
+ To change the logger level.
500
2915
 
501
- You can set, get and delete your cookies very simply using `cookies` method.
2916
+ ```ruby
2917
+ class API < Grape::API
2918
+ self.logger.level = Logger::INFO
2919
+ end
2920
+ ```
2921
+
2922
+ You can also set your own logger.
502
2923
 
503
2924
  ```ruby
2925
+ class MyLogger
2926
+ def warning(message)
2927
+ puts "this is a warning: #{message}"
2928
+ end
2929
+ end
2930
+
504
2931
  class API < Grape::API
2932
+ logger MyLogger.new
2933
+ helpers do
2934
+ def logger
2935
+ API.logger
2936
+ end
2937
+ end
2938
+ get '/statuses' do
2939
+ logger.warning "#{current_user} has statused"
2940
+ end
2941
+ end
2942
+ ```
505
2943
 
506
- get 'status_count' do
507
- cookies[:status_count] ||= 0
508
- cookies[:status_count] += 1
509
- { status_count: cookies[:status_count] }
2944
+ For similar to Rails request logging try the [grape_logging](https://github.com/aserafin/grape_logging) or [grape-middleware-logger](https://github.com/ridiculous/grape-middleware-logger) gems.
2945
+
2946
+ ## API Formats
2947
+
2948
+ Your API can declare which content-types to support by using `content_type`. If you do not specify any, Grape will support _XML_, _JSON_, _BINARY_, and _TXT_ content-types. The default format is `:txt`; you can change this with `default_format`. Essentially, the two APIs below are equivalent.
2949
+
2950
+ ```ruby
2951
+ class Twitter::API < Grape::API
2952
+ # no content_type declarations, so Grape uses the defaults
2953
+ end
2954
+
2955
+ class Twitter::API < Grape::API
2956
+ # the following declarations are equivalent to the defaults
2957
+
2958
+ content_type :xml, 'application/xml'
2959
+ content_type :json, 'application/json'
2960
+ content_type :binary, 'application/octet-stream'
2961
+ content_type :txt, 'text/plain'
2962
+
2963
+ default_format :txt
2964
+ end
2965
+ ```
2966
+
2967
+ If you declare any `content_type` whatsoever, the Grape defaults will be overridden. For example, the following API will only support the `:xml` and `:rss` content-types, but not `:txt`, `:json`, or `:binary`. Importantly, this means the `:txt` default format is not supported! So, make sure to set a new `default_format`.
2968
+
2969
+ ```ruby
2970
+ class Twitter::API < Grape::API
2971
+ content_type :xml, 'application/xml'
2972
+ content_type :rss, 'application/xml+rss'
2973
+
2974
+ default_format :xml
2975
+ end
2976
+ ```
2977
+
2978
+ Serialization takes place automatically. For example, you do not have to call `to_json` in each JSON API endpoint implementation. The response format (and thus the automatic serialization) is determined in the following order:
2979
+ * Use the file extension, if specified. If the file is .json, choose the JSON format.
2980
+ * Use the value of the `format` parameter in the query string, if specified.
2981
+ * Use the format set by the `format` option, if specified.
2982
+ * Attempt to find an acceptable format from the `Accept` header.
2983
+ * Use the default format, if specified by the `default_format` option.
2984
+ * Default to `:txt`.
2985
+
2986
+ For example, consider the following API.
2987
+
2988
+ ```ruby
2989
+ class MultipleFormatAPI < Grape::API
2990
+ content_type :xml, 'application/xml'
2991
+ content_type :json, 'application/json'
2992
+
2993
+ default_format :json
2994
+
2995
+ get :hello do
2996
+ { hello: 'world' }
510
2997
  end
2998
+ end
2999
+ ```
511
3000
 
512
- delete 'status_count' do
513
- { status_count: cookies.delete(:status_count) }
3001
+ * `GET /hello` (with an `Accept: */*` header) does not have an extension or a `format` parameter, so it will respond with JSON (the default format).
3002
+ * `GET /hello.xml` has a recognized extension, so it will respond with XML.
3003
+ * `GET /hello?format=xml` has a recognized `format` parameter, so it will respond with XML.
3004
+ * `GET /hello.xml?format=json` has a recognized extension (which takes precedence over the `format` parameter), so it will respond with XML.
3005
+ * `GET /hello.xls` (with an `Accept: */*` header) has an extension, but that extension is not recognized, so it will respond with JSON (the default format).
3006
+ * `GET /hello.xls` with an `Accept: application/xml` header has an unrecognized extension, but the `Accept` header corresponds to a recognized format, so it will respond with XML.
3007
+ * `GET /hello.xls` with an `Accept: text/plain` header has an unrecognized extension *and* an unrecognized `Accept` header, so it will respond with JSON (the default format).
3008
+
3009
+ You can override this process explicitly by calling `api_format` in the API itself.
3010
+ For example, the following API will let you upload arbitrary files and return their contents as an attachment with the correct MIME type.
3011
+
3012
+ ```ruby
3013
+ class Twitter::API < Grape::API
3014
+ post 'attachment' do
3015
+ filename = params[:file][:filename]
3016
+ content_type MIME::Types.type_for(filename)[0].to_s
3017
+ api_format :binary # there's no formatter for :binary, data will be returned "as is"
3018
+ header 'Content-Disposition', "attachment; filename*=UTF-8''#{CGI.escape(filename)}"
3019
+ params[:file][:tempfile].read
514
3020
  end
3021
+ end
3022
+ ```
3023
+
3024
+ You can have your API only respond to a single format with `format`. If you use this, the API will **not** respond to file extensions other than specified in `format`. For example, consider the following API.
3025
+
3026
+ ```ruby
3027
+ class SingleFormatAPI < Grape::API
3028
+ format :json
515
3029
 
3030
+ get :hello do
3031
+ { hello: 'world' }
3032
+ end
516
3033
  end
517
3034
  ```
518
3035
 
519
- Use a hash-based syntax to set more than one value.
3036
+ * `GET /hello` will respond with JSON.
3037
+ * `GET /hello.json` will respond with JSON.
3038
+ * `GET /hello.xml`, `GET /hello.foobar`, or *any* other extension will respond with an HTTP 404 error code.
3039
+ * `GET /hello?format=xml` will respond with an HTTP 406 error code, because the XML format specified by the request parameter is not supported.
3040
+ * `GET /hello` with an `Accept: application/xml` header will still respond with JSON, since it could not negotiate a recognized content-type from the headers and JSON is the effective default.
3041
+
3042
+ The formats apply to parsing, too. The following API will only respond to the JSON content-type and will not parse any other input than `application/json`, `application/x-www-form-urlencoded`, `multipart/form-data`, `multipart/related` and `multipart/mixed`. All other requests will fail with an HTTP 406 error code.
520
3043
 
521
3044
  ```ruby
522
- cookies[:status_count] = {
523
- value: 0,
524
- expires: Time.tomorrow,
525
- domain: '.twitter.com',
526
- path: '/'
527
- }
3045
+ class Twitter::API < Grape::API
3046
+ format :json
3047
+ end
3048
+ ```
528
3049
 
529
- cookies[:status_count][:value] +=1
3050
+ When the content-type is omitted, Grape will return a 406 error code unless `default_format` is specified.
3051
+ The following API will try to parse any data without a content-type using a JSON parser.
3052
+
3053
+ ```ruby
3054
+ class Twitter::API < Grape::API
3055
+ format :json
3056
+ default_format :json
3057
+ end
530
3058
  ```
531
3059
 
532
- Delete a cookie with `delete`.
3060
+ If you combine `format` with `rescue_from :all`, errors will be rendered using the same format.
3061
+ If you do not want this behavior, set the default error formatter with `default_error_formatter`.
533
3062
 
534
3063
  ```ruby
535
- cookies.delete :status_count
3064
+ class Twitter::API < Grape::API
3065
+ format :json
3066
+ content_type :txt, 'text/plain'
3067
+ default_error_formatter :txt
3068
+ end
536
3069
  ```
537
3070
 
538
- Specify an optional path.
3071
+ Custom formatters for existing and additional types can be defined with a proc.
539
3072
 
540
3073
  ```ruby
541
- cookies.delete :status_count, path: '/'
3074
+ class Twitter::API < Grape::API
3075
+ content_type :xls, 'application/vnd.ms-excel'
3076
+ formatter :xls, ->(object, env) { object.to_xls }
3077
+ end
542
3078
  ```
543
3079
 
544
- ## Redirecting
3080
+ You can also use a module or class.
545
3081
 
546
- You can redirect to a new url temporarily (302) or permanently (301).
3082
+ ```ruby
3083
+ module XlsFormatter
3084
+ def self.call(object, env)
3085
+ object.to_xls
3086
+ end
3087
+ end
3088
+
3089
+ class Twitter::API < Grape::API
3090
+ content_type :xls, 'application/vnd.ms-excel'
3091
+ formatter :xls, XlsFormatter
3092
+ end
3093
+ ```
3094
+
3095
+ Built-in formatters are the following.
3096
+
3097
+ * `:json`: use object's `to_json` when available, otherwise call `MultiJson.dump`
3098
+ * `:xml`: use object's `to_xml` when available, usually via `MultiXml`
3099
+ * `:txt`: use object's `to_txt` when available, otherwise `to_s`
3100
+ * `:serializable_hash`: use object's `serializable_hash` when available, otherwise fallback to `:json`
3101
+ * `:binary`: data will be returned "as is"
3102
+
3103
+ 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.
3104
+
3105
+ Response statuses that indicate no content as defined by [Rack](https://github.com/rack) [here](https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L567) will bypass serialization and the body entity - though there should be none - will not be modified.
3106
+
3107
+ ### JSONP
3108
+
3109
+ Grape supports JSONP via [Rack::JSONP](https://github.com/rack/rack-contrib), part of the [rack-contrib](https://github.com/rack/rack-contrib) gem. Add `rack-contrib` to your `Gemfile`.
547
3110
 
548
3111
  ```ruby
549
- redirect "/statuses"
3112
+ require 'rack/contrib'
3113
+
3114
+ class API < Grape::API
3115
+ use Rack::JSONP
3116
+ format :json
3117
+ get '/' do
3118
+ 'Hello World'
3119
+ end
3120
+ end
550
3121
  ```
551
3122
 
3123
+ ### CORS
3124
+
3125
+ Grape supports CORS via [Rack::CORS](https://github.com/cyu/rack-cors), part of the [rack-cors](https://github.com/cyu/rack-cors) gem. Add `rack-cors` to your `Gemfile`, then use the middleware in your config.ru file.
3126
+
552
3127
  ```ruby
553
- redirect "/statuses", permanent: true
3128
+ require 'rack/cors'
3129
+
3130
+ use Rack::Cors do
3131
+ allow do
3132
+ origins '*'
3133
+ resource '*', headers: :any, methods: :get
3134
+ end
3135
+ end
3136
+
3137
+ run Twitter::API
3138
+
554
3139
  ```
555
3140
 
556
- ## Allowed Methods
3141
+ ## Content-type
557
3142
 
558
- When you add a `GET` route for a resource, a route for the `HEAD`
559
- method will also be added automatically. You can disable this
560
- behavior with `do_not_route_head!`.
3143
+ Content-type is set by the formatter. You can override the content-type of the response at runtime by setting the `Content-Type` header.
561
3144
 
562
- ``` ruby
3145
+ ```ruby
563
3146
  class API < Grape::API
3147
+ get '/home_timeline_js' do
3148
+ content_type 'application/javascript'
3149
+ "var statuses = ...;"
3150
+ end
3151
+ end
3152
+ ```
564
3153
 
565
- do_not_route_head!
3154
+ ## API Data Formats
566
3155
 
567
- get '/example' do
568
- # only responds to GET
3156
+ Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters section above. It also supports custom data formats. You must declare additional content-types via `content_type` and optionally supply a parser via `parser` unless a parser is already available within Grape to enable a custom format. Such a parser can be a function or a class.
3157
+
3158
+ With a parser, parsed data is available "as-is" in `env['api.request.body']`.
3159
+ Without a parser, data is available "as-is" and in `env['api.request.input']`.
3160
+
3161
+ The following example is a trivial parser that will assign any input with the "text/custom" content-type to `:value`. The parameter will be available via `params[:value]` inside the API call.
3162
+
3163
+ ```ruby
3164
+ module CustomParser
3165
+ def self.call(object, env)
3166
+ { value: object.to_s }
3167
+ end
3168
+ end
3169
+ ```
3170
+
3171
+ ```ruby
3172
+ content_type :txt, 'text/plain'
3173
+ content_type :custom, 'text/custom'
3174
+ parser :custom, CustomParser
3175
+
3176
+ put 'value' do
3177
+ params[:value]
3178
+ end
3179
+ ```
3180
+
3181
+ You can invoke the above API as follows.
3182
+
3183
+ ```
3184
+ curl -X PUT -d 'data' 'http://localhost:9292/value' -H Content-Type:text/custom -v
3185
+ ```
3186
+
3187
+ You can disable parsing for a content-type with `nil`. For example, `parser :json, nil` will disable JSON parsing altogether. The request data is then available as-is in `env['api.request.body']`.
3188
+
3189
+ ## JSON and XML Processors
3190
+
3191
+ Grape uses `JSON` and `ActiveSupport::XmlMini` for JSON and XML parsing by default. It also detects and supports [multi_json](https://github.com/intridea/multi_json) and [multi_xml](https://github.com/sferik/multi_xml). Adding those gems to your Gemfile and requiring them will enable them and allow you to swap the JSON and XML back-ends.
3192
+
3193
+ ## RESTful Model Representations
3194
+
3195
+ Grape supports a range of ways to present your data with some help from a generic `present` method, which accepts two arguments: the object to be presented and the options associated with it. The options hash may include `:with`, which defines the entity to expose.
3196
+
3197
+ ### Grape Entities
3198
+
3199
+ Add the [grape-entity](https://github.com/ruby-grape/grape-entity) gem to your Gemfile.
3200
+ Please refer to the [grape-entity documentation](https://github.com/ruby-grape/grape-entity/blob/master/README.md)
3201
+ for more details.
3202
+
3203
+ The following example exposes statuses.
3204
+
3205
+ ```ruby
3206
+ module API
3207
+ module Entities
3208
+ class Status < Grape::Entity
3209
+ expose :user_name
3210
+ expose :text, documentation: { type: 'string', desc: 'Status update text.' }
3211
+ expose :ip, if: { type: :full }
3212
+ expose :user_type, :user_id, if: ->(status, options) { status.user.public? }
3213
+ expose :digest do |status, options|
3214
+ Digest::MD5.hexdigest(status.txt)
3215
+ end
3216
+ expose :replies, using: API::Status, as: :replies
3217
+ end
3218
+ end
3219
+
3220
+ class Statuses < Grape::API
3221
+ version 'v1'
3222
+
3223
+ desc 'Statuses index' do
3224
+ params: API::Entities::Status.documentation
3225
+ end
3226
+ get '/statuses' do
3227
+ statuses = Status.all
3228
+ type = current_user.admin? ? :full : :default
3229
+ present statuses, with: API::Entities::Status, type: type
3230
+ end
569
3231
  end
570
-
571
3232
  end
572
3233
  ```
573
3234
 
574
- When you add a route for a resource, a route for the `OPTIONS`
575
- method will also be added. The response to an OPTIONS request will
576
- include an "Allow" header listing the supported methods.
3235
+ You can use entity documentation directly in the params block with `using: Entity.documentation`.
577
3236
 
578
3237
  ```ruby
579
- class API < Grape::API
580
-
581
- get '/rt_count' do
582
- { rt_count: current_user.rt_count }
583
- end
3238
+ module API
3239
+ class Statuses < Grape::API
3240
+ version 'v1'
584
3241
 
585
- params do
586
- requires :value, type: Integer, desc: 'Value to add to the rt count.'
587
- end
588
- put '/rt_count' do
589
- current_user.rt_count += params[:value].to_i
590
- { rt_count: current_user.rt_count }
3242
+ desc 'Create a status'
3243
+ params do
3244
+ requires :all, except: [:ip], using: API::Entities::Status.documentation.except(:id)
3245
+ end
3246
+ post '/status' do
3247
+ Status.create! params
3248
+ end
591
3249
  end
592
-
593
3250
  end
594
3251
  ```
595
3252
 
596
- ``` shell
597
- curl -v -X OPTIONS http://localhost:3000/rt_count
3253
+ You can present with multiple entities using an optional Symbol argument.
598
3254
 
599
- > OPTIONS /rt_count HTTP/1.1
600
- >
601
- < HTTP/1.1 204 No Content
602
- < Allow: OPTIONS, GET, PUT
3255
+ ```ruby
3256
+ get '/statuses' do
3257
+ statuses = Status.all.page(1).per(20)
3258
+ present :total_page, 10
3259
+ present :per_page, 20
3260
+ present :statuses, statuses, with: API::Entities::Status
3261
+ end
603
3262
  ```
604
3263
 
605
- You can disable this behavior with `do_not_route_options!`.
606
-
607
- If a request for a resource is made with an unsupported HTTP method, an
608
- HTTP 405 (Method Not Allowed) response will be returned.
609
-
610
- ``` shell
611
- curl -X DELETE -v http://localhost:3000/rt_count/
3264
+ The response will be
612
3265
 
613
- > DELETE /rt_count/ HTTP/1.1
614
- > Host: localhost:3000
615
- >
616
- < HTTP/1.1 405 Method Not Allowed
617
- < Allow: OPTIONS, GET, PUT
618
3266
  ```
619
-
620
- ## Raising Exceptions
621
-
622
- You can abort the execution of an API method by raising errors with `error!`.
623
-
624
- ```ruby
625
- error! "Access Denied", 401
3267
+ {
3268
+ total_page: 10,
3269
+ per_page: 20,
3270
+ statuses: []
3271
+ }
626
3272
  ```
627
3273
 
628
- You can also return JSON formatted objects by raising error! and passing a hash
629
- instead of a message.
3274
+ In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent.
630
3275
 
631
3276
  ```ruby
632
- error! { "error" => "unexpected error", "detail" => "missing widget" }, 500
3277
+ class Status
3278
+ def entity
3279
+ Entity.new(self)
3280
+ end
3281
+
3282
+ class Entity < Grape::Entity
3283
+ expose :text, :user_id
3284
+ end
3285
+ end
633
3286
  ```
634
3287
 
635
- ## Exception Handling
3288
+ If you organize your entities this way, Grape will automatically detect the `Entity` class and use it to present your models. In this example, if you added `present Status.new` to your endpoint, Grape will automatically detect that there is a `Status::Entity` class and use that as the representative entity. This can still be overridden by using the `:with` option or an explicit `represents` call.
636
3289
 
637
- Grape can be told to rescue all exceptions and return them in the API format.
3290
+ You can present `hash` with `Grape::Presenters::Presenter` to keep things consistent.
638
3291
 
639
3292
  ```ruby
640
- class Twitter::API < Grape::API
641
- rescue_from :all
3293
+ get '/users' do
3294
+ present { id: 10, name: :dgz }, with: Grape::Presenters::Presenter
642
3295
  end
3296
+ ````
3297
+ The response will be
3298
+
3299
+ ```ruby
3300
+ {
3301
+ id: 10,
3302
+ name: 'dgz'
3303
+ }
643
3304
  ```
644
3305
 
645
- You can also rescue specific exceptions.
3306
+ It has the same result with
646
3307
 
647
3308
  ```ruby
648
- class Twitter::API < Grape::API
649
- rescue_from ArgumentError, NotImplementedError
3309
+ get '/users' do
3310
+ present :id, 10
3311
+ present :name, :dgz
650
3312
  end
651
3313
  ```
652
3314
 
653
- The error format will match the request format. See "Content-Types" below.
3315
+ ### Hypermedia and Roar
654
3316
 
655
- Custom error formatters for existing and additional types can be defined with a proc.
3317
+ You can use [Roar](https://github.com/apotonick/roar) to render HAL or Collection+JSON with the help of [grape-roar](https://github.com/ruby-grape/grape-roar), which defines a custom JSON formatter and enables presenting entities with Grape's `present` keyword.
3318
+
3319
+ ### Rabl
3320
+
3321
+ You can use [Rabl](https://github.com/nesquena/rabl) templates with the help of the [grape-rabl](https://github.com/ruby-grape/grape-rabl) gem, which defines a custom Grape Rabl formatter.
3322
+
3323
+ ### Active Model Serializers
3324
+
3325
+ You can use [Active Model Serializers](https://github.com/rails-api/active_model_serializers) serializers with the help of the [grape-active_model_serializers](https://github.com/jrhe/grape-active_model_serializers) gem, which defines a custom Grape AMS formatter.
3326
+
3327
+ ## Sending Raw or No Data
3328
+
3329
+ In general, use the binary format to send raw data.
656
3330
 
657
3331
  ```ruby
658
- class Twitter::API < Grape::API
659
- error_formatter :txt, lambda { |message, backtrace, options, env|
660
- "error: #{message} from #{backtrace}"
661
- }
3332
+ class API < Grape::API
3333
+ get '/file' do
3334
+ content_type 'application/octet-stream'
3335
+ File.binread 'file.bin'
3336
+ end
662
3337
  end
663
3338
  ```
664
3339
 
665
- You can also use a module or class.
3340
+ You can set the response body explicitly with `body`.
666
3341
 
667
3342
  ```ruby
668
- module CustomFormatter
669
- def self.call(message, backtrace, options, env)
670
- { message: message, backtrace: backtrace }
3343
+ class API < Grape::API
3344
+ get '/' do
3345
+ content_type 'text/plain'
3346
+ body 'Hello World'
3347
+ # return value ignored
671
3348
  end
672
3349
  end
3350
+ ```
673
3351
 
674
- class Twitter::API < Grape::API
675
- error_formatter :custom, CustomFormatter
3352
+ Use `body false` to return `204 No Content` without any data or content-type.
3353
+
3354
+ If you want to empty the body with an HTTP status code other than `204 No Content`, you can override the status code after specifying `body false` as follows
3355
+
3356
+ ```ruby
3357
+ class API < Grape::API
3358
+ get '/' do
3359
+ body false
3360
+ status 304
3361
+ end
676
3362
  end
677
3363
  ```
678
3364
 
679
- You can rescue all exceptions with a code block. The `rack_response` wrapper
680
- automatically sets the default error code and content-type.
3365
+ You can also set the response to a file with `sendfile`. This works with the [Rack::Sendfile](https://www.rubydoc.info/gems/rack/Rack/Sendfile) middleware to optimally send the file through your web server software.
681
3366
 
682
3367
  ```ruby
683
- class Twitter::API < Grape::API
684
- rescue_from :all do |e|
685
- rack_response({ message: "rescued from #{e.class.name}" })
3368
+ class API < Grape::API
3369
+ get '/' do
3370
+ sendfile '/path/to/file'
686
3371
  end
687
3372
  end
688
3373
  ```
689
3374
 
690
- You can also rescue specific exceptions with a code block and handle the Rack
691
- response at the lowest level.
3375
+ To stream a file in chunks use `stream`
692
3376
 
693
3377
  ```ruby
694
- class Twitter::API < Grape::API
695
- rescue_from :all do |e|
696
- Rack::Response.new([ e.message ], 500, { "Content-type" => "text/error" }).finish
3378
+ class API < Grape::API
3379
+ get '/' do
3380
+ stream '/path/to/file'
697
3381
  end
698
3382
  end
699
3383
  ```
700
3384
 
701
- Or rescue specific exceptions.
3385
+ If you want to stream non-file data use the `stream` method and a `Stream` object.
3386
+ This is an object that responds to `each` and yields for each chunk to send to the client.
3387
+ Each chunk will be sent as it is yielded instead of waiting for all of the content to be available.
702
3388
 
703
3389
  ```ruby
704
- class Twitter::API < Grape::API
705
- rescue_from ArgumentError do |e|
706
- Rack::Response.new([ "ArgumentError: #{e.message}" ], 500)
3390
+ class MyStream
3391
+ def each
3392
+ yield 'part 1'
3393
+ yield 'part 2'
3394
+ yield 'part 3'
707
3395
  end
708
- rescue_from NotImplementedError do |e|
709
- Rack::Response.new([ "NotImplementedError: #{e.message}" ], 500)
3396
+ end
3397
+
3398
+ class API < Grape::API
3399
+ get '/' do
3400
+ stream MyStream.new
710
3401
  end
711
3402
  end
712
3403
  ```
713
3404
 
714
- #### Rails 3.x
3405
+ ## Authentication
715
3406
 
716
- When mounted inside containers, such as Rails 3.x, errors like "404 Not Found" or
717
- "406 Not Acceptable" will likely be handled and rendered by Rails handlers. For instance,
718
- accessing a nonexistent route "/api/foo" raises a 404, which inside rails will ultimately
719
- be translated to an `ActionController::RoutingError`, which most likely will get rendered
720
- to a HTML error page.
3407
+ ### Basic Auth
721
3408
 
722
- Most APIs will enjoy preventing downstream handlers from handling errors. You may set the
723
- `:cascade` option to `false` for the entire API or separately on specific `version` definitions,
724
- which will remove the `X-Cascade: true` header from API responses.
3409
+ Grape has built-in Basic authentication (the given `block` is executed in the context of the current `Endpoint`). Authentication applies to the current namespace and any children, but not parents.
725
3410
 
726
3411
  ```ruby
727
- cascade false
3412
+ http_basic do |username, password|
3413
+ # verify user's password here
3414
+ # IMPORTANT: make sure you use a comparison method which isn't prone to a timing attack
3415
+ end
728
3416
  ```
729
3417
 
730
- ```ruby
731
- version 'v1', using: :header, vendor: 'twitter', cascade: false
732
- ```
3418
+ ### Register custom middleware for authentication
733
3419
 
734
- ## Logging
3420
+ Grape can use custom Middleware for authentication. How to implement these Middleware have a look at `Rack::Auth::Basic` or similar implementations.
735
3421
 
736
- `Grape::API` provides a `logger` method which by default will return an instance of the `Logger`
737
- class from Ruby's standard library.
3422
+ For registering a Middleware you need the following options:
738
3423
 
739
- To log messages from within an endpoint, you need to define a helper to make the logger
740
- available in the endpoint context.
3424
+ * `label` - the name for your authenticator to use it later
3425
+ * `MiddlewareClass` - the MiddlewareClass to use for authentication
3426
+ * `option_lookup_proc` - A Proc with one Argument to lookup the options at runtime (return value is an `Array` as Parameter for the Middleware).
3427
+
3428
+ Example:
741
3429
 
742
3430
  ```ruby
743
- class API < Grape::API
744
- helpers do
745
- def logger
746
- API.logger
747
- end
748
- end
749
- post '/statuses' do
750
- # ...
751
- logger.info "#{current_user} has statused"
752
- end
753
- end
754
- ```
755
3431
 
756
- You can also set your own logger.
3432
+ Grape::Middleware::Auth::Strategies.add(:my_auth, AuthMiddleware, ->(options) { [options[:realm]] } )
757
3433
 
758
- ```ruby
759
- class MyLogger
760
- def warning(message)
761
- puts "this is a warning: #{message}"
762
- end
763
- end
764
3434
 
765
- class API < Grape::API
766
- logger MyLogger.new
767
- helpers do
768
- def logger
769
- API.logger
770
- end
771
- end
772
- get '/statuses' do
773
- logger.warning "#{current_user} has statused"
774
- end
3435
+ auth :my_auth, { realm: 'Test Api'} do |credentials|
3436
+ # lookup the user's password here
3437
+ { 'user1' => 'password1' }[username]
775
3438
  end
3439
+
776
3440
  ```
777
3441
 
778
- ## API Formats
3442
+ Use [Doorkeeper](https://github.com/doorkeeper-gem/doorkeeper), [warden-oauth2](https://github.com/opperator/warden-oauth2) or [rack-oauth2](https://github.com/nov/rack-oauth2) for OAuth2 support.
779
3443
 
780
- By default, Grape supports _XML_, _JSON_, and _TXT_ content-types. The default format is `:txt`.
3444
+ You can access the controller params, headers, and helpers through the context with the `#context` method inside any auth middleware inherited from `Grape::Middleware::Auth::Base`.
781
3445
 
782
- Serialization takes place automatically. For example, you do not have to call `to_json` in each JSON API implementation.
3446
+ ## Describing and Inspecting an API
783
3447
 
784
- Your API can declare which types to support by using `content_type`. Response format is determined by the
785
- request's extension, an explicit `format` parameter in the query string, or `Accept` header.
3448
+ Grape routes can be reflected at runtime. This can notably be useful for generating documentation.
786
3449
 
787
- The following API will only respond to the JSON content-type and will not parse any other input than `application/json`,
788
- `application/x-www-form-urlencoded`, `multipart/form-data`, `multipart/related` and `multipart/mixed`. All other requests
789
- will fail with an HTTP 406 error code.
3450
+ Grape exposes arrays of API versions and compiled routes. Each route contains a `prefix`, `version`, `namespace`, `method` and `params`. You can add custom route settings to the route metadata with `route_setting`.
790
3451
 
791
3452
  ```ruby
792
- class Twitter::API < Grape::API
793
- format :json
3453
+ class TwitterAPI < Grape::API
3454
+ version 'v1'
3455
+ desc 'Includes custom settings.'
3456
+ route_setting :custom, key: 'value'
3457
+ get do
3458
+
3459
+ end
794
3460
  end
795
3461
  ```
796
3462
 
797
- When the content-type is omitted, Grape will return a 406 error code unless `default_format` is specified.
798
- The following API will try to parse any data without a content-type using a JSON parser.
3463
+ Examine the routes at runtime.
799
3464
 
800
3465
  ```ruby
801
- class Twitter::API < Grape::API
802
- format :json
803
- default_format :json
804
- end
3466
+ TwitterAPI::versions # yields [ 'v1', 'v2' ]
3467
+ TwitterAPI::routes # yields an array of Grape::Route objects
3468
+ TwitterAPI::routes[0].version # => 'v1'
3469
+ TwitterAPI::routes[0].description # => 'Includes custom settings.'
3470
+ TwitterAPI::routes[0].settings[:custom] # => { key: 'value' }
805
3471
  ```
806
3472
 
807
- If you combine `format` with `rescue_from :all`, errors will be rendered using the same format.
808
- If you do not want this behavior, set the default error formatter with `default_error_formatter`.
3473
+ Note that `Route#route_xyz` methods have been deprecated since 0.15.0 and removed since 2.0.1.
809
3474
 
810
- ```ruby
811
- class Twitter::API < Grape::API
812
- format :json
813
- content_type :txt, "text/plain"
814
- default_error_formatter :txt
815
- end
816
- ```
3475
+ Please use `Route#xyz` instead.
817
3476
 
818
- Custom formatters for existing and additional types can be defined with a proc.
3477
+ Note that difference of `Route#options` and `Route#settings`.
3478
+
3479
+ The `options` can be referred from your route, it should be set by specifying key and value on verb methods such as `get`, `post` and `put`.
3480
+ The `settings` can also be referred from your route, but it should be set by specifying key and value on `route_setting`.
3481
+
3482
+ ## Current Route and Endpoint
3483
+
3484
+ It's possible to retrieve the information about the current route from within an API call with `route`.
819
3485
 
820
3486
  ```ruby
821
- class Twitter::API < Grape::API
822
- content_type :xls, "application/vnd.ms-excel"
823
- formatter :xls, lambda { |object, env| object.to_xls }
3487
+ class MyAPI < Grape::API
3488
+ desc 'Returns a description of a parameter.'
3489
+ params do
3490
+ requires :id, type: Integer, desc: 'Identity.'
3491
+ end
3492
+ get 'params/:id' do
3493
+ route.params[params[:id]] # yields the parameter description
3494
+ end
824
3495
  end
825
3496
  ```
826
3497
 
827
- You can also use a module or class.
3498
+ The current endpoint responding to the request is `self` within the API block or `env['api.endpoint']` elsewhere. The endpoint has some interesting properties, such as `source` which gives you access to the original code block of the API implementation. This can be particularly useful for building a logger middleware.
828
3499
 
829
3500
  ```ruby
830
- module XlsFormatter
831
- def self.call(object, env)
832
- object.to_xls
3501
+ class ApiLogger < Grape::Middleware::Base
3502
+ def before
3503
+ file = env['api.endpoint'].source.source_location[0]
3504
+ line = env['api.endpoint'].source.source_location[1]
3505
+ logger.debug "[api] #{file}:#{line}"
833
3506
  end
834
3507
  end
835
-
836
- class Twitter::API < Grape::API
837
- content_type :xls, "application/vnd.ms-excel"
838
- formatter :xls, XlsFormatter
839
- end
840
3508
  ```
841
3509
 
842
- Built-in formats are the following.
3510
+ ## Before, After and Finally
843
3511
 
844
- * `:json`: use object's `to_json` when available, otherwise call `MultiJson.dump`
845
- * `:xml`: use object's `to_xml` when available, usually via `MultiXml`, otherwise call `to_s`
846
- * `:txt`: use object's `to_txt` when available, otherwise `to_s`
847
- * `:serializable_hash`: use object's `serializable_hash` when available, otherwise fallback to `:json`
3512
+ Blocks can be executed before or after every API call, using `before`, `after`, `before_validation` and `after_validation`.
3513
+ If the API fails the `after` call will not be triggered, if you need code to execute for sure use the `finally`.
3514
+
3515
+ Before and after callbacks execute in the following order:
3516
+
3517
+ 1. `before`
3518
+ 2. `before_validation`
3519
+ 3. _validations_
3520
+ 4. `after_validation` (upon successful validation)
3521
+ 5. _the API call_ (upon successful validation)
3522
+ 6. `after` (upon successful validation and API call)
3523
+ 7. `finally` (always)
3524
+
3525
+ Steps 4, 5 and 6 only happen if validation succeeds.
3526
+
3527
+ If a request for a resource is made with an unsupported HTTP method (returning HTTP 405) only `before` callbacks will be executed. The remaining callbacks will be bypassed.
3528
+
3529
+ If a request for a resource is made that triggers the built-in `OPTIONS` handler, only `before` and `after` callbacks will be executed. The remaining callbacks will be bypassed.
848
3530
 
849
- Use `default_format` to set the fallback format when the format could not be determined from the `Accept` header.
850
- See below for the order for choosing the API format.
3531
+ For example, using a simple `before` block to set a header.
851
3532
 
852
3533
  ```ruby
853
- class Twitter::API < Grape::API
854
- default_format :json
3534
+ before do
3535
+ header 'X-Robots-Tag', 'noindex'
855
3536
  end
856
3537
  ```
857
3538
 
858
- The order for choosing the format is the following.
3539
+ You can ensure a block of code runs after every request (including failures) with `finally`:
859
3540
 
860
- * Use the file extension, if specified. If the file is .json, choose the JSON format.
861
- * Use the value of the `format` parameter in the query string, if specified.
862
- * Use the format set by the `format` option, if specified.
863
- * Attempt to find an acceptable format from the `Accept` header.
864
- * Use the default format, if specified by the `default_format` option.
865
- * Default to `:txt`.
3541
+ ```ruby
3542
+ finally do
3543
+ # this code will run after every request (successful or failed)
3544
+ end
3545
+ ```
866
3546
 
867
- ### JSONP
3547
+ **Namespaces**
868
3548
 
869
- Grape suports JSONP via [Rack::JSONP](https://github.com/rack/rack-contrib), part of the
870
- [rack-contrib](https://github.com/rack/rack-contrib) gem. Add `rack-contrib` to your `Gemfile`.
3549
+ Callbacks apply to each API call within and below the current namespace:
871
3550
 
872
3551
  ```ruby
873
- require 'rack/contrib'
874
-
875
- class API < Grape::API
876
- use Rack::JSONP
877
- format :json
3552
+ class MyAPI < Grape::API
878
3553
  get '/' do
879
- 'Hello World'
3554
+ "root - #{@blah}"
3555
+ end
3556
+
3557
+ namespace :foo do
3558
+ before do
3559
+ @blah = 'blah'
3560
+ end
3561
+
3562
+ get '/' do
3563
+ "root - foo - #{@blah}"
3564
+ end
3565
+
3566
+ namespace :bar do
3567
+ get '/' do
3568
+ "root - foo - bar - #{@blah}"
3569
+ end
3570
+ end
880
3571
  end
881
3572
  end
882
3573
  ```
883
3574
 
884
- ### CORS
3575
+ The behavior is then:
3576
+
3577
+ ```bash
3578
+ GET / # 'root - '
3579
+ GET /foo # 'root - foo - blah'
3580
+ GET /foo/bar # 'root - foo - bar - blah'
3581
+ ```
885
3582
 
886
- Grape supports CORS via [Rack::CORS](https://github.com/cyu/rack-cors), part of the
887
- [rack-cors](https://github.com/cyu/rack-cors) gem. Add `rack-cors` to your `Gemfile`,
888
- then use the middleware in your config.ru file.
3583
+ Params on a `namespace` (or whichever alias you are using) will also be available when using `before_validation` or `after_validation`:
889
3584
 
890
3585
  ```ruby
891
- require 'rack/cors'
3586
+ class MyAPI < Grape::API
3587
+ params do
3588
+ requires :blah, type: Integer
3589
+ end
3590
+ resource ':blah' do
3591
+ after_validation do
3592
+ # if we reach this point validations will have passed
3593
+ @blah = declared(params, include_missing: false)[:blah]
3594
+ end
892
3595
 
893
- use Rack::Cors do
894
- allow do
895
- origins '*'
896
- resource '*', headers: :any, methods: :get
3596
+ get '/' do
3597
+ @blah.class
3598
+ end
897
3599
  end
898
3600
  end
3601
+ ```
899
3602
 
900
- run Twitter::API
3603
+ The behavior is then:
901
3604
 
3605
+ ```bash
3606
+ GET /123 # 'Integer'
3607
+ GET /foo # 400 error - 'blah is invalid'
902
3608
  ```
903
3609
 
904
- ## Content-type
3610
+ **Versioning**
905
3611
 
906
- Content-type is set by the formatter. You can override the content-type of the response at runtime
907
- by setting the `Content-Type` header.
3612
+ When a callback is defined within a version block, it's only called for the routes defined in that block.
908
3613
 
909
3614
  ```ruby
910
- class API < Grape::API
911
- get '/home_timeline_js' do
912
- content_type "application/javascript"
913
- "var statuses = ...;"
3615
+ class Test < Grape::API
3616
+ resource :foo do
3617
+ version 'v1', :using => :path do
3618
+ before do
3619
+ @output ||= 'v1-'
3620
+ end
3621
+ get '/' do
3622
+ @output += 'hello'
3623
+ end
3624
+ end
3625
+
3626
+ version 'v2', :using => :path do
3627
+ before do
3628
+ @output ||= 'v2-'
3629
+ end
3630
+ get '/' do
3631
+ @output += 'hello'
3632
+ end
3633
+ end
914
3634
  end
915
3635
  end
916
3636
  ```
917
3637
 
918
- ## API Data Formats
3638
+ The behavior is then:
919
3639
 
920
- Grape accepts and parses input data sent with the POST and PUT methods as described in the Parameters
921
- section above. It also supports custom data formats. You must declare additional content-types via
922
- `content_type` and optionally supply a parser via `parser` unless a parser is already available within
923
- Grape to enable a custom format. Such a parser can be a function or a class.
3640
+ ```bash
3641
+ GET /foo/v1 # 'v1-hello'
3642
+ GET /foo/v2 # 'v2-hello'
3643
+ ```
924
3644
 
925
- With a parser, parsed data is available "as-is" in `env['api.request.body']`.
926
- Without a parser, data is available "as-is" and in `env['api.request.input']`.
3645
+ **Altering Responses**
927
3646
 
928
- The following example is a trivial parser that will assign any input with the "text/custom" content-type
929
- to `:value`. The parameter will be available via `params[:value]` inside the API call.
3647
+ Using `present` in any callback allows you to add data to a response:
930
3648
 
931
3649
  ```ruby
932
- module CustomParser
933
- def self.call(object, env)
934
- { value: object.to_s }
935
- end
936
- end
937
- ```
3650
+ class MyAPI < Grape::API
3651
+ format :json
938
3652
 
939
- ```ruby
940
- content_type :txt, "text/plain"
941
- content_type :custom, "text/custom"
942
- parser :custom, CustomParser
3653
+ after_validation do
3654
+ present :name, params[:name] if params[:name]
3655
+ end
943
3656
 
944
- put "value" do
945
- params[:value]
3657
+ get '/greeting' do
3658
+ present :greeting, 'Hello!'
3659
+ end
946
3660
  end
947
3661
  ```
948
3662
 
949
- You can invoke the above API as follows.
3663
+ The behavior is then:
950
3664
 
3665
+ ```bash
3666
+ GET /greeting # {"greeting":"Hello!"}
3667
+ GET /greeting?name=Alan # {"name":"Alan","greeting":"Hello!"}
951
3668
  ```
952
- curl -X PUT -d 'data' 'http://localhost:9292/value' -H Content-Type:text/custom -v
953
- ```
954
-
955
- You can disable parsing for a content-type with `nil`. For example, `parser :json, nil` will disable JSON parsing altogether. The request data is then available as-is in `env['api.request.body']`.
956
3669
 
957
- ## RESTful Model Representations
958
-
959
- Grape supports a range of ways to present your data with some help from a generic `present` method,
960
- which accepts two arguments: the object to be presented and the options associated with it. The options
961
- hash may include `:with`, which defines the entity to expose.
3670
+ Instead of altering a response, you can also terminate and rewrite it from any callback using `error!`, including `after`. This will cause all subsequent steps in the process to not be called. **This includes the actual api call and any callbacks**
962
3671
 
963
- ### Grape Entities
3672
+ ## Anchoring
964
3673
 
965
- Add the [grape-entity](https://github.com/intridea/grape-entity) gem to your Gemfile.
966
- Please refer to the [grape-entity documentation](https://github.com/intridea/grape-entity/blob/master/README.markdown)
967
- for more details.
3674
+ Grape by default anchors all request paths, which means that the request URL should match from start to end to match, otherwise a `404 Not Found` is returned. However, this is sometimes not what you want, because it is not always known upfront what can be expected from the call. This is because Rack-mount by default anchors requests to match from the start to the end, or not at all.
3675
+ Rails solves this problem by using a `anchor: false` option in your routes.
3676
+ In Grape this option can be used as well when a method is defined.
968
3677
 
969
- The following example exposes statuses.
3678
+ For instance when your API needs to get part of an URL, for instance:
970
3679
 
971
3680
  ```ruby
972
- module API
973
-
974
- module Entities
975
- class Status < Grape::Entity
976
- expose :user_name
977
- expose :text, documentation: { type: "string", desc: "Status update text." }
978
- expose :ip, if: { type: :full }
979
- expose :user_type, user_id, if: lambda{ |status, options| status.user.public? }
980
- expose :digest { |status, options| Digest::MD5.hexdigest(status.txt) }
981
- expose :replies, using: API::Status, as: :replies
982
- end
983
- end
984
-
985
- class Statuses < Grape::API
986
- version 'v1'
3681
+ class TwitterAPI < Grape::API
3682
+ namespace :statuses do
3683
+ get '/(*:status)', anchor: false do
987
3684
 
988
- desc 'Statuses index', {
989
- object_fields: API::Entities::Status.documentation
990
- }
991
- get '/statuses' do
992
- statuses = Status.all
993
- type = current_user.admin? ? :full : :default
994
- present statuses, with: API::Entities::Status, type: type
995
3685
  end
996
3686
  end
997
3687
  end
998
3688
  ```
999
3689
 
1000
- You can present with multiple entities using an optional Symbol argument.
3690
+ This will match all paths starting with '/statuses/'. There is one caveat though: the `params[:status]` parameter only holds the first part of the request url.
3691
+ Luckily this can be circumvented by using the described above syntax for path specification and using the `PATH_INFO` Rack environment variable, using `env['PATH_INFO']`. This will hold everything that comes after the '/statuses/' part.
3692
+
3693
+ ## Instance Variables
3694
+
3695
+ You can use instance variables to pass information across the various stages of a request. An instance variable set within a `before` validator is accessible within the endpoint's code and can also be utilized within the `rescue_from` handler.
1001
3696
 
1002
3697
  ```ruby
1003
- get '/statuses' do
1004
- statuses = Status.all.page(1).per(20)
1005
- present :total_page, 10
1006
- present :per_page, 20
1007
- present :statuses, statuses, with: API::Entities::Status
3698
+ class TwitterAPI < Grape::API
3699
+ before do
3700
+ @var = 1
1008
3701
  end
1009
- ```
1010
3702
 
1011
- The response will be
3703
+ get '/' do
3704
+ puts @var # => 1
3705
+ raise
3706
+ end
1012
3707
 
1013
- ```
1014
- {
1015
- total_page: 10,
1016
- per_page: 20,
1017
- statuses: []
1018
- }
3708
+ rescue_from :all do
3709
+ puts @var # => 1
3710
+ end
3711
+ end
1019
3712
  ```
1020
3713
 
1021
- In addition to separately organizing entities, it may be useful to put them as namespaced
1022
- classes underneath the model they represent.
3714
+ 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.
1023
3715
 
1024
3716
  ```ruby
1025
- class Status
1026
- def entity
1027
- Status.new(self)
3717
+ class TwitterAPI < Grape::API
3718
+ get '/first' do
3719
+ @var = 1
3720
+ puts @var # => 1
1028
3721
  end
1029
3722
 
1030
- class Entity < Grape::Entity
1031
- expose :text, :user_id
3723
+ get '/second' do
3724
+ puts @var # => nil
1032
3725
  end
1033
3726
  end
1034
3727
  ```
1035
3728
 
1036
- If you organize your entities this way, Grape will automatically detect the `Entity` class and
1037
- use it to present your models. In this example, if you added `present Status.new` to your endpoint,
1038
- Grape will automatically detect that there is a `Status::Entity` class and use that as the
1039
- representative entity. This can still be overridden by using the `:with` option or an explicit
1040
- `represents` call.
1041
-
1042
- ### Hypermedia
1043
-
1044
- You can use any Hypermedia representer, including [Roar](https://github.com/apotonick/roar).
1045
- Roar renders JSON and works with the built-in Grape JSON formatter. Add `Roar::Representer::JSON`
1046
- into your models or call `to_json` explicitly in your API implementation.
3729
+ ## Using Custom Middleware
1047
3730
 
1048
- ### Rabl
3731
+ ### Grape Middleware
1049
3732
 
1050
- You can use [Rabl](https://github.com/nesquena/rabl) templates with the help of the
1051
- [grape-rabl](https://github.com/LTe/grape-rabl) gem, which defines a custom Grape Rabl
1052
- formatter.
3733
+ You can make a custom middleware by using `Grape::Middleware::Base`.
3734
+ It's inherited from some grape official middlewares in fact.
1053
3735
 
1054
- ## Authentication
3736
+ For example, you can write a middleware to log application exception.
1055
3737
 
1056
- ### Basic and Digest Auth
3738
+ ```ruby
3739
+ class LoggingError < Grape::Middleware::Base
3740
+ def after
3741
+ return unless @app_response && @app_response[0] == 500
3742
+ env['rack.logger'].error("Raised error on #{env['PATH_INFO']}")
3743
+ end
3744
+ end
3745
+ ```
1057
3746
 
1058
- Grape has built-in Basic and Digest authentication.
3747
+ Your middleware can overwrite application response as follows, except error case.
1059
3748
 
1060
3749
  ```ruby
1061
- http_basic do |username, password|
1062
- # verify user's password here
1063
- { 'test' => 'password1' }[username] == password
3750
+ class Overwriter < Grape::Middleware::Base
3751
+ def after
3752
+ [200, { 'Content-Type' => 'text/plain' }, ['Overwritten.']]
3753
+ end
1064
3754
  end
1065
3755
  ```
1066
3756
 
3757
+ You can add your custom middleware with `use`, that push the middleware onto the stack, and you can also control where the middleware is inserted using `insert`, `insert_before` and `insert_after`.
3758
+
1067
3759
  ```ruby
1068
- http_digest({ realm: 'Test Api', opaque: 'app secret' }) do |username|
1069
- # lookup the user's password here
1070
- { 'user1' => 'password1' }[username]
3760
+ class CustomOverwriter < Grape::Middleware::Base
3761
+ def after
3762
+ [200, { 'Content-Type' => 'text/plain' }, [@options[:message]]]
3763
+ end
3764
+ end
3765
+
3766
+
3767
+ class API < Grape::API
3768
+ use Overwriter
3769
+ insert_before Overwriter, CustomOverwriter, message: 'Overwritten again.'
3770
+ insert 0, CustomOverwriter, message: 'Overwrites all other middleware.'
3771
+
3772
+ get '/' do
3773
+ end
1071
3774
  end
1072
3775
  ```
1073
3776
 
1074
- Use [warden-oauth2](https://github.com/opperator/warden-oauth2) or [rack-oauth2](https://github.com/nov/rack-oauth2) for OAuth2 support.
3777
+ You can access the controller params, headers, and helpers through the context with the `#context` method inside any middleware inherited from `Grape::Middleware::Base`.
1075
3778
 
1076
- ## Describing and Inspecting an API
3779
+ ### Rails Middleware
1077
3780
 
1078
- Grape routes can be reflected at runtime. This can notably be useful for generating
1079
- documentation.
3781
+ 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.
3782
+ You only have to implement the helpers to access the specific `env` variable.
1080
3783
 
1081
- Grape exposes arrays of API versions and compiled routes. Each route
1082
- contains a `route_prefix`, `route_version`, `route_namespace`, `route_method`,
1083
- `route_path` and `route_params`. The description and the optional hash that
1084
- follows the API path may contain any number of keys and its values are also
1085
- accessible via dynamically-generated `route_[name]` functions.
3784
+ If you are using a custom application that is inherited from `Rails::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.
1086
3785
 
1087
3786
  ```ruby
1088
- TwitterAPI::versions # yields [ 'v1', 'v2' ]
1089
- TwitterAPI::routes # yields an array of Grape::Route objects
1090
- TwitterAPI::routes[0].route_version # yields 'v1'
1091
- TwitterAPI::routes[0].route_description # etc.
3787
+ class Company::Application < Rails::Application
3788
+ config.middleware.insert_before(Rack::Attack, Middleware::ApiLogger)
3789
+ end
1092
3790
  ```
1093
3791
 
1094
- ## Current Route and Endpoint
3792
+ ### Remote IP
3793
+
3794
+ By default you can access remote IP with `request.ip`. This is the remote IP address implemented by Rack. Sometimes it is desirable to get the remote IP [Rails-style](http://stackoverflow.com/questions/10997005/whats-the-difference-between-request-remote-ip-and-request-ip-in-rails) with `ActionDispatch::RemoteIp`.
1095
3795
 
1096
- It's possible to retrieve the information about the current route from within an API
1097
- call with `route`.
3796
+ Add `gem 'actionpack'` to your Gemfile and `require 'action_dispatch/middleware/remote_ip.rb'`. Use the middleware in your API and expose a `client_ip` helper. See [this documentation](http://api.rubyonrails.org/classes/ActionDispatch/RemoteIp.html) for additional options.
1098
3797
 
1099
3798
  ```ruby
1100
- class MyAPI < Grape::API
1101
- desc "Returns a description of a parameter."
1102
- params do
1103
- requires :id, type: Integer, desc: "Identity."
3799
+ class API < Grape::API
3800
+ use ActionDispatch::RemoteIp
3801
+
3802
+ helpers do
3803
+ def client_ip
3804
+ env['action_dispatch.remote_ip'].to_s
3805
+ end
1104
3806
  end
1105
- get "params/:id" do
1106
- route.route_params[params[:id]] # yields the parameter description
3807
+
3808
+ get :remote_ip do
3809
+ { ip: client_ip }
1107
3810
  end
1108
3811
  end
1109
3812
  ```
1110
3813
 
1111
- The current endpoint responding to the request is `self` within the API block
1112
- or `env['api.endpoint']` elsewhere. The endpoint has some interesting properties,
1113
- such as `source` which gives you access to the original code block of the API
1114
- implementation. This can be particularly useful for building a logger middleware.
3814
+ ## Writing Tests
3815
+
3816
+ ### Writing Tests with Rack
3817
+
3818
+ Use `rack-test` and define your API as `app`.
3819
+
3820
+ #### RSpec
3821
+
3822
+ You can test a Grape API with RSpec by making HTTP requests and examining the response.
1115
3823
 
1116
3824
  ```ruby
1117
- class ApiLogger < Grape::Middleware::Base
1118
- def before
1119
- file = env['api.endpoint'].source.source_location[0]
1120
- line = env['api.endpoint'].source.source_location[1]
1121
- logger.debug "[api] #{file}:#{line}"
3825
+
3826
+
3827
+ describe Twitter::API do
3828
+ include Rack::Test::Methods
3829
+
3830
+ def app
3831
+ Twitter::API
3832
+ end
3833
+
3834
+ context 'GET /api/statuses/public_timeline' do
3835
+ it 'returns an empty array of statuses' do
3836
+ get '/api/statuses/public_timeline'
3837
+ expect(last_response.status).to eq(200)
3838
+ expect(JSON.parse(last_response.body)).to eq []
3839
+ end
3840
+ end
3841
+ context 'GET /api/statuses/:id' do
3842
+ it 'returns a status by id' do
3843
+ status = Status.create!
3844
+ get "/api/statuses/#{status.id}"
3845
+ expect(last_response.body).to eq status.to_json
3846
+ end
1122
3847
  end
1123
3848
  end
1124
3849
  ```
1125
3850
 
1126
- ## Before and After
1127
-
1128
- Execute a block before or after every API call with `before` and `after`.
3851
+ There's no standard way of sending arrays of objects via an HTTP GET, so POST JSON data and specify the correct content-type.
1129
3852
 
1130
3853
  ```ruby
1131
- before do
1132
- header "X-Robots-Tag", "noindex"
3854
+ describe Twitter::API do
3855
+ context 'POST /api/statuses' do
3856
+ it 'creates many statuses' do
3857
+ statuses = [{ text: '...' }, { text: '...'}]
3858
+ post '/api/statuses', statuses.to_json, 'CONTENT_TYPE' => 'application/json'
3859
+ expect(last_response.body).to eq 201
3860
+ end
3861
+ end
1133
3862
  end
1134
3863
  ```
1135
3864
 
1136
- ## Anchoring
1137
-
1138
- Grape by default anchors all request paths, which means that the request URL
1139
- should match from start to end to match, otherwise a `404 Not Found` is
1140
- returned. However, this is sometimes not what you want, because it is not always
1141
- known upfront what can be expected from the call. This is because Rack-mount by
1142
- default anchors requests to match from the start to the end, or not at all.
1143
- Rails solves this problem by using a `anchor: false` option in your routes.
1144
- In Grape this option can be used as well when a method is defined.
3865
+ #### Airborne
1145
3866
 
1146
- For instance when you're API needs to get part of an URL, for instance:
3867
+ You can test with other RSpec-based frameworks, including [Airborne](https://github.com/brooklynDev/airborne), which uses `rack-test` to make requests.
1147
3868
 
1148
3869
  ```ruby
1149
- class TwitterAPI < Grape::API
1150
- namespace :statuses do
1151
- get '/(*:status)', anchor: false do
3870
+ require 'airborne'
3871
+
3872
+ Airborne.configure do |config|
3873
+ config.rack_app = Twitter::API
3874
+ end
1152
3875
 
3876
+ describe Twitter::API do
3877
+ context 'GET /api/statuses/:id' do
3878
+ it 'returns a status by id' do
3879
+ status = Status.create!
3880
+ get "/api/statuses/#{status.id}"
3881
+ expect_json(status.as_json)
1153
3882
  end
1154
3883
  end
1155
3884
  end
1156
3885
  ```
1157
3886
 
1158
- This will match all paths starting with '/statuses/'. There is one caveat though:
1159
- the `params[:status]` parameter only holds the first part of the request url.
1160
- Luckily this can be circumvented by using the described above syntax for path
1161
- specification and using the `PATH_INFO` Rack environment variable, using
1162
- `env["PATH_INFO"]`. This will hold everything that comes after the '/statuses/'
1163
- part.
1164
-
1165
- ## Writing Tests
1166
-
1167
- You can test a Grape API with RSpec by making HTTP requests and examining the response.
1168
-
1169
- ### Writing Tests with Rack
1170
-
1171
- Use `rack-test` and define your API as `app`.
3887
+ #### MiniTest
1172
3888
 
1173
3889
  ```ruby
1174
- require 'spec_helper'
3890
+ require 'test_helper'
1175
3891
 
1176
- describe Twitter::API do
3892
+ class Twitter::APITest < MiniTest::Test
1177
3893
  include Rack::Test::Methods
1178
3894
 
1179
3895
  def app
1180
3896
  Twitter::API
1181
3897
  end
1182
3898
 
1183
- describe Twitter::API do
1184
- describe "GET /api/v1/statuses" do
1185
- it "returns an empty array of statuses" do
1186
- get "/api/v1/statuses"
1187
- last_response.status.should == 200
1188
- JSON.parse(last_response.body).should == []
1189
- end
1190
- end
1191
- describe "GET /api/v1/statuses/:id" do
1192
- it "returns a status by id" do
1193
- status = Status.create!
1194
- get "/api/v1/statuses/#{status.id}"
1195
- last_response.body.should == status.to_json
1196
- end
1197
- end
3899
+ def test_get_api_statuses_public_timeline_returns_an_empty_array_of_statuses
3900
+ get '/api/statuses/public_timeline'
3901
+ assert last_response.ok?
3902
+ assert_equal [], JSON.parse(last_response.body)
3903
+ end
3904
+
3905
+ def test_get_api_statuses_id_returns_a_status_by_id
3906
+ status = Status.create!
3907
+ get "/api/statuses/#{status.id}"
3908
+ assert_equal status.to_json, last_response.body
1198
3909
  end
1199
3910
  end
1200
3911
  ```
1201
3912
 
1202
3913
  ### Writing Tests with Rails
1203
3914
 
1204
- ```ruby
1205
- require 'spec_helper'
3915
+ #### RSpec
1206
3916
 
3917
+ ```ruby
1207
3918
  describe Twitter::API do
1208
- describe "GET /api/v1/statuses" do
1209
- it "returns an empty array of statuses" do
1210
- get "/api/v1/statuses"
1211
- response.status.should == 200
1212
- JSON.parse(response.body).should == []
3919
+ context 'GET /api/statuses/public_timeline' do
3920
+ it 'returns an empty array of statuses' do
3921
+ get '/api/statuses/public_timeline'
3922
+ expect(response.status).to eq(200)
3923
+ expect(JSON.parse(response.body)).to eq []
1213
3924
  end
1214
3925
  end
1215
- describe "GET /api/v1/statuses/:id" do
1216
- it "returns a status by id" do
3926
+ context 'GET /api/statuses/:id' do
3927
+ it 'returns a status by id' do
1217
3928
  status = Status.create!
1218
- get "/api/v1/statuses/#{status.id}"
1219
- response.body.should == status.to_json
3929
+ get "/api/statuses/#{status.id}"
3930
+ expect(response.body).to eq status.to_json
1220
3931
  end
1221
3932
  end
1222
3933
  end
1223
3934
  ```
1224
3935
 
1225
- In Rails, HTTP request tests would go into the `spec/requests` group. You may want your API code to go into
1226
- `app/api` - you can match that layout under `spec` by adding the following in `spec/spec_helper.rb`.
3936
+ In Rails, HTTP request tests would go into the `spec/requests` group. You may want your API code to go into `app/api` - you can match that layout under `spec` by adding the following in `spec/rails_helper.rb`.
1227
3937
 
1228
3938
  ```ruby
1229
3939
  RSpec.configure do |config|
1230
- config.include RSpec::Rails::RequestExampleGroup, type: :request, example_group: {
1231
- file_path: /spec\/api/
1232
- }
3940
+ config.include RSpec::Rails::RequestExampleGroup, type: :request, file_path: /spec\/api/
3941
+ end
3942
+ ```
3943
+
3944
+ #### MiniTest
3945
+
3946
+ ```ruby
3947
+ class Twitter::APITest < ActiveSupport::TestCase
3948
+ include Rack::Test::Methods
3949
+
3950
+ def app
3951
+ Rails.application
3952
+ end
3953
+
3954
+ test 'GET /api/statuses/public_timeline returns an empty array of statuses' do
3955
+ get '/api/statuses/public_timeline'
3956
+ assert last_response.ok?
3957
+ assert_equal [], JSON.parse(last_response.body)
3958
+ end
3959
+
3960
+ test 'GET /api/statuses/:id returns a status by id' do
3961
+ status = Status.create!
3962
+ get "/api/statuses/#{status.id}"
3963
+ assert_equal status.to_json, last_response.body
3964
+ end
3965
+ end
3966
+ ```
3967
+
3968
+ ### Stubbing Helpers
3969
+
3970
+ Because helpers are mixed in based on the context when an endpoint is defined, it can be difficult to stub or mock them for testing. The `Grape::Endpoint.before_each` method can help by allowing you to define behavior on the endpoint that will run before every request.
3971
+
3972
+ ```ruby
3973
+ describe 'an endpoint that needs helpers stubbed' do
3974
+ before do
3975
+ Grape::Endpoint.before_each do |endpoint|
3976
+ allow(endpoint).to receive(:helper_name).and_return('desired_value')
3977
+ end
3978
+ end
3979
+
3980
+ after do
3981
+ Grape::Endpoint.before_each nil
3982
+ end
3983
+
3984
+ it 'stubs the helper' do
3985
+
3986
+ end
1233
3987
  end
1234
3988
  ```
1235
3989
 
1236
3990
  ## Reloading API Changes in Development
1237
3991
 
1238
- ### Rails 3.x
3992
+ ### Reloading in Rack Applications
3993
+
3994
+ Use [grape-reload](https://github.com/AlexYankee/grape-reload).
3995
+
3996
+ ### Reloading in Rails Applications
3997
+
3998
+ #### Rails 7+ (Zeitwerk)
3999
+
4000
+ Rails 7+ uses [Zeitwerk](https://github.com/fxn/zeitwerk) as the default autoloader, which automatically handles reloading of code in development mode without any additional configuration.
4001
+
4002
+ If your API files are in `app/api`, Zeitwerk will automatically autoload and reload them. No additional configuration is needed.
4003
+
4004
+ If you encounter issues with reloading, ensure that:
4005
+
4006
+ 1. Your API files follow Zeitwerk naming conventions (file names should match class names).
4007
+ 2. The `config.enable_reloading` is set to `true` in `config/environments/development.rb` (this is the default).
4008
+
4009
+ For troubleshooting autoloading issues, have a look at the [Rails documentation](https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#troubleshooting).
4010
+
4011
+ See the [Rails Autoloading and Reloading Constants guide](https://guides.rubyonrails.org/autoloading_and_reloading_constants.html) for more information.
4012
+
4013
+ #### Rails 6 and Earlier
4014
+
4015
+ For Rails versions before 7, you need to configure reloading manually.
1239
4016
 
1240
4017
  Add API paths to `config/application.rb`.
1241
4018
 
1242
4019
  ```ruby
1243
4020
  # Auto-load API and its subdirectories
1244
- config.paths.add "app/api", glob: "**/*.rb"
1245
- config.autoload_paths += Dir["#{Rails.root}/app/api/*"]
4021
+ config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
4022
+ config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]
1246
4023
  ```
1247
4024
 
1248
4025
  Create `config/initializers/reload_api.rb`.
1249
4026
 
1250
4027
  ```ruby
1251
4028
  if Rails.env.development?
4029
+ ActiveSupport::Dependencies.explicitly_unloadable_constants << 'Twitter::API'
1252
4030
 
1253
- ActiveSupport::Dependencies.explicitly_unloadable_constants << "Twitter::API"
1254
-
1255
- api_files = Dir["#{Rails.root}/app/api/**/*.rb"]
4031
+ api_files = Dir[Rails.root.join('app', 'api', '**', '*.rb')]
1256
4032
  api_reloader = ActiveSupport::FileUpdateChecker.new(api_files) do
1257
4033
  Rails.application.reload_routes!
1258
4034
  end
1259
- ActionDispatch::Callbacks.to_prepare do
4035
+ ActiveSupport::Reloader.to_prepare do
1260
4036
  api_reloader.execute_if_updated
1261
4037
  end
1262
-
1263
4038
  end
1264
4039
  ```
1265
4040
 
1266
4041
  See [StackOverflow #3282655](http://stackoverflow.com/questions/3282655/ruby-on-rails-3-reload-lib-directory-for-each-request/4368838#4368838) for more information.
1267
4042
 
1268
-
1269
4043
  ## Performance Monitoring
1270
4044
 
1271
- Grape integrates with NewRelic via the
1272
- [newrelic-grape](https://github.com/flyerhzm/newrelic-grape) gem, and
1273
- with Librato Metrics with the [grape-librato](https://github.com/seanmoon/grape-librato) gem.
4045
+ ### Active Support Instrumentation
4046
+
4047
+ Grape has built-in support for [ActiveSupport::Notifications](http://api.rubyonrails.org/classes/ActiveSupport/Notifications.html) which provides simple hook points to instrument key parts of your application.
4048
+
4049
+
4050
+ #### Hook Points
4051
+
4052
+ The following hook points are currently supported:
4053
+
4054
+ ##### endpoint_run.grape
4055
+
4056
+ The main execution of an endpoint, includes filters and rendering.
4057
+
4058
+ * *endpoint* - The endpoint instance
4059
+
4060
+ ##### endpoint_render.grape
4061
+
4062
+ The execution of the main content block of the endpoint.
4063
+
4064
+ * *endpoint* - The endpoint instance
4065
+
4066
+ ##### endpoint_run_filters.grape
4067
+
4068
+ * *endpoint* - The endpoint instance
4069
+ * *filters* - The filters being executed
4070
+ * *type* - The type of filters (before, before_validation, after_validation, after)
4071
+
4072
+ ##### endpoint_run_validators.grape
4073
+
4074
+ The execution of validators.
4075
+
4076
+ * *endpoint* - The endpoint instance
4077
+ * *validators* - The validators being executed
4078
+ * *request* - The request being validated
4079
+
4080
+ ##### format_response.grape
4081
+
4082
+ Serialization or template rendering.
4083
+
4084
+ * *env* - The request environment
4085
+ * *formatter* - The formatter object (e.g., `Grape::Formatter::Json`)
4086
+
4087
+ See the [ActiveSupport::Notifications documentation](http://api.rubyonrails.org/classes/ActiveSupport/Notifications.html) for information on how to subscribe to these events.
4088
+
4089
+ #### Subscribe to Hooks
4090
+
4091
+ Once subscribed to the instrumentation, you can intercept the events reported above.
4092
+
4093
+ ```ruby
4094
+ ActiveSupport::Notifications.subscribe(/<api_path>/) do |name, start, finish, id, payload|
4095
+ # your code to intercept the notification
4096
+ end
4097
+ ```
4098
+
4099
+ The request data, the API’s internal data, and the response can be retrieved from the payload.
4100
+
4101
+ You can use `payload.fetch(:endpoint)` or directly `payload[:endpoint]`.
4102
+
4103
+ The `:endpoint` contains the data currently being processed, and access to attributes such as `body`, `request`, `params`, `headers`, `cookies` and `response_cookies`
4104
+
4105
+ For example, `payload[:endpoint].body` provides the current state of the response.
4106
+
4107
+ ```ruby
4108
+ ActiveSupport::Notifications.subscribe(/v1/) do |name, start, finish, id, payload|
4109
+ hook_record = {
4110
+ hook: name
4111
+ status: payload[:env]&.dig("api.endpoint")&.status
4112
+ format: payload[:env]&.dig("api.format")
4113
+ body: payload[:endpoint]&.body
4114
+ duration: (finish - start) * 1000
4115
+ }
4116
+ # your code to save the notification
4117
+ end
4118
+ ```
4119
+
4120
+ ### Monitoring Products
4121
+
4122
+ Grape integrates with following third-party tools:
4123
+
4124
+ * **New Relic** - [built-in support](https://docs.newrelic.com/docs/agents/ruby-agent/frameworks/grape-instrumentation) from v3.10.0 of the official [newrelic_rpm](https://github.com/newrelic/rpm) gem, also [newrelic-grape](https://github.com/xinminlabs/newrelic-grape) gem
4125
+ * **Librato Metrics** - [grape-librato](https://github.com/seanmoon/grape-librato) gem
4126
+ * **Rails Performance** - [rails_performance](https://github.com/igorkasyanchuk/rails_performance) gem
4127
+ * **[Skylight](https://www.skylight.io/)** - [skylight](https://github.com/skylightio/skylight-ruby) gem, [documentation](https://docs.skylight.io/grape/)
4128
+ * **[AppSignal](https://www.appsignal.com)** - [appsignal-ruby](https://github.com/appsignal/appsignal-ruby) gem, [documentation](http://docs.appsignal.com/getting-started/supported-frameworks.html#grape)
4129
+ * **[ElasticAPM](https://www.elastic.co/products/apm)** - [elastic-apm](https://github.com/elastic/apm-agent-ruby) gem, [documentation](https://www.elastic.co/guide/en/apm/agent/ruby/3.x/getting-started-rack.html#getting-started-grape)
4130
+ * **[Datadog APM](https://docs.datadoghq.com/tracing/)** - [ddtrace](https://github.com/datadog/dd-trace-rb) gem, [documentation](https://docs.datadoghq.com/tracing/setup_overview/setup/ruby/#grape)
1274
4131
 
1275
4132
  ## Contributing to Grape
1276
4133
 
1277
- Grape is work of dozens of contributors. You're encouraged to submit pull requests, propose
1278
- features and discuss issues.
4134
+ Grape is work of hundreds of contributors. You're encouraged to submit pull requests, propose features and discuss issues.
4135
+
4136
+ See [CONTRIBUTING](CONTRIBUTING.md).
4137
+
4138
+ ## Security
1279
4139
 
1280
- * Fork the project
1281
- * Write tests for your new feature or a test that reproduces a bug
1282
- * Implement your feature or make a bug fix
1283
- * Add a line to `CHANGELOG.md` describing your change
1284
- * Commit, push and make a pull request. Bonus points for topic branches.
4140
+ See [SECURITY](SECURITY.md) for details.
1285
4141
 
1286
4142
  ## License
1287
4143
 
1288
- MIT License. See LICENSE for details.
4144
+ MIT License. See [LICENSE](LICENSE) for details.
1289
4145
 
1290
4146
  ## Copyright
1291
4147
 
1292
- Copyright (c) 2010-2013 Michael Bleigh, and Intridea, Inc.
4148
+ Copyright (c) 2010-2020 Michael Bleigh, Intridea Inc. and Contributors.