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/UPGRADING.md ADDED
@@ -0,0 +1,1851 @@
1
+ Upgrading Grape
2
+ ===============
3
+
4
+ ### Upgrading to >= 3.2
5
+
6
+ #### Rack parameter parsing errors now raise `Grape::Exceptions::RequestError`
7
+
8
+ Rack errors raised during parameter parsing (malformed multipart, parameter type conflicts, encoding issues, etc.) are now wrapped in `Grape::Exceptions::RequestError` instead of their previous specific exception classes (`Grape::Exceptions::EmptyMessageBody`, `Grape::Exceptions::TooManyMultipartFiles`, `Grape::Exceptions::TooDeepParameters`, `Grape::Exceptions::ConflictingTypes`, `Grape::Exceptions::InvalidParameters`). Those classes have been removed.
9
+
10
+ If you rescue any of these specific exceptions, update your rescue clauses to use `Grape::Exceptions::RequestError`:
11
+
12
+ ```ruby
13
+ # Before
14
+ rescue Grape::Exceptions::ConflictingTypes, Grape::Exceptions::TooDeepParameters => e
15
+ # ...
16
+
17
+ # After
18
+ rescue Grape::Exceptions::RequestError => e
19
+ # ...
20
+ ```
21
+
22
+ The error message is now forwarded directly from Rack rather than translated through Grape's locale system. On Rack 3, all Rack bad-request errors share the `Rack::BadRequest` marker module and are covered by a single rescue.
23
+
24
+ #### `endpoint_run_validators.grape` notification no longer fired when there are no validators
25
+
26
+ `ActiveSupport::Notifications` subscribers listening to `endpoint_run_validators.grape` will no longer receive an event for endpoints that have no validators. If you rely on this notification to measure every request, subscribe to `endpoint_run.grape` instead, which always fires.
27
+
28
+ #### Custom validators: use `default_message_key` and `validation_error!`
29
+
30
+ Validators are now instantiated once at definition time and frozen. Any setup should happen in `initialize`, not in `validate_param!`.
31
+
32
+ If your custom validator did work in `validate_param!` that only depends on the validator's options (not the param value), move it to `initialize`. A common case is compiling a value derived from options — for example, building a `Regexp`. Previously this may have been cached back into `@options`, which now raises `FrozenError` since `@options` and its nested values are deep-frozen by the base class:
33
+
34
+ **Before:**
35
+ ```ruby
36
+ class MyValidator < Grape::Validations::Validators::Base
37
+ def validate_param!(attr_name, params)
38
+ # raises FrozenError: @options is frozen, cannot store compiled pattern back into it
39
+ @options[:compiled] ||= Regexp.new(@options[:pattern])
40
+ validation_error!(attr_name) unless params[attr_name].match?(@options[:compiled])
41
+ end
42
+ end
43
+ ```
44
+
45
+ **After:**
46
+ ```ruby
47
+ class MyValidator < Grape::Validations::Validators::Base
48
+ def initialize(attrs, options, required, scope, opts)
49
+ super
50
+ @pattern = Regexp.new(@options[:pattern]).freeze
51
+ end
52
+
53
+ def validate_param!(attr_name, params)
54
+ validation_error!(attr_name) unless params[attr_name].match?(@pattern)
55
+ end
56
+ end
57
+ ```
58
+
59
+ Any Array or Hash derived from options and stored in an ivar should be frozen, since the validator instance is shared across requests. `@options` itself (and any nested Hash/Array/String values within it) is deep-frozen by the base class, so mutations like `@options[:values] << 'extra'` will also raise a `FrozenError`.
60
+
61
+ #### Custom validators: rename `@option` to `@options`
62
+
63
+ The instance variable holding the validator's option value has been renamed from `@option` to `@options`. `@option` remains as an alias for backwards compatibility but will be removed in the next major release. Update any custom validators to use `@options` instead.
64
+
65
+ Several new helpers are available — see [Available helpers](README.md#available-helpers) in the README for full documentation and examples.
66
+
67
+ #### `with` now uses keyword arguments
68
+
69
+ The `with` DSL method now uses `**opts` instead of a positional hash. Calls using bare keyword syntax are unaffected:
70
+
71
+ ```ruby
72
+ # still works
73
+ with(type: String, documentation: { in: 'body' }) { ... }
74
+ ```
75
+
76
+ However, passing an explicit hash literal will now raise an `ArgumentError`:
77
+
78
+ ```ruby
79
+ # raises ArgumentError
80
+ with({ type: String }) { ... }
81
+ ```
82
+
83
+ See [#2663](https://github.com/ruby-grape/grape/pull/2663) for more information.
84
+
85
+ #### Custom validators: use `translate` instead of `I18n` directly
86
+
87
+ `Grape::Util::Translation` is now included in `Grape::Validations::Validators::Base`. Custom validators that previously called `I18n.t` or `I18n.translate` directly should switch to the `translate`, which provides the same `:en` fallback logic used by all built-in validators.
88
+
89
+ Key points:
90
+ - `scope` defaults to `'grape.errors.messages'` — no need to specify it for standard error message keys.
91
+ - Interpolation variables are passed directly to I18n.
92
+ - `format` is no longer needed — `translate` returns the fully interpolated string.
93
+
94
+ ```ruby
95
+ # Before
96
+ raise Grape::Exceptions::Validation.new(
97
+ params: [@scope.full_name(attr_name)],
98
+ message: format(I18n.t(:my_key, scope: 'grape.errors.messages'), min: 2, max: 10)
99
+ )
100
+
101
+ # After
102
+ raise Grape::Exceptions::Validation.new(
103
+ params: [@scope.full_name(attr_name)],
104
+ message: translate(:my_key, min: 2, max: 10)
105
+ )
106
+ ```
107
+
108
+ See [#2662](https://github.com/ruby-grape/grape/pull/2662) for more information.
109
+
110
+ ### Upgrading to >= 3.1
111
+
112
+ #### Explicit kwargs for `namespace` and `route_param`
113
+
114
+ The `API#namespace` and `route_param` methods are now defined with `**options` instead of `options = {}`. In addtion, `requirements` in explicitly defined so it's not in `options` anymore. You can still call `requirements` like before but `options[:requirements]` will be empty. For `route_param`, `type` is also an explicit parameter so it's not in `options` anymore. See [#2647](https://github.com/ruby-grape/grape/pull/2647) for more information.
115
+
116
+ #### ParamsBuilder Grape::Extensions
117
+
118
+ Deprecated [ParamsBuilder's extensions](https://github.com/ruby-grape/grape/blob/master/UPGRADING.md#params-builder) have been removed.
119
+
120
+ #### Enhanced API compile!
121
+
122
+ Endpoints are now "compiled" instead of lazy loaded. Historically, when calling `YourAPI.compile!` in `config.ru` (or just receiving the first API call), only routing was compiled see [Grape::Router#compile!](https://github.com/ruby-grape/grape/blob/bf90e95c3b17c415c944363b1c07eb9727089ee7/lib/grape/router.rb#L41-L54) and endpoints were lazy loaded. Now, it's part of the API compilation. See [#2645](https://github.com/ruby-grape/grape/pull/2645) for more information.
123
+
124
+ ### Upgrading to >= 3.0.0
125
+
126
+ #### Ruby 3+ Argument Delegation Modernization
127
+
128
+ Grape has been modernized to use Ruby 3+'s preferred argument delegation patterns. This change replaces `args.extract_options!` with explicit `**kwargs` parameters throughout the codebase.
129
+
130
+ - All DSL methods now use explicit keyword arguments (`**kwargs`) instead of extracting options from mixed argument lists
131
+ - Method signatures are now more explicit and follow Ruby 3+ best practices
132
+ - The `active_support/core_ext/array/extract_options` dependency has been removed
133
+
134
+ This is a modernization effort that improves code quality while maintaining full backward compatibility.
135
+
136
+ See [#2618](https://github.com/ruby-grape/grape/pull/2618) for more information.
137
+
138
+ #### Configuration API Migration from ActiveSupport::Configurable to Dry::Configurable
139
+
140
+ Grape has migrated from `ActiveSupport::Configurable` to `Dry::Configurable` for its configuration system since its [deprecated](https://github.com/rails/rails/blob/1cdd190a25e483b65f1f25bbd0f13a25d696b461/activesupport/lib/active_support/configurable.rb#L3-L7).
141
+
142
+ See [#2617](https://github.com/ruby-grape/grape/pull/2617) for more information.
143
+
144
+ #### Endpoint execution simplified and `return` deprecated
145
+
146
+ Executing a endpoint's block has been simplified and calling `return` in it has been deprecated. Use `next` instead.
147
+
148
+ See [#2577](https://github.com/ruby-grape/grape/pull/2577) for more information.
149
+
150
+ #### Old Deprecations Clean Up
151
+
152
+ - `rack_response` has been removed in favor of using `error!`.
153
+ - `Grape::Exceptions::MissingGroupType` and `Grape::Exceptions::UnsupportedGroupType` aliases `MissingGroupTypeError and `UnsupportedGroupType` have been removed.
154
+ - `Grape::Validations::Base` has been removed in favor of `Grape::Validations::Validators::Base`.
155
+
156
+ See [2573](https://github.com/ruby-grape/grape/pull/2573) for more information.
157
+
158
+ ### Upgrading to >= 2.4.0
159
+
160
+ #### Grape::Middleware::Auth::Base
161
+ `type` is now validated at compile time and will raise a `Grape::Exceptions::UnknownAuthStrategy` if unknown.
162
+
163
+ #### Grape::Middleware::Base
164
+
165
+ - Second argument `options` is now a double splat (**) instead of single splat (*). If you're redefining `initialize` in your middleware and/or calling `super` in it, you might have to adapt the signature and the `super` call. Also, you might have to remove `{}` if you're pass `options` as a literal `Hash` or add `**` if you're using a variable.
166
+ - `Grape::Middleware::Helpers` has been removed. The equivalent method `context` is now part of `Grape::Middleware::Base`.
167
+
168
+ #### Grape::Http::Headers, Grape::Util::Lazy::Object
169
+
170
+ Both have been removed. See [2554](https://github.com/ruby-grape/grape/pull/2554).
171
+ Here are the notable changes:
172
+
173
+ - Constants like `HTTP_ACCEPT` have been replaced by their literal value.
174
+ - `SUPPORTED_METHODS` has been moved to `Grape` module.
175
+ - `HTTP_HEADERS` has been moved to `Grape::Request` and renamed `KNOWN_HEADERS`. The last has been refreshed with new headers, and it's not lazy anymore.
176
+ - `SUPPORTED_METHODS_WITHOUT_OPTIONS` and `find_supported_method` have been removed.
177
+
178
+ #### Grape::Middleware::Base
179
+
180
+ - Constant `TEXT_HTML` has been removed in favor of using literal string 'text/html'.
181
+ - `rack_request` and `query_params` have been added. Feel free to call these in your middlewares.
182
+
183
+ #### Params Builder
184
+
185
+ - Passing a class to `build_with` or `Grape.config.param_builder` has been deprecated in favor of a symbolized short_name. See `SHORTNAME_LOOKUP` in [params_builder](lib/grape/params_builder.rb).
186
+ - Including Grape's extensions like `Grape::Extensions::Hashie::Mash::ParamBuilder` has been deprecated in favor of using `build_with` at the route level.
187
+
188
+ #### Accept Header Negotiation Harmonized
189
+
190
+ [Accept](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Accept) header is now fully interpreted through `Rack::Utils.best_q_match` which is following [RFC2616 14.1](https://datatracker.ietf.org/doc/html/rfc2616#section-14.1). Since [Grape 2.1.0](https://github.com/ruby-grape/grape/blob/master/CHANGELOG.md#210-20240615), the [header versioning strategy](https://github.com/ruby-grape/grape?tab=readme-ov-file#header) was adhering to it, but `Grape::Middleware::Formatter` never did.
191
+
192
+ Your API might act differently since it will strictly follow the [RFC2616 14.1](https://datatracker.ietf.org/doc/html/rfc2616#section-14.1) when interpreting the `Accept` header. Here are the differences:
193
+
194
+ ##### Invalid or missing quality ranking
195
+ The following used to yield `application/xml` and now will yield `application/json` as the preferred media type:
196
+ - `application/json;q=invalid,application/xml;q=0.5`
197
+ - `application/json,application/xml;q=1.0`
198
+
199
+ For the invalid case, the value `invalid` was automatically `to_f` and `invalid.to_f` equals `0.0`. Now, since it doesn't match [Rack's regex](https://github.com/rack/rack/blob/3-1-stable/lib/rack/utils.rb#L138), its interpreted as non provided and its quality ranking equals 1.0.
200
+
201
+ For the non provided case, 1.0 was automatically assigned and in a case of multiple best matches, the first was returned based on Ruby's sort_by `quality`. Now, 1.0 is still assigned and the last is returned in case of multiple best matches. See [Rack's implementation](https://github.com/rack/rack/blob/e8f47608668d507e0f231a932fa37c9ca551c0a5/lib/rack/utils.rb#L167) of the RFC.
202
+
203
+ ##### Considering the closest generic when vendor tree
204
+ Excluding the [header versioning strategy](https://github.com/ruby-grape/grape?tab=readme-ov-file#header), whenever a media type with the [vendor tree](https://datatracker.ietf.org/doc/html/rfc6838#section-3.2) leading facet `vnd.` like `application/vnd.api+json` was provided, Grape would also consider its closest generic when negotiating. In that case, `application/json` was added to the negotiation. Now, it will just consider the provided media types without considering any closest generics, and you'll need to [register](https://github.com/ruby-grape/grape?tab=readme-ov-file#api-formats) it.
205
+ You can find the official vendor tree registrations on [IANA](https://www.iana.org/assignments/media-types/media-types.xhtml)
206
+
207
+ #### Custom Validators
208
+
209
+ If you now receive an error of `'Grape::Validations.require_validator': unknown validator: your_custom_validation (Grape::Exceptions::UnknownValidator)` after upgrading to 2.4.0 then you will need to ensure that you require the `your_custom_validation` file before your Grape API code is loaded.
210
+
211
+ See [2533](https://github.com/ruby-grape/grape/issues/2533) for more information.
212
+
213
+ ### Upgrading to >= 2.3.0
214
+
215
+ ### `content_type` vs `api.format` inside API
216
+
217
+ Before 2.3.0, `content_type` had priority over `env['api.format']` when set in an API, which was incorrect. The priority has been flipped and `env['api.format']` will be checked first.
218
+ In addition, the function `api_format` has been added. Instead of setting `env['api.format']` directly, you can call `api_format`.
219
+ See [#2506](https://github.com/ruby-grape/grape/pull/2506) for more information.
220
+
221
+ #### Remove Deprecated Methods and Options
222
+
223
+ - Deprecated `file` method has been removed. Use `send_file` or `stream`.
224
+ See [#2500](https://github.com/ruby-grape/grape/pull/2500) for more information.
225
+
226
+ - The `except` and `proc` options have been removed from the `values` validator. Use `except_values` validator or assign `proc` directly to `values`.
227
+ See [#2501](https://github.com/ruby-grape/grape/pull/2501) for more information.
228
+
229
+ - `Passing an options hash and a block to 'desc'` deprecation has been removed. Move all hash options to block instead.
230
+ See [#2502](https://github.com/ruby-grape/grape/pull/2502) for more information.
231
+
232
+ ### Upgrading to >= 2.2.0
233
+
234
+ ### `Length` validator
235
+
236
+ After Grape 2.2.0, `length` validator will only take effect for parameters with types that support `#length` method, will not throw `ArgumentError` exception.
237
+
238
+ See [#2464](https://github.com/ruby-grape/grape/pull/2464) for more information.
239
+
240
+ ### Upgrading to >= 2.1.0
241
+
242
+ #### Optional Builder
243
+
244
+ The `builder` gem dependency has been made optional as it's only used when generating XML. If your code does, add `builder` to your `Gemfile`.
245
+
246
+ See [#2445](https://github.com/ruby-grape/grape/pull/2445) for more information.
247
+
248
+ #### Deep Merging of Parameter Attributes
249
+
250
+ Grape now uses `deep_merge` to combine parameter attributes within the `with` method. Previously, attributes defined at the parameter level would override those defined at the group level.
251
+ With deep merge, attributes are now combined, allowing for more detailed and nuanced API specifications.
252
+
253
+ For example:
254
+
255
+ ```ruby
256
+ with(documentation: { in: 'body' }) do
257
+ optional :vault, documentation: { default: 33 }
258
+ end
259
+ ```
260
+
261
+ Before it was equivalent to:
262
+
263
+ ```ruby
264
+ optional :vault, documentation: { default: 33 }
265
+ ```
266
+
267
+ After it is an equivalent of:
268
+
269
+ ```ruby
270
+ optional :vault, documentation: { in: 'body', default: 33 }
271
+ ```
272
+
273
+ See [#2432](https://github.com/ruby-grape/grape/pull/2432) for more information.
274
+
275
+ #### Zeitwerk
276
+
277
+ Grape's autoloader has been updated and it's now based on [Zeitwerk](https://github.com/fxn/zeitwerk).
278
+ If you MP (Monkey Patch) some files and you're not following the [file structure](https://github.com/fxn/zeitwerk?tab=readme-ov-file#file-structure), you might end up with a Zeitwerk error.
279
+
280
+ See [#2363](https://github.com/ruby-grape/grape/pull/2363) for more information.
281
+
282
+ #### Changes in rescue_from
283
+
284
+ The `rack_response` method has been deprecated and the `error_response` method has been removed. Use `error!` instead.
285
+
286
+ See [#2414](https://github.com/ruby-grape/grape/pull/2414) for more information.
287
+
288
+ #### Change in parameters precedence
289
+
290
+ When using together with `Grape::Extensions::Hash::ParamBuilder`, `route_param` takes higher precedence over a regular parameter defined with same name, which now matches the default param builder behavior.
291
+
292
+ This was a regression introduced by [#2326](https://github.com/ruby-grape/grape/pull/2326) in Grape v1.8.0.
293
+
294
+ ```ruby
295
+ Grape.configure do |config|
296
+ config.param_builder = Grape::Extensions::Hash::ParamBuilder
297
+ end
298
+
299
+ params do
300
+ requires :foo, type: String
301
+ end
302
+ route_param :foo do
303
+ get do
304
+ { value: params[:foo] }
305
+ end
306
+ end
307
+ ```
308
+
309
+ Request:
310
+
311
+ ```bash
312
+ curl -X POST -H "Content-Type: application/json" localhost:9292/bar -d '{"foo": "baz"}'
313
+ ```
314
+
315
+ Response prior to v1.8.0:
316
+
317
+ ```json
318
+ {
319
+ "value": "bar"
320
+ }
321
+ ```
322
+
323
+ v1.8.0..v2.0.0:
324
+
325
+ ```json
326
+ {
327
+ "value": "baz"
328
+ }
329
+ ```
330
+
331
+ v2.1.0+:
332
+
333
+ ```json
334
+ {
335
+ "value": "bar"
336
+ }
337
+ ```
338
+
339
+ See [#2378](https://github.com/ruby-grape/grape/pull/2378) for details.
340
+
341
+ #### Grape::Router::Route.route_xxx methods have been removed
342
+
343
+ - `route_method` is accessible through `request_method`
344
+ - `route_path` is accessible through `path`
345
+ - Any other `route_xyz` are accessible through `options[xyz]`
346
+
347
+ #### Instance variables scope
348
+
349
+ Due to the changes done in [#2377](https://github.com/ruby-grape/grape/pull/2377), the instance variables defined inside each of the endpoints (or inside a `before` validator) are now accessible inside the `rescue_from`. The behavior of the instance variables was undefined until `2.1.0`.
350
+
351
+ If you were using the same variable name defined inside an endpoint or `before` validator inside a `rescue_from` handler, you need to take in mind that you can start getting different values or you can be overriding values.
352
+
353
+ Before:
354
+ ```ruby
355
+ class TwitterAPI < Grape::API
356
+ before do
357
+ @var = 1
358
+ end
359
+
360
+ get '/' do
361
+ puts @var # => 1
362
+ raise
363
+ end
364
+
365
+ rescue_from :all do
366
+ puts @var # => nil
367
+ end
368
+ end
369
+ ```
370
+
371
+ After:
372
+ ```ruby
373
+ class TwitterAPI < Grape::API
374
+ before do
375
+ @var = 1
376
+ end
377
+
378
+ get '/' do
379
+ puts @var # => 1
380
+ raise
381
+ end
382
+
383
+ rescue_from :all do
384
+ puts @var # => 1
385
+ end
386
+ end
387
+ ```
388
+
389
+ #### Recognizing Path
390
+
391
+ Grape now considers the types of the configured `route_params` in order to determine the endpoint that matches with the performed request.
392
+
393
+ So taking into account this `Grape::API` class
394
+
395
+ ```ruby
396
+ class Books < Grape::API
397
+ resource :books do
398
+ route_param :id, type: Integer do
399
+ # GET /books/:id
400
+ get do
401
+ #...
402
+ end
403
+ end
404
+
405
+ resource :share do
406
+ # POST /books/share
407
+ post do
408
+ # ....
409
+ end
410
+ end
411
+ end
412
+ end
413
+ ```
414
+
415
+ Before:
416
+ ```ruby
417
+ API.recognize_path '/books/1' # => /books/:id
418
+ API.recognize_path '/books/share' # => /books/:id
419
+ API.recognize_path '/books/other' # => /books/:id
420
+ ```
421
+
422
+ After:
423
+ ```ruby
424
+ API.recognize_path '/books/1' # => /books/:id
425
+ API.recognize_path '/books/share' # => /books/share
426
+ API.recognize_path '/books/other' # => nil
427
+ ```
428
+
429
+ This implies that before this changes, when you performed `/books/other` and it matched with the `/books/:id` endpoint, you get a `400 Bad Request` response because the type of the provided `:id` param was not an `Integer`. However, after upgrading to version `2.1.0` you will get a `404 Not Found` response, because there is not a defined endpoint that matches with `/books/other`.
430
+
431
+ See [#2379](https://github.com/ruby-grape/grape/pull/2379) for more information.
432
+
433
+ ### Upgrading to >= 2.0.0
434
+
435
+ #### Headers
436
+
437
+ As per [rack/rack#1592](https://github.com/rack/rack/issues/1592) Rack 3 is following the HTTP/2+ semantics which require header names to be lower case. To avoid compatibility issues, starting with Grape 1.9.0, headers will be cased based on what version of Rack you are using.
438
+
439
+ Given this request:
440
+
441
+ ```shell
442
+ curl -H "Content-Type: application/json" -H "Secret-Password: foo" ...
443
+ ```
444
+
445
+ If you are using Rack 3 in your application then the headers will be set to:
446
+
447
+ ```ruby
448
+ { "content-type" => "application/json", "secret-password" => "foo"}
449
+ ```
450
+
451
+ This means if you are checking for header values in your application, you would need to change your code to use downcased keys.
452
+
453
+ ```ruby
454
+ get do
455
+ # This would use headers['Secret-Password'] in Rack < 3
456
+ error!('Unauthorized', 401) unless headers['secret-password'] == 'swordfish'
457
+ end
458
+ ```
459
+
460
+ See [#2355](https://github.com/ruby-grape/grape/pull/2355) for more information.
461
+
462
+ #### Digest auth deprecation
463
+
464
+ Digest auth has been removed along with the deprecation of `Rack::Auth::Digest` in Rack 3.
465
+
466
+ See [#2294](https://github.com/ruby-grape/grape/issues/2294) for more information.
467
+
468
+ ### Upgrading to >= 1.7.0
469
+
470
+ #### Exceptions renaming
471
+
472
+ The following exceptions has been renamed for consistency through exceptions naming :
473
+
474
+ * `MissingGroupTypeError` => `MissingGroupType`
475
+ * `UnsupportedGroupTypeError` => `UnsupportedGroupType`
476
+
477
+ See [#2227](https://github.com/ruby-grape/grape/pull/2227) for more information.
478
+
479
+ #### Handling Multipart Limit Errors
480
+
481
+ Rack supports a configurable limit on the number of files created from multipart parameters (`Rack::Utils.multipart_part_limit`) and raises an error if params are received that create too many files. If you were handling the Rack error directly, Grape now wraps that error in `Grape::Execeptions::TooManyMultipartFiles`. Additionally, Grape will return a 413 status code if the exception goes unhandled.
482
+
483
+ ### Upgrading to >= 1.6.0
484
+
485
+ #### Parameter renaming with :as
486
+
487
+ Prior to 1.6.0 the [parameter renaming](https://github.com/ruby-grape/grape#renaming) with `:as` was directly touching the request payload ([`#params`](https://github.com/ruby-grape/grape#parameters)) while duplicating the old and the new key to be both available in the hash. This allowed clients to bypass any validation in case they knew the internal name of the parameter. Unfortunately, in combination with [grape-swagger](https://github.com/ruby-grape/grape-swagger) the internal name (name set with `:as`) of the parameters were documented.
488
+
489
+ This behavior was fixed. Parameter renaming is now done when using the [`#declared(params)`](https://github.com/ruby-grape/grape#declared) parameters helper. This stops confusing validation/coercion behavior.
490
+
491
+ Here comes an illustration of the old and new behaviour as code:
492
+
493
+ ```ruby
494
+ # (1) Rename a to b, while client sends +a+
495
+ optional :a, type: Integer, as: :b
496
+ params = { a: 1 }
497
+ declared(params, include_missing: false)
498
+ # expected => { b: 1 }
499
+ # actual => { b: 1 }
500
+
501
+ # (2) Rename a to b, while client sends +b+
502
+ optional :a, type: Integer, as: :b, values: [1, 2, 3]
503
+ params = { b: '5' }
504
+ declared(params, include_missing: false)
505
+ # expected => { } (>= 1.6.0)
506
+ # actual => { b: '5' } (uncasted, unvalidated, <= 1.5.3)
507
+ ```
508
+
509
+ Another implication of this change is the dependent parameter resolution. Prior to 1.6.0 the following code produced a `Grape::Exceptions::UnknownParameter` because `:a` was replaced by `:b`:
510
+
511
+ ```ruby
512
+ params do
513
+ optional :a, as: :b
514
+ given :a do # (<= 1.5.3 you had to reference +:b+ here to make it work)
515
+ requires :c
516
+ end
517
+ end
518
+ ```
519
+
520
+ This code now works without any errors, as the renaming is just an internal behaviour of the `#declared(params)` parameter helper.
521
+
522
+ See [#2189](https://github.com/ruby-grape/grape/pull/2189) for more information.
523
+
524
+ ### Upgrading to >= 1.5.3
525
+
526
+ #### Nil value and coercion
527
+
528
+ Prior to 1.2.5 version passing a `nil` value for a parameter with a custom coercer would invoke the coercer, and not passing a parameter would not invoke it.
529
+ This behavior was not tested or documented. Version 1.3.0 quietly changed this behavior, in that `nil` values skipped the coercion. Version 1.5.3 fixes and documents this as follows:
530
+
531
+ ```ruby
532
+ class Api < Grape::API
533
+ params do
534
+ optional :value, type: Integer, coerce_with: ->(val) { val || 0 }
535
+ end
536
+
537
+ get 'example' do
538
+ params[:my_param]
539
+ end
540
+ get '/example', params: { value: nil }
541
+ # 1.5.2 = nil
542
+ # 1.5.3 = 0
543
+ get '/example', params: {}
544
+ # 1.5.2 = nil
545
+ # 1.5.3 = nil
546
+ end
547
+ ```
548
+ See [#2164](https://github.com/ruby-grape/grape/pull/2164) for more information.
549
+
550
+ ### Upgrading to >= 1.5.1
551
+
552
+ #### Dependent params
553
+
554
+ If you use [dependent params](https://github.com/ruby-grape/grape#dependent-parameters) with
555
+ `Grape::Extensions::Hash::ParamBuilder`, make sure a parameter to be dependent on is set as a Symbol.
556
+ If a String is given, a parameter that other parameters depend on won't be found even if it is present.
557
+
558
+ _Correct_:
559
+ ```ruby
560
+ given :matrix do
561
+ # dependent params
562
+ end
563
+ ```
564
+
565
+ _Wrong_:
566
+ ```ruby
567
+ given 'matrix' do
568
+ # dependent params
569
+ end
570
+ ```
571
+
572
+ ### Upgrading to >= 1.5.0
573
+
574
+ Prior to 1.3.3, the `declared` helper would always return the complete params structure if `include_missing=true` was set. In 1.3.3 a regression was introduced such that a missing Hash with or without nested parameters would always resolve to `{}`.
575
+
576
+ In 1.5.0 this behavior is reverted, so the whole params structure will always be available via `declared`, regardless of whether any params are passed.
577
+
578
+ The following rules now apply to the `declared` helper when params are missing and `include_missing=true`:
579
+
580
+ * Hash params with children will resolve to a Hash with keys for each declared child.
581
+ * Hash params with no children will resolve to `{}`.
582
+ * Set params will resolve to `Set.new`.
583
+ * Array params will resolve to `[]`.
584
+ * All other params will resolve to `nil`.
585
+
586
+ #### Example
587
+
588
+ ```ruby
589
+ class Api < Grape::API
590
+ params do
591
+ optional :outer, type: Hash do
592
+ optional :inner, type: Hash do
593
+ optional :value, type: String
594
+ end
595
+ end
596
+ end
597
+ get 'example' do
598
+ declared(params, include_missing: true)
599
+ end
600
+ end
601
+ ```
602
+
603
+ ```
604
+ get '/example'
605
+ # 1.3.3 = {}
606
+ # 1.5.0 = {outer: {inner: {value:null}}}
607
+ ```
608
+
609
+ For more information see [#2103](https://github.com/ruby-grape/grape/pull/2103).
610
+
611
+ ### Upgrading to >= 1.4.0
612
+
613
+ #### Reworking stream and file and un-deprecating stream like-objects
614
+
615
+ Previously in 0.16 stream-like objects were deprecated. This release restores their functionality for use-cases other than file streaming.
616
+
617
+ This release deprecated `file` in favor of `sendfile` to better document its purpose.
618
+
619
+ To deliver a file via the Sendfile support in your web server and have the Rack::Sendfile middleware enabled. See [`Rack::Sendfile`](https://www.rubydoc.info/gems/rack/Rack/Sendfile).
620
+ ```ruby
621
+ class API < Grape::API
622
+ get '/' do
623
+ sendfile '/path/to/file'
624
+ end
625
+ end
626
+ ```
627
+
628
+ Use `stream` to stream file content in chunks.
629
+
630
+ ```ruby
631
+ class API < Grape::API
632
+ get '/' do
633
+ stream '/path/to/file'
634
+ end
635
+ end
636
+ ```
637
+
638
+ Or use `stream` to stream other kinds of content. In the following example a streamer class
639
+ streams paginated data from a database.
640
+
641
+ ```ruby
642
+ class MyObject
643
+ attr_accessor :result
644
+
645
+ def initialize(query)
646
+ @result = query
647
+ end
648
+
649
+ def each
650
+ yield '['
651
+ # Do paginated DB fetches and return each page formatted
652
+ first = false
653
+ result.find_in_batches do |records|
654
+ yield process_records(records, first)
655
+ first = false
656
+ end
657
+ yield ']'
658
+ end
659
+
660
+ def process_records(records, first)
661
+ buffer = +''
662
+ buffer << ',' unless first
663
+ buffer << records.map(&:to_json).join(',')
664
+ buffer
665
+ end
666
+ end
667
+
668
+ class API < Grape::API
669
+ get '/' do
670
+ stream MyObject.new(Sprocket.all)
671
+ end
672
+ end
673
+ ```
674
+
675
+ ### Upgrading to >= 1.3.3
676
+
677
+ #### Nil values for structures
678
+
679
+ Nil values have always been a special case when dealing with types, especially with the following structures:
680
+
681
+ - Array
682
+ - Hash
683
+ - Set
684
+
685
+ The behavior for these structures has changed throughout the latest releases. For example:
686
+
687
+ ```ruby
688
+ class Api < Grape::API
689
+ params do
690
+ require :my_param, type: Array[Integer]
691
+ end
692
+
693
+ get 'example' do
694
+ params[:my_param]
695
+ end
696
+ get '/example', params: { my_param: nil }
697
+ # 1.3.1 = []
698
+ # 1.3.2 = nil
699
+ end
700
+ ```
701
+
702
+ For now on, `nil` values stay `nil` values for all types, including arrays, sets and hashes.
703
+
704
+ If you want to have the same behavior as 1.3.1, apply a `default` validator:
705
+
706
+ ```ruby
707
+ class Api < Grape::API
708
+ params do
709
+ require :my_param, type: Array[Integer], default: []
710
+ end
711
+
712
+ get 'example' do
713
+ params[:my_param]
714
+ end
715
+ get '/example', params: { my_param: nil } # => []
716
+ end
717
+ ```
718
+
719
+ #### Default validator
720
+
721
+ Default validator is now applied for `nil` values.
722
+
723
+ ```ruby
724
+ class Api < Grape::API
725
+ params do
726
+ requires :my_param, type: Integer, default: 0
727
+ end
728
+
729
+ get 'example' do
730
+ params[:my_param]
731
+ end
732
+ get '/example', params: { my_param: nil } #=> before: nil, after: 0
733
+ end
734
+ ```
735
+
736
+ ### Upgrading to >= 1.3.0
737
+
738
+ You will need to upgrade to this version if you depend on `rack >= 2.1.0`.
739
+
740
+ #### Ruby
741
+
742
+ After adding dry-types, Ruby 2.4 or newer is required.
743
+
744
+ #### Coercion
745
+
746
+ [Virtus](https://github.com/solnic/virtus) has been replaced by [dry-types](https://dry-rb.org/gems/dry-types/1.2/) for parameter coercion. If your project depends on Virtus outside of Grape, explicitly add it to your `Gemfile`.
747
+
748
+ Here's an example of how to migrate a custom type from Virtus to dry-types:
749
+
750
+ ```ruby
751
+ # Legacy Grape parser
752
+ class SecureUriType < Virtus::Attribute
753
+ def coerce(input)
754
+ URI.parse value
755
+ end
756
+
757
+ def value_coerced?(input)
758
+ value.is_a? String
759
+ end
760
+ end
761
+
762
+ params do
763
+ requires :secure_uri, type: SecureUri
764
+ end
765
+ ```
766
+
767
+ To use dry-types, we need to:
768
+
769
+ 1. Remove the inheritance of `Virtus::Attribute`
770
+ 1. Rename `coerce` to `self.parse`
771
+ 1. Rename `value_coerced?` to `self.parsed?`
772
+
773
+ The custom type must have a class-level `parse` method to the model. A class-level `parsed?` is needed if the parsed type differs from the defined type. In the example below, since `SecureUri` is not the same as `URI::HTTPS`, `self.parsed?` is needed:
774
+
775
+ ```ruby
776
+ # New dry-types parser
777
+ class SecureUri
778
+ def self.parse(value)
779
+ URI.parse value
780
+ end
781
+
782
+ def self.parsed?(value)
783
+ value.is_a? URI::HTTPS
784
+ end
785
+ end
786
+
787
+ params do
788
+ requires :secure_uri, type: SecureUri
789
+ end
790
+ ```
791
+
792
+ #### Coercing to `FalseClass` or `TrueClass` no longer works
793
+
794
+ Previous Grape versions allowed this, though it wasn't documented:
795
+
796
+ ```ruby
797
+ requires :true_value, type: TrueClass
798
+ requires :bool_value, types: [FalseClass, TrueClass]
799
+ ```
800
+
801
+ This is no longer supported, if you do this, your values will never be valid. Instead you should do this:
802
+
803
+ ```ruby
804
+ requires :true_value, type: Boolean # in your endpoint you should validate if this is actually `true`
805
+ requires :bool_value, type: Boolean
806
+ ```
807
+
808
+ #### Ensure that Array types have explicit coercions
809
+
810
+ Unlike Virtus, dry-types does not perform any implict coercions. If you have any uses of `Array[String]`, `Array[Integer]`, etc. be sure they use a `coerce_with` block. For example:
811
+
812
+ ```ruby
813
+ requires :values, type: Array[String]
814
+ ```
815
+
816
+ It's quite common to pass a comma-separated list, such as `tag1,tag2` as `values`. Previously Virtus would implicitly coerce this to `Array(values)` so that `["tag1,tag2"]` would pass the type checks, but with `dry-types` the values are no longer coerced for you. To fix this, you might do:
817
+
818
+ ```ruby
819
+ requires :values, type: Array[String], coerce_with: ->(val) { val.split(',').map(&:strip) }
820
+ ```
821
+
822
+ Likewise, for `Array[Integer]`, you might do:
823
+
824
+ ```ruby
825
+ requires :values, type: Array[Integer], coerce_with: ->(val) { val.split(',').map(&:strip).map(&:to_i) }
826
+ ```
827
+
828
+ For more information see [#1920](https://github.com/ruby-grape/grape/pull/1920).
829
+
830
+ ### Upgrading to >= 1.2.4
831
+
832
+ #### Headers in `error!` call
833
+
834
+ Headers in `error!` will be merged with `headers` hash. If any header need to be cleared on `error!` call, make sure to move it to the `after` block.
835
+
836
+ ```ruby
837
+ class SampleApi < Grape::API
838
+ before do
839
+ header 'X-Before-Header', 'before_call'
840
+ end
841
+
842
+ get 'ping' do
843
+ header 'X-App-Header', 'on_call'
844
+ error! :pong, 400, 'X-Error-Details' => 'Invalid token'
845
+ end
846
+ end
847
+ ```
848
+ **Former behaviour**
849
+ ```ruby
850
+ response.headers['X-Before-Header'] # => nil
851
+ response.headers['X-App-Header'] # => nil
852
+ response.headers['X-Error-Details'] # => Invalid token
853
+ ```
854
+
855
+ **Current behaviour**
856
+ ```ruby
857
+ response.headers['X-Before-Header'] # => 'before_call'
858
+ response.headers['X-App-Header'] # => 'on_call'
859
+ response.headers['X-Error-Details'] # => Invalid token
860
+ ```
861
+
862
+ ### Upgrading to >= 1.2.1
863
+
864
+ #### Obtaining the name of a mounted class
865
+
866
+ In order to make obtaining the name of a mounted class simpler, we've delegated `.to_s` to `base.name`
867
+
868
+ **Deprecated in 1.2.0**
869
+ ```ruby
870
+ payload[:endpoint].options[:for].name
871
+ ```
872
+ **New**
873
+ ```ruby
874
+ payload[:endpoint].options[:for].to_s
875
+ ```
876
+
877
+ ### Upgrading to >= 1.2.0
878
+
879
+ #### Changes in the Grape::API class
880
+
881
+ ##### Patching the class
882
+
883
+ In an effort to make APIs re-mountable, The class `Grape::API` no longer refers to an API instance, rather, what used to be `Grape::API` is now `Grape::API::Instance` and `Grape::API` was replaced with a class that can contain several instances of `Grape::API`.
884
+
885
+ This changes were done in such a way that no code-changes should be required. However, if experiencing problems, or relying on private methods and internal behaviour too deeply, it is possible to restore the prior behaviour by replacing the references from `Grape::API` to `Grape::API::Instance`.
886
+
887
+ Note, this is particularly relevant if you are opening the class `Grape::API` for modification.
888
+
889
+ **Deprecated**
890
+ ```ruby
891
+ class Grape::API
892
+ # your patched logic
893
+ ...
894
+ end
895
+ ```
896
+ **New**
897
+ ```ruby
898
+ class Grape::API::Instance
899
+ # your patched logic
900
+ ...
901
+ end
902
+ ```
903
+
904
+ ##### `name` (and other caveats) of the mounted API
905
+
906
+ After the patch, the mounted API is no longer a Named class inheriting from `Grape::API`, it is an anonymous class which inherit from `Grape::API::Instance`.
907
+
908
+ What this means in practice, is:
909
+
910
+ - Generally: you can access the named class from the instance calling the getter `base`.
911
+ - In particular: If you need the `name`, you can use `base`.`name`.
912
+
913
+ **Deprecated**
914
+
915
+ ```ruby
916
+ payload[:endpoint].options[:for].name
917
+ ```
918
+
919
+ **New**
920
+
921
+ ```ruby
922
+ payload[:endpoint].options[:for].base.name
923
+ ```
924
+
925
+ #### Changes in rescue_from returned object
926
+
927
+ Grape will now check the object returned from `rescue_from` and ensure that it is a `Rack::Response`. That makes sure response is valid and avoids exposing service information. Change any code that invoked `Rack::Response.new(...).finish` in a custom `rescue_from` block to `Rack::Response.new(...)` to comply with the validation.
928
+
929
+ ```ruby
930
+ class Twitter::API < Grape::API
931
+ rescue_from :all do |e|
932
+ # version prior to 1.2.0
933
+ Rack::Response.new([ e.message ], 500, { 'Content-type' => 'text/error' }).finish
934
+ # 1.2.0 version
935
+ Rack::Response.new([ e.message ], 500, { 'Content-type' => 'text/error' })
936
+ end
937
+ end
938
+ ```
939
+
940
+ See [#1757](https://github.com/ruby-grape/grape/pull/1757) and [#1776](https://github.com/ruby-grape/grape/pull/1776) for more information.
941
+
942
+ ### Upgrading to >= 1.1.0
943
+
944
+ #### Changes in HTTP Response Code for Unsupported Content Type
945
+
946
+ For PUT, POST, PATCH, and DELETE requests where a non-empty body and a "Content-Type" header is supplied that is not supported by the Grape API, Grape will no longer return a 406 "Not Acceptable" HTTP status code and will instead return a 415 "Unsupported Media Type" so that the usage of HTTP status code falls more in line with the specification of [RFC 2616](https://www.ietf.org/rfc/rfc2616.txt).
947
+
948
+ ### Upgrading to >= 1.0.0
949
+
950
+ #### Changes in XML and JSON Parsers
951
+
952
+ Grape no longer uses `multi_json` or `multi_xml` by default and uses `JSON` and `ActiveSupport::XmlMini` instead. This has no visible impact on JSON processing, but the default behavior of the XML parser has changed. For example, an XML POST containing `<user>Bobby T.</user>` was parsed as `Bobby T.` with `multi_xml`, and as now parsed as `{"__content__"=>"Bobby T."}` with `XmlMini`.
953
+
954
+ If you were using `MultiJson.load`, `MultiJson.dump` or `MultiXml.parse`, you can substitute those with `Grape::Json.load`, `Grape::Json.dump`, `::Grape::Xml.parse`, or directly with `JSON.load`, `JSON.dump`, `XmlMini.parse`, etc.
955
+
956
+ To restore previous behavior, add `multi_json` or `multi_xml` to your `Gemfile` and `require` it.
957
+
958
+ See [#1623](https://github.com/ruby-grape/grape/pull/1623) for more information.
959
+
960
+ #### Changes in Parameter Class
961
+
962
+ The default class for `params` has changed from `Hashie::Mash` to `ActiveSupport::HashWithIndifferentAccess` and the `hashie` dependency has been removed. This means that by default you can no longer access parameters by method name.
963
+
964
+ ```ruby
965
+ class API < Grape::API
966
+ params do
967
+ optional :color, type: String
968
+ end
969
+ get do
970
+ params[:color] # use params[:color] instead of params.color
971
+ end
972
+ end
973
+ ```
974
+
975
+ To restore the behavior of prior versions, add `hashie` to your `Gemfile` and `include Grape::Extensions::Hashie::Mash::ParamBuilder` in your API.
976
+
977
+ ```ruby
978
+ class API < Grape::API
979
+ include Grape::Extensions::Hashie::Mash::ParamBuilder
980
+
981
+ params do
982
+ optional :color, type: String
983
+ end
984
+ get do
985
+ # params.color works
986
+ end
987
+ end
988
+ ```
989
+
990
+ This behavior can also be overridden on individual parameter blocks using `build_with`.
991
+
992
+ ```ruby
993
+ params do
994
+ build_with Grape::Extensions::Hash::ParamBuilder
995
+ optional :color, type: String
996
+ end
997
+ ```
998
+
999
+ If you're constructing your own `Grape::Request` in a middleware, you can pass different parameter handlers to create the desired `params` class with `build_params_with`.
1000
+
1001
+ ```ruby
1002
+ def request
1003
+ Grape::Request.new(env, build_params_with: Grape::Extensions::Hashie::Mash::ParamBuilder)
1004
+ end
1005
+ ```
1006
+
1007
+ See [#1610](https://github.com/ruby-grape/grape/pull/1610) for more information.
1008
+
1009
+ #### The `except`, `except_message`, and `proc` options of the `values` validator are deprecated.
1010
+
1011
+ The new `except_values` validator should be used in place of the `except` and `except_message` options of the `values` validator.
1012
+
1013
+ Arity one Procs may now be used directly as the `values` option to explicitly test param values.
1014
+
1015
+ **Deprecated**
1016
+ ```ruby
1017
+ params do
1018
+ requires :a, values: { value: 0..99, except: [3] }
1019
+ requires :b, values: { value: 0..99, except: [3], except_message: 'not allowed' }
1020
+ requires :c, values: { except: ['admin'] }
1021
+ requires :d, values: { proc: -> (v) { v.even? } }
1022
+ end
1023
+ ```
1024
+ **New**
1025
+ ```ruby
1026
+ params do
1027
+ requires :a, values: 0..99, except_values: [3]
1028
+ requires :b, values: 0..99, except_values: { value: [3], message: 'not allowed' }
1029
+ requires :c, except_values: ['admin']
1030
+ requires :d, values: -> (v) { v.even? }
1031
+ end
1032
+ ```
1033
+
1034
+ See [#1616](https://github.com/ruby-grape/grape/pull/1616) for more information.
1035
+
1036
+ ### Upgrading to >= 0.19.1
1037
+
1038
+ #### DELETE now defaults to status code 200 for responses with a body, or 204 otherwise
1039
+
1040
+ Prior to this version, DELETE requests defaulted to a status code of 204 No Content, even when the response included content. This behavior confused some clients and prevented the formatter middleware from running properly. As of this version, DELETE requests will only default to a 204 No Content status code if no response body is provided, and will default to 200 OK otherwise.
1041
+
1042
+ Specifically, DELETE behaviour has changed as follows:
1043
+
1044
+ - In versions < 0.19.0, all DELETE requests defaulted to a 200 OK status code.
1045
+ - In version 0.19.0, all DELETE requests defaulted to a 204 No Content status code, even when content was included in the response.
1046
+ - As of version 0.19.1, DELETE requests default to a 204 No Content status code, unless content is supplied, in which case they default to a 200 OK status code.
1047
+
1048
+ To achieve the old behavior, one can specify the status code explicitly:
1049
+
1050
+ ```ruby
1051
+ delete :id do
1052
+ status 204 # or 200, for < 0.19.0 behavior
1053
+ 'foo successfully deleted'
1054
+ end
1055
+ ```
1056
+
1057
+ One can also use the new `return_no_content` helper to explicitly return a 204 status code and an empty body for any request type:
1058
+
1059
+ ```ruby
1060
+ delete :id do
1061
+ return_no_content
1062
+ 'this will not be returned'
1063
+ end
1064
+ ```
1065
+
1066
+ See [#1550](https://github.com/ruby-grape/grape/pull/1550) for more information.
1067
+
1068
+ ### Upgrading to >= 0.18.1
1069
+
1070
+ #### Changes in priority of :any routes
1071
+
1072
+ Prior to this version, `:any` routes were searched after matching first route and 405 routes. This behavior has changed and `:any` routes are now searched before 405 processing. In the following example the `:any` route will match first when making a request with an unsupported verb.
1073
+
1074
+ ```ruby
1075
+ post :example do
1076
+ 'example'
1077
+ end
1078
+ route :any, '*path' do
1079
+ error! :not_found, 404
1080
+ end
1081
+
1082
+ get '/example' #=> before: 405, after: 404
1083
+ ```
1084
+
1085
+ #### Removed param processing from built-in OPTIONS handler
1086
+
1087
+ When a request is made to the built-in `OPTIONS` handler, only the `before` and `after` callbacks associated with the resource will be run. The `before_validation` and `after_validation` callbacks and parameter validations will be skipped.
1088
+
1089
+ See [#1505](https://github.com/ruby-grape/grape/pull/1505) for more information.
1090
+
1091
+ #### Changed endpoint params validation
1092
+
1093
+ Grape now correctly returns validation errors for all params when multiple params are passed to a requires.
1094
+ The following code will return `one is missing, two is missing` when calling the endpoint without parameters.
1095
+
1096
+ ```ruby
1097
+ params do
1098
+ requires :one, :two
1099
+ end
1100
+ ```
1101
+
1102
+ Prior to this version the response would be `one is missing`.
1103
+
1104
+ See [#1510](https://github.com/ruby-grape/grape/pull/1510) for more information.
1105
+
1106
+ #### The default status code for DELETE is now 204 instead of 200.
1107
+
1108
+ Breaking change: Sets the default response status code for a delete request to 204. A status of 204 makes the response more distinguishable and therefore easier to handle on the client side, particularly because a DELETE request typically returns an empty body as the resource was deleted or voided.
1109
+
1110
+ To achieve the old behavior, one has to set it explicitly:
1111
+ ```ruby
1112
+ delete :id do
1113
+ status 200
1114
+ 'foo successfully deleted'
1115
+ end
1116
+ ```
1117
+
1118
+ For more information see: [#1532](https://github.com/ruby-grape/grape/pull/1532).
1119
+
1120
+ ### Upgrading to >= 0.17.0
1121
+
1122
+ #### Removed official support for Ruby < 2.2.2
1123
+
1124
+ Grape is no longer automatically tested against versions of Ruby prior to 2.2.2. This is because of its dependency on activesupport which, with version 5.0.0, now requires at least Ruby 2.2.2.
1125
+
1126
+ See [#1441](https://github.com/ruby-grape/grape/pull/1441) for nmore information.
1127
+
1128
+ #### Changed priority of `rescue_from` clauses applying
1129
+
1130
+ The `rescue_from` clauses declared inside a namespace would take a priority over ones declared in the root scope.
1131
+ This could possibly affect those users who use different `rescue_from` clauses in root scope and in namespaces.
1132
+
1133
+ See [#1405](https://github.com/ruby-grape/grape/pull/1405) for more information.
1134
+
1135
+ #### Helper methods injected inside `rescue_from` in middleware
1136
+
1137
+ Helper methods are injected inside `rescue_from` may cause undesirable effects. For example, definining a helper method called `error!` will take precendence over the built-in `error!` method and should be renamed.
1138
+
1139
+ See [#1451](https://github.com/ruby-grape/grape/issues/1451) for an example.
1140
+
1141
+ ### Upgrading to >= 0.16.0
1142
+
1143
+ #### Replace rack-mount with new router
1144
+
1145
+ The `Route#route_xyz` methods have been deprecated since 0.15.1.
1146
+
1147
+ Please use `Route#xyz` instead.
1148
+
1149
+ Note that the `Route#route_method` was replaced by `Route#request_method`.
1150
+
1151
+ The following code would work correctly.
1152
+
1153
+ ```ruby
1154
+ TwitterAPI::versions # yields [ 'v1', 'v2' ]
1155
+ TwitterAPI::routes # yields an array of Grape::Route objects
1156
+ TwitterAPI::routes[0].version # => 'v1'
1157
+ TwitterAPI::routes[0].description # => 'Includes custom settings.'
1158
+ TwitterAPI::routes[0].settings[:custom] # => { key: 'value' }
1159
+
1160
+ TwitterAPI::routes[0].request_method # => 'GET'
1161
+ ```
1162
+
1163
+ #### `file` method accepts path to file
1164
+
1165
+ Now to serve files via Grape just pass the path to the file. Functionality with FileStreamer-like objects is deprecated.
1166
+
1167
+ Please, replace your FileStreamer-like objects with paths of served files.
1168
+
1169
+ Old style:
1170
+
1171
+ ```ruby
1172
+ class FileStreamer
1173
+ def initialize(file_path)
1174
+ @file_path = file_path
1175
+ end
1176
+
1177
+ def each(&blk)
1178
+ File.open(@file_path, 'rb') do |file|
1179
+ file.each(10, &blk)
1180
+ end
1181
+ end
1182
+ end
1183
+
1184
+ # ...
1185
+
1186
+ class API < Grape::API
1187
+ get '/' do
1188
+ file FileStreamer.new('/path/to/file')
1189
+ end
1190
+ end
1191
+ ```
1192
+
1193
+ New style:
1194
+
1195
+ ```ruby
1196
+ class API < Grape::API
1197
+ get '/' do
1198
+ file '/path/to/file'
1199
+ end
1200
+ end
1201
+ ```
1202
+
1203
+ ### Upgrading to >= 0.15.0
1204
+
1205
+ #### Changes to availability of `:with` option of `rescue_from` method
1206
+
1207
+ The `:with` option of `rescue_from` does not accept value except Proc, String or Symbol now.
1208
+
1209
+ If you have been depending the old behavior, you should use lambda block instead.
1210
+
1211
+ ```ruby
1212
+ class API < Grape::API
1213
+ rescue_from :all, with: -> { Rack::Response.new('rescued with a method', 400) }
1214
+ end
1215
+ ```
1216
+
1217
+ #### Changes to behavior of `after` method of middleware on error
1218
+
1219
+ The `after` method of the middleware is now also called on error. The following code would work correctly.
1220
+
1221
+ ```ruby
1222
+ class ErrorMiddleware < Grape::Middleware::Base
1223
+ def after
1224
+ return unless @app_response && @app_response[0] == 500
1225
+ env['rack.logger'].debug("Raised error on #{env['PATH_INFO']}")
1226
+ end
1227
+ end
1228
+ ```
1229
+
1230
+ See [#1147](https://github.com/ruby-grape/grape/issues/1147) and [#1240](https://github.com/ruby-grape/grape/issues/1240) for discussion of the issues.
1231
+
1232
+ A warning will be logged if an exception is raised in an `after` callback, which points you to middleware that was not called in the previous version and is called now.
1233
+
1234
+ ```
1235
+ caught error of type NoMethodError in after callback inside Api::Middleware::SomeMiddleware : undefined method `headers' for nil:NilClass
1236
+ ```
1237
+
1238
+ See [#1285](https://github.com/ruby-grape/grape/pull/1285) for more information.
1239
+
1240
+ #### Changes to Method Not Allowed routes
1241
+
1242
+ A `405 Method Not Allowed` error now causes `Grape::Exceptions::MethodNotAllowed` to be raised, which will be rescued via `rescue_from :all`. Restore old behavior with the following error handler.
1243
+
1244
+ ```ruby
1245
+ rescue_from Grape::Exceptions::MethodNotAllowed do |e|
1246
+ error! e.message, e.status, e.headers
1247
+ end
1248
+ ```
1249
+
1250
+ See [#1283](https://github.com/ruby-grape/grape/pull/1283) for more information.
1251
+
1252
+ #### Changes to Grape::Exceptions::Validation parameters
1253
+
1254
+ When raising `Grape::Exceptions::Validation` explicitly, replace `message_key` with `message`.
1255
+
1256
+ For example,
1257
+
1258
+ ```ruby
1259
+ fail Grape::Exceptions::Validation, params: [:oauth_token_secret], message_key: :presence
1260
+ ```
1261
+
1262
+ becomes
1263
+
1264
+ ```ruby
1265
+ fail Grape::Exceptions::Validation, params: [:oauth_token_secret], message: :presence
1266
+ ```
1267
+
1268
+ See [#1295](https://github.com/ruby-grape/grape/pull/1295) for more information.
1269
+
1270
+ ### Upgrading to >= 0.14.0
1271
+
1272
+ #### Changes to availability of DSL methods in filters
1273
+
1274
+ The `#declared` method of the route DSL is no longer available in the `before` filter. Using `declared` in a `before` filter will now raise `Grape::DSL::InsideRoute::MethodNotYetAvailable`.
1275
+
1276
+ See [#1074](https://github.com/ruby-grape/grape/issues/1074) for discussion of the issue.
1277
+
1278
+ #### Changes to header versioning and invalid header version handling
1279
+
1280
+ Identical endpoints with different versions now work correctly. A regression introduced in Grape 0.11.0 caused all but the first-mounted version for such an endpoint to wrongly throw an `InvalidAcceptHeader`. As a side effect, requests with a correct vendor but invalid version can no longer be rescued from a `rescue_from` block.
1281
+
1282
+ See [#1114](https://github.com/ruby-grape/grape/pull/1114) for more information.
1283
+
1284
+ #### Bypasses formatters when status code indicates no content
1285
+
1286
+ To be consistent with rack and it's handling of standard responses associated with no content, both default and custom formatters will now be bypassed when processing responses for status codes defined [by rack](https://github.com/rack/rack/blob/master/lib/rack/utils.rb#L567)
1287
+
1288
+ See [#1190](https://github.com/ruby-grape/grape/pull/1190) for more information.
1289
+
1290
+ #### Redirects respond as plain text with message
1291
+
1292
+ `#redirect` now uses `text/plain` regardless of whether that format has been enabled. This prevents formatters from attempting to serialize the message body and allows for a descriptive message body to be provided - and optionally overridden - that better fulfills the theme of the HTTP spec.
1293
+
1294
+ See [#1194](https://github.com/ruby-grape/grape/pull/1194) for more information.
1295
+
1296
+ ### Upgrading to >= 0.12.0
1297
+
1298
+ #### Changes in middleware
1299
+
1300
+ The Rack response object is no longer converted to an array by the formatter, enabling streaming. If your custom middleware is accessing `@app_response`, update it to expect a `Rack::Response` instance instead of an array.
1301
+
1302
+ For example,
1303
+
1304
+ ```ruby
1305
+ class CacheBusterMiddleware < Grape::Middleware::Base
1306
+ def after
1307
+ @app_response[1]['Expires'] = Time.at(0).utc.to_s
1308
+ @app_response
1309
+ end
1310
+ end
1311
+ ```
1312
+
1313
+ becomes
1314
+
1315
+ ```ruby
1316
+ class CacheBusterMiddleware < Grape::Middleware::Base
1317
+ def after
1318
+ @app_response.headers['Expires'] = Time.at(0).utc.to_s
1319
+ @app_response
1320
+ end
1321
+ end
1322
+ ```
1323
+
1324
+ See [#1029](https://github.com/ruby-grape/grape/pull/1029) for more information.
1325
+
1326
+ There is a known issue because of this change. When Grape is used with an older than 1.2.4 version of [warden](https://github.com/hassox/warden) there may be raised the following exception having the [rack-mount](https://github.com/jm/rack-mount) gem's lines as last ones in the backtrace:
1327
+
1328
+ ```
1329
+ NoMethodError: undefined method `[]' for nil:NilClass
1330
+ ```
1331
+
1332
+ The issue can be solved by upgrading warden to 1.2.4 version.
1333
+
1334
+ See [#1151](https://github.com/ruby-grape/grape/issues/1151) for more information.
1335
+
1336
+ #### Changes in present
1337
+
1338
+ Using `present` with objects that responded to `merge` would cause early evaluation of the represented object, with unexpected side-effects, such as missing parameters or environment within rendering code. Grape now only merges represented objects with a previously rendered body, usually when multiple `present` calls are made in the same route.
1339
+
1340
+ See [grape-with-roar#5](https://github.com/dblock/grape-with-roar/issues/5) and [#1023](https://github.com/ruby-grape/grape/issues/1023).
1341
+
1342
+ #### Changes to regexp validator
1343
+
1344
+ Parameters with `nil` value will now pass `regexp` validation. To disallow `nil` value for an endpoint, add `allow_blank: false`.
1345
+
1346
+ ```ruby
1347
+ params do
1348
+ requires :email, allow_blank: false, regexp: /.+@.+/
1349
+ end
1350
+ ```
1351
+
1352
+ See [#957](https://github.com/ruby-grape/grape/pull/957) for more information.
1353
+
1354
+ #### Replace error_response with error! in rescue_from blocks
1355
+
1356
+ Note: `error_response` is being deprecated, not removed.
1357
+
1358
+ ```ruby
1359
+ def error!(message, status = options[:default_status], headers = {}, backtrace = [])
1360
+ headers = { 'Content-Type' => content_type }.merge(headers)
1361
+ rack_response(format_message(message, backtrace), status, headers)
1362
+ end
1363
+ ```
1364
+
1365
+ For example,
1366
+
1367
+ ```
1368
+ error_response({ message: { message: 'No such page.', id: 'missing_page' }, status: 404, headers: { 'Content-Type' => 'api/error' })
1369
+ ```
1370
+
1371
+ becomes
1372
+
1373
+ ```
1374
+ error!({ message: 'No such page.', id: 'missing_page' }, 404, { 'Content-Type' => 'api/error' })
1375
+ ```
1376
+
1377
+ `error!` also supports just passing a message. `error!('Server error.')` and `format: :json` returns the following JSON response
1378
+
1379
+ ```
1380
+ { 'error': 'Server error.' }
1381
+ ```
1382
+
1383
+ with a status code of 500 and a Content Type of text/error.
1384
+
1385
+ Optionally, also replace `Rack::Response.new` with `error!.`
1386
+ The following are equivalent:
1387
+
1388
+ ```
1389
+ Rack::Response.new([ e.message ], 500, { "Content-type" => "text/error" }).finish
1390
+ error!(e)
1391
+ ```
1392
+
1393
+ See [#889](https://github.com/ruby-grape/grape/issues/889) for more information.
1394
+
1395
+ #### Changes to routes when using `format`
1396
+
1397
+ Version 0.10.0 has introduced a change via [#809](https://github.com/ruby-grape/grape/pull/809) whereas routes no longer got file-type suffixes added if you declared a single API `format`. This has been reverted, it's now again possible to call API with proper suffix when single `format` is defined:
1398
+
1399
+ ```ruby
1400
+ class API < Grape::API
1401
+ format :json
1402
+
1403
+ get :hello do
1404
+ { hello: 'world' }
1405
+ end
1406
+ end
1407
+ ```
1408
+
1409
+ Will respond with JSON to `/hello` **and** `/hello.json`.
1410
+
1411
+ Will respond with 404 to `/hello.xml`, `/hello.txt` etc.
1412
+
1413
+ See the [#1001](https://github.com/ruby-grape/grape/pull/1001) and [#914](https://github.com/ruby-grape/grape/issues/914) for more info.
1414
+
1415
+ ### Upgrading to >= 0.11.0
1416
+
1417
+ #### Added Rack 1.6.0 support
1418
+
1419
+ Grape now supports, but doesn't require Rack 1.6.0. If you encounter an issue with parsing requests larger than 128KB, explictly require Rack 1.6.0 in your Gemfile.
1420
+
1421
+ ```ruby
1422
+ gem 'rack', '~> 1.6.0'
1423
+ ```
1424
+
1425
+ See [#559](https://github.com/ruby-grape/grape/issues/559) for more information.
1426
+
1427
+ #### Removed route_info
1428
+
1429
+ Key route_info is excluded from params.
1430
+
1431
+ See [#879](https://github.com/ruby-grape/grape/pull/879) for more information.
1432
+
1433
+
1434
+ #### Fix callbacks within a version block
1435
+
1436
+ Callbacks defined in a version block are only called for the routes defined in that block. This was a regression introduced in Grape 0.10.0, and is fixed in this version.
1437
+
1438
+ See [#901](https://github.com/ruby-grape/grape/pull/901) for more information.
1439
+
1440
+
1441
+ #### Make type of group of parameters required
1442
+
1443
+ Groups of parameters now require their type to be set explicitly as Array or Hash.
1444
+ Not setting the type now results in MissingGroupTypeError, unsupported type will raise UnsupportedTypeError.
1445
+
1446
+ See [#886](https://github.com/ruby-grape/grape/pull/886) for more information.
1447
+
1448
+ ### Upgrading to >= 0.10.1
1449
+
1450
+ #### Changes to `declared(params, include_missing: false)`
1451
+
1452
+ Attributes with `nil` values or with values that evaluate to `false` are no longer considered *missing* and will be returned when `include_missing` is set to `false`.
1453
+
1454
+ See [#864](https://github.com/ruby-grape/grape/pull/864) for more information.
1455
+
1456
+ ### Upgrading to >= 0.10.0
1457
+
1458
+ #### Changes to content-types
1459
+
1460
+ The following content-types have been removed:
1461
+
1462
+ * atom (application/atom+xml)
1463
+ * rss (application/rss+xml)
1464
+ * jsonapi (application/jsonapi)
1465
+
1466
+ This is because they have never been properly supported.
1467
+
1468
+ #### Changes to desc
1469
+
1470
+ New block syntax:
1471
+
1472
+ Former:
1473
+
1474
+ ```ruby
1475
+ desc "some descs",
1476
+ detail: 'more details',
1477
+ entity: API::Entities::Entity,
1478
+ params: API::Entities::Status.documentation,
1479
+ named: 'a name',
1480
+ headers: [XAuthToken: {
1481
+ description: 'Valdates your identity',
1482
+ required: true
1483
+ }
1484
+ get nil, http_codes: [
1485
+ [401, 'Unauthorized', API::Entities::BaseError],
1486
+ [404, 'not found', API::Entities::Error]
1487
+ ] do
1488
+ ```
1489
+
1490
+ Now:
1491
+
1492
+ ```ruby
1493
+ desc "some descs" do
1494
+ detail 'more details'
1495
+ params API::Entities::Status.documentation
1496
+ success API::Entities::Entity
1497
+ failure [
1498
+ [401, 'Unauthorized', API::Entities::BaseError],
1499
+ [404, 'not found', API::Entities::Error]
1500
+ ]
1501
+ named 'a name'
1502
+ headers [
1503
+ XAuthToken: {
1504
+ description: 'Valdates your identity',
1505
+ required: true
1506
+ },
1507
+ XOptionalHeader: {
1508
+ description: 'Not really needed',
1509
+ required: false
1510
+ }
1511
+ ]
1512
+ end
1513
+ ```
1514
+
1515
+ #### Changes to Route Options and Descriptions
1516
+
1517
+ A common hack to extend Grape with custom DSL methods was manipulating `@last_description`.
1518
+
1519
+ ``` ruby
1520
+ module Grape
1521
+ module Extensions
1522
+ module SortExtension
1523
+ def sort(value)
1524
+ @last_description ||= {}
1525
+ @last_description[:sort] ||= {}
1526
+ @last_description[:sort].merge! value
1527
+ value
1528
+ end
1529
+ end
1530
+
1531
+ Grape::API.extend self
1532
+ end
1533
+ end
1534
+ ```
1535
+
1536
+ You could access this value from within the API with `route.route_sort` or, more generally, via `env['api.endpoint'].options[:route_options][:sort]`.
1537
+
1538
+ This will no longer work, use the documented and supported `route_setting`.
1539
+
1540
+ ``` ruby
1541
+ module Grape
1542
+ module Extensions
1543
+ module SortExtension
1544
+ def sort(value)
1545
+ route_setting :sort, sort: value
1546
+ value
1547
+ end
1548
+ end
1549
+
1550
+ Grape::API.extend self
1551
+ end
1552
+ end
1553
+ ```
1554
+
1555
+ To retrieve this value at runtime from within an API, use `env['api.endpoint'].route_setting(:sort)` and when introspecting a mounted API, use `route.route_settings[:sort]`.
1556
+
1557
+ #### Accessing Class Variables from Helpers
1558
+
1559
+ It used to be possible to fetch an API class variable from a helper function. For example:
1560
+
1561
+ ```ruby
1562
+ @@static_variable = 42
1563
+
1564
+ helpers do
1565
+ def get_static_variable
1566
+ @@static_variable
1567
+ end
1568
+ end
1569
+
1570
+ get do
1571
+ get_static_variable
1572
+ end
1573
+ ```
1574
+
1575
+ This will no longer work. Use a class method instead of a helper.
1576
+
1577
+ ```ruby
1578
+ @@static_variable = 42
1579
+
1580
+ def self.get_static_variable
1581
+ @@static_variable
1582
+ end
1583
+
1584
+ get do
1585
+ get_static_variable
1586
+ end
1587
+ ```
1588
+
1589
+ For more information see [#836](https://github.com/ruby-grape/grape/issues/836).
1590
+
1591
+ #### Changes to Custom Validators
1592
+
1593
+ To implement a custom validator, you need to inherit from `Grape::Validations::Base` instead of `Grape::Validations::Validator`.
1594
+
1595
+ For more information see [Custom Validators](https://github.com/ruby-grape/grape#custom-validators) in the documentation.
1596
+
1597
+ #### Changes to Raising Grape::Exceptions::Validation
1598
+
1599
+ In previous versions raising `Grape::Exceptions::Validation` required a single `param`.
1600
+
1601
+ ```ruby
1602
+ raise Grape::Exceptions::Validation, param: :id, message_key: :presence
1603
+ ```
1604
+
1605
+ The `param` argument has been deprecated and is now an array of `params`, accepting multiple values.
1606
+
1607
+ ```ruby
1608
+ raise Grape::Exceptions::Validation, params: [:id], message_key: :presence
1609
+ ```
1610
+
1611
+ #### Changes to routes when using `format`
1612
+
1613
+ Routes will no longer get file-type suffixes added if you declare a single API `format`. For example,
1614
+
1615
+ ```ruby
1616
+ class API < Grape::API
1617
+ format :json
1618
+
1619
+ get :hello do
1620
+ { hello: 'world' }
1621
+ end
1622
+ end
1623
+ ```
1624
+
1625
+ Pre-0.10.0, this would respond with JSON to `/hello`, `/hello.json`, `/hello.xml`, `/hello.txt`, etc.
1626
+
1627
+ Now, this will only respond with JSON to `/hello`, but will be a 404 when trying to access `/hello.json`, `/hello.xml`, `/hello.txt`, etc.
1628
+
1629
+ If you declare further `content_type`s, this behavior will be circumvented. For example, the following API will respond with JSON to `/hello`, `/hello.json`, `/hello.xml`, `/hello.txt`, etc.
1630
+
1631
+ ```ruby
1632
+ class API < Grape::API
1633
+ format :json
1634
+ content_type :json, 'application/json'
1635
+
1636
+ get :hello do
1637
+ { hello: 'world' }
1638
+ end
1639
+ end
1640
+ ```
1641
+
1642
+ See the [the updated API Formats documentation](https://github.com/ruby-grape/grape#api-formats) and [#809](https://github.com/ruby-grape/grape/pull/809) for more info.
1643
+
1644
+ #### Changes to Evaluation of Permitted Parameter Values
1645
+
1646
+ Permitted and default parameter values are now only evaluated lazily for each request when declared as a proc. The following code would raise an error at startup time.
1647
+
1648
+ ```ruby
1649
+ params do
1650
+ optional :v, values: -> { [:x, :y] }, default: -> { :z }
1651
+ end
1652
+ ```
1653
+
1654
+ Remove the proc to get the previous behavior.
1655
+
1656
+ ```ruby
1657
+ params do
1658
+ optional :v, values: [:x, :y], default: :z
1659
+ end
1660
+ ```
1661
+
1662
+ See [#801](https://github.com/ruby-grape/grape/issues/801) for more information.
1663
+
1664
+ #### Changes to version
1665
+
1666
+ If version is used with a block, the callbacks defined within that version block are not scoped to that individual block. In other words, the callback would be inherited by all versions blocks that follow the first one e.g
1667
+
1668
+ ```ruby
1669
+ class API < Grape::API
1670
+ resource :foo do
1671
+ version 'v1', :using => :path do
1672
+ before do
1673
+ @output ||= 'hello1'
1674
+ end
1675
+ get '/' do
1676
+ @output += '-v1'
1677
+ end
1678
+ end
1679
+
1680
+ version 'v2', :using => :path do
1681
+ before do
1682
+ @output ||= 'hello2'
1683
+ end
1684
+ get '/:id' do
1685
+ @output += '-v2'
1686
+ end
1687
+ end
1688
+ end
1689
+ end
1690
+ ```
1691
+
1692
+ when making a API call `GET /foo/v2/1`, the API would set instance variable `@output` to `hello1-v2`
1693
+
1694
+ See [#898](https://github.com/ruby-grape/grape/issues/898) for more information.
1695
+
1696
+
1697
+ ### Upgrading to >= 0.9.0
1698
+
1699
+ #### Changes in Authentication
1700
+
1701
+ The following middleware classes have been removed:
1702
+
1703
+ * `Grape::Middleware::Auth::Basic`
1704
+ * `Grape::Middleware::Auth::Digest`
1705
+ * `Grape::Middleware::Auth::OAuth2`
1706
+
1707
+ When you use theses classes directly like:
1708
+
1709
+ ```ruby
1710
+ module API
1711
+ class Root < Grape::API
1712
+ class Protected < Grape::API
1713
+ use Grape::Middleware::Auth::OAuth2,
1714
+ token_class: 'AccessToken',
1715
+ parameter: %w(access_token api_key)
1716
+
1717
+ ```
1718
+
1719
+ you have to replace these classes.
1720
+
1721
+ As replacement can be used
1722
+
1723
+ * `Grape::Middleware::Auth::Basic` => [`Rack::Auth::Basic`](https://github.com/rack/rack/blob/master/lib/rack/auth/basic.rb)
1724
+ * `Grape::Middleware::Auth::Digest` => [`Rack::Auth::Digest::MD5`](https://github.com/rack/rack/blob/master/lib/rack/auth/digest/md5.rb)
1725
+ * `Grape::Middleware::Auth::OAuth2` => [warden-oauth2](https://github.com/opperator/warden-oauth2) or [rack-oauth2](https://github.com/nov/rack-oauth2)
1726
+
1727
+ If this is not possible you can extract the middleware files from [grape v0.7.0](https://github.com/ruby-grape/grape/tree/v0.7.0/lib/grape/middleware/auth) and host these files within your application
1728
+
1729
+ See [#703](https://github.com/ruby-grape/Grape/pull/703) for more information.
1730
+
1731
+ ### Upgrading to >= 0.7.0
1732
+
1733
+ #### Changes in Exception Handling
1734
+
1735
+ Assume you have the following exception classes defined.
1736
+
1737
+ ```ruby
1738
+ class ParentError < StandardError; end
1739
+ class ChildError < ParentError; end
1740
+ ```
1741
+
1742
+ In Grape <= 0.6.1, the `rescue_from` keyword only handled the exact exception being raised. The following code would rescue `ParentError`, but not `ChildError`.
1743
+
1744
+ ```ruby
1745
+ rescue_from ParentError do |e|
1746
+ # only rescue ParentError
1747
+ end
1748
+ ```
1749
+
1750
+ This made it impossible to rescue an exception hieararchy, which is a more sensible default. In Grape 0.7.0 or newer, both `ParentError` and `ChildError` are rescued.
1751
+
1752
+ ```ruby
1753
+ rescue_from ParentError do |e|
1754
+ # rescue both ParentError and ChildError
1755
+ end
1756
+ ```
1757
+
1758
+ To only rescue the base exception class, set `rescue_subclasses: false`.
1759
+
1760
+ ```ruby
1761
+ rescue_from ParentError, rescue_subclasses: false do |e|
1762
+ # only rescue ParentError
1763
+ end
1764
+ ```
1765
+
1766
+ See [#544](https://github.com/ruby-grape/grape/pull/544) for more information.
1767
+
1768
+
1769
+ #### Changes in the Default HTTP Status Code
1770
+
1771
+ In Grape <= 0.6.1, the default status code returned from `error!` was 403.
1772
+
1773
+ ```ruby
1774
+ error! "You may not reticulate this spline!" # yields HTTP error 403
1775
+ ```
1776
+
1777
+ This was a bad default value, since 403 means "Forbidden". Change any call to `error!` that does not specify a status code to specify one. The new default value is a more sensible default of 500, which is "Internal Server Error".
1778
+
1779
+ ```ruby
1780
+ error! "You may not reticulate this spline!", 403 # yields HTTP error 403
1781
+ ```
1782
+
1783
+ You may also use `default_error_status` to change the global default.
1784
+
1785
+ ```ruby
1786
+ default_error_status 400
1787
+ ```
1788
+
1789
+ See [#525](https://github.com/ruby-grape/Grape/pull/525) for more information.
1790
+
1791
+
1792
+ #### Changes in Parameter Declaration and Validation
1793
+
1794
+ In Grape <= 0.6.1, `group`, `optional` and `requires` keywords with a block accepted either an `Array` or a `Hash`.
1795
+
1796
+ ```ruby
1797
+ params do
1798
+ requires :id, type: Integer
1799
+ group :name do
1800
+ requires :first_name
1801
+ requires :last_name
1802
+ end
1803
+ end
1804
+ ```
1805
+
1806
+ This caused the ambiguity and unexpected errors described in [#543](https://github.com/ruby-grape/Grape/issues/543).
1807
+
1808
+ In Grape 0.7.0, the `group`, `optional` and `requires` keywords take an additional `type` attribute which defaults to `Array`. This means that without a `type` attribute, these nested parameters will no longer accept a single hash, only an array (of hashes).
1809
+
1810
+ Whereas in 0.6.1 the API above accepted the following json, it no longer does in 0.7.0.
1811
+
1812
+ ```json
1813
+ {
1814
+ "id": 1,
1815
+ "name": {
1816
+ "first_name": "John",
1817
+ "last_name" : "Doe"
1818
+ }
1819
+ }
1820
+ ```
1821
+
1822
+ The `params` block should now read as follows.
1823
+
1824
+ ```ruby
1825
+ params do
1826
+ requires :id, type: Integer
1827
+ requires :name, type: Hash do
1828
+ requires :first_name
1829
+ requires :last_name
1830
+ end
1831
+ end
1832
+ ```
1833
+
1834
+ See [#545](https://github.com/ruby-grape/Grape/pull/545) for more information.
1835
+
1836
+
1837
+ ### Upgrading to 0.6.0
1838
+
1839
+ In Grape <= 0.5.0, only the first validation error was raised and processing aborted. Validation errors are now collected and a single `Grape::Exceptions::ValidationErrors` exception is raised. You can access the collection of validation errors as `.errors`.
1840
+
1841
+ ```ruby
1842
+ rescue_from Grape::Exceptions::Validations do |e|
1843
+ Rack::Response.new({
1844
+ status: 422,
1845
+ message: e.message,
1846
+ errors: e.errors
1847
+ }.to_json, 422)
1848
+ end
1849
+ ```
1850
+
1851
+ For more information see [#462](https://github.com/ruby-grape/grape/issues/462).