Skip to content

Commit edd868c

Browse files
ericproulxclaude
andcommitted
Report a required param the request left out as missing only
Every validator of a `requires` param was called whether the request sent the param or not, because PresenceValidator has to be called for a missing one to report it. A custom validator that read the value was then handed nil and raised, so the request answered 500 instead of 400. The README's own AlphaNumeric example does that: requires :text, alpha_numeric: true GET / Before: 500 NoMethodError (undefined method 'match?' for nil) After: 400 text is missing The built-in validators added a second error to `is missing` instead: `n is missing, n does not have a valid value` from `values`, `email is missing, email is empty` from `allow_blank: false`, and `ids is missing, ids is invalid` from a `coerce_with` method handed nil. Only PresenceValidator is now called for an attribute the params do not hold. Every other validator sees only the params a request sent, as it already did for an `optional` param, so a missing one is reported once. Each validator settles this when it is built, so the attribute loop reads an ivar where it called `required?`. A param sent as `null` is still validated, and `values` still rejects it. Asking the params whether they hold each required attribute cost a nested body of 20 items 5%, and `declared` 4%, in Duel. The built-in validators no longer ask again whether the params are a Hash that holds the attribute, as they are now only called when it does. And CoerceValidator, which every typed param has, is still called for a required attribute and tells a missing one for itself, from the value it reads anyway: only a nil is looked up. Every benchmark now measures the same as master. UPGRADING notes the dropped second messages, including the one #3010 documented for a nested param with `values`. The README says when `validate_param!` is called. Fixes #1693. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 2952721 commit edd868c

20 files changed

Lines changed: 159 additions & 29 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@
5555
* [#3087](https://github.com/ruby-grape/grape/pull/3087): Let a mounted API `use` the named params of the scope it is mounted in - [@ericproulx](https://github.com/ericproulx).
5656
* [#3093](https://github.com/ruby-grape/grape/pull/3093): Move the endpoint Rack stack building into `Endpoint::RackStack` to fix RuboCop - [@ericproulx](https://github.com/ericproulx).
5757
* [#3099](https://github.com/ruby-grape/grape/pull/3099): Report a nested Array scope that got no Array under its own name only - [@ericproulx](https://github.com/ericproulx).
58+
* [#3100](https://github.com/ruby-grape/grape/pull/3100): Report a required param the request left out as missing only - [@ericproulx](https://github.com/ericproulx).
5859
* Your contribution here.
5960

6061
### 4.1.0 (2026-10-31)

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1863,6 +1863,8 @@ params do
18631863
end
18641864
```
18651865

1866+
`validate_param!` is only called for a param the request sent. A `requires` param the request left out is reported as `text is missing`, and none of its other validators are called. A param sent as `null` reaches `validate_param!` as `nil`.
1867+
18661868
You can also create custom classes that take parameters.
18671869

18681870
```ruby

‎UPGRADING.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,28 @@ Upgrading Grape
33

44
### Upgrading to >= 4.2.0
55

6+
#### A required param the request left out is only reported missing
7+
8+
A `requires` param the request left out now answers `is missing` and nothing else ([#3100](https://github.com/ruby-grape/grape/pull/3100)). Its other validators, custom ones included, are only called for a param the request sent, as they already were for an `optional` one. A custom validator that read the value used to be handed `nil` for it and raise, so the request answered `500` instead of `400`. The README's own `AlphaNumeric` example did that.
9+
10+
The built-in validators that added a second error for a missing param no longer do:
11+
12+
```ruby
13+
params do
14+
requires :n, type: Integer, values: [1, 2]
15+
requires :email, type: String, allow_blank: false
16+
end
17+
```
18+
19+
```
20+
# Before
21+
n is missing, n does not have a valid value, email is missing, email is empty
22+
# After
23+
n is missing, email is missing
24+
```
25+
26+
This also drops the `does not have a valid value` that [#3010](https://github.com/ruby-grape/grape/pull/3010) added after `is missing` for a nested param with `values` (see [A required param with `values` rejects `nil` in a nested scope](#a-required-param-with-values-rejects-nil-in-a-nested-scope)). A param sent as `null` is still validated, and `values` still rejects it. A custom validator that has to see a missing param, to report it in its own words for instance, can override `validate(request)`, which is called whether the param was sent or not.
27+
628
#### `Grape::Util::MediaType` parses for a vendor's pattern
729

830
`Grape::Util::MediaType.parse`, `.best_quality` and `.new` take `vendor_pattern:`, the pattern `Grape::Util::MediaType.vendor_pattern(vendor)` answers, in place of `vendor:` ([#3098](https://github.com/ruby-grape/grape/pull/3098)). The header versioner looks its vendor's pattern up as it is built, so a request no longer reads a cache. Only code calling these internals is affected: pass `vendor_pattern: Grape::Util::MediaType.vendor_pattern(vendor)`.

‎lib/grape/validations/validators/allow_blank_validator.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def initialize(attrs, options, required, scope, opts)
1212
end
1313

1414
def validate_param!(attr_name, params)
15-
return if @value || !hash_like?(params)
15+
return if @value
1616

1717
value = params[attr_name]
1818
return if value == false || !Grape::Util::Scrub.blank?(value)

‎lib/grape/validations/validators/base.rb‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ def initialize(attrs, options, required, scope, opts)
6969
@opts = SharedOptions.new(**opts.slice(:allow_blank, :fail_fast))
7070
@exception_message = message(self.class.default_message_key) if self.class.default_message_key
7171
@iterator = AttributesIterator.new(@scope).freeze
72+
@validates_missing = validates_missing?
7273
choose_validation_path(scope)
7374
end
7475

@@ -116,6 +117,19 @@ def validate_param!(attr_name, params)
116117

117118
alias required? required
118119

120+
# Whether #validate_param! is asked about an attribute the params do
121+
# not hold, or params that are not a Hash. PresenceValidator is, to
122+
# report it missing, and CoerceValidator of a required one, which
123+
# tells for itself.
124+
# Every other validator sees only the params a request sent, whether
125+
# they are required or not, so a missing one is reported once, and a
126+
# custom validator is never handed one that is not there. The other
127+
# built-in validators count on it: they read the attribute without
128+
# asking first whether the params are a Hash that holds it.
129+
def validates_missing?
130+
false
131+
end
132+
119133
# A scope's parent, optionality, dependency and type are all set
120134
# before its block declares anything, so these are settled by the
121135
# time a validator is built. See #validate and #validate!.
@@ -138,7 +152,7 @@ def validate_attributes!(params)
138152
array_errors = nil
139153

140154
@attrs.each do |attr_name|
141-
validate_param!(attr_name, params) if required? || params.key?(attr_name)
155+
validate_param!(attr_name, params) if @validates_missing || params.key?(attr_name)
142156
rescue Grape::Exceptions::Validation => e
143157
(array_errors ||= []) << e
144158
end
@@ -196,11 +210,12 @@ def validate_iterated!(params)
196210
end
197211

198212
# Runs #validate_param! for each attribute +element+ holds, or for every
199-
# one when they are required, and returns +array_errors+ with what
200-
# failed appended, allocating it on the first failure.
213+
# one when this validator reports a missing one (see
214+
# #validates_missing?), and returns +array_errors+ with what failed
215+
# appended, allocating it on the first failure.
201216
def validate_element_attributes(element, array_errors)
202217
@attrs.each do |attr_name|
203-
validate_param!(attr_name, element) if required? || (hash_like?(element) && element.key?(attr_name))
218+
validate_param!(attr_name, element) if @validates_missing || (hash_like?(element) && element.key?(attr_name))
204219
rescue Grape::Exceptions::Validation => e
205220
(array_errors ||= []) << e
206221
end

‎lib/grape/validations/validators/coerce_validator.rb‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,17 @@ def initialize(attrs, options, required, scope, opts)
2626
# HashWithIndifferentAccess key conversion each time, for every coerced
2727
# attribute of every request.
2828
def validate_param!(attr_name, params)
29-
validation_error!(attr_name) unless hash_like?(params)
29+
return unless hash_like?(params)
3030

3131
value = params[attr_name]
32+
# Left out rather than sent as null, which reads the same. Only a
33+
# +nil+ is looked up, so a param that was sent spares the Hash the
34+
# lookup (see #validates_missing?).
35+
return if value.nil? && !params.key?(attr_name)
36+
3237
new_value = coerce_value(value)
3338

34-
validation_error!(attr_name, new_value.message || exception_message) if new_value.is_a?(Types::InvalidValue)
39+
invalid!(attr_name, new_value) if new_value.is_a?(Types::InvalidValue)
3540

3641
# Don't assign a value if it is identical. It fixes a problem with Hashie::Mash
3742
# which loses wrappers for hashes and arrays after reassigning values
@@ -49,6 +54,21 @@ def validate_param!(attr_name, params)
4954

5055
private
5156

57+
# Asked about every required attribute, unlike the other validators,
58+
# as it reads each one anyway: every typed param has a coercion, and
59+
# on the elements of an Array the key lookup cost a nested body of 20
60+
# items some 5%. A param left out is still never coerced. An optional
61+
# one is asked about only when it was sent, as a request leaves most
62+
# of those out, and reading one that is not there costs a
63+
# HashWithIndifferentAccess more than asking whether it holds it.
64+
def validates_missing?
65+
required?
66+
end
67+
68+
def invalid!(attr_name, invalid_value)
69+
validation_error!(attr_name, invalid_value.message || exception_message)
70+
end
71+
5272
# Calls the converter built at definition time.
5373
# Custom coercers may raise; any StandardError is treated as an invalid value.
5474
def coerce_value(val)

‎lib/grape/validations/validators/except_values_validator.rb‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,6 @@ def initialize(attrs, options, required, scope, opts)
2323
end
2424

2525
def validate_param!(attr_name, params)
26-
return unless hash_like?(params) && params.key?(attr_name)
27-
2826
excepts = current_excepts
2927
return if excepts.nil?
3028

‎lib/grape/validations/validators/length_validator.rb‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@ def initialize(attrs, options, required, scope, opts)
1616
end
1717

1818
def validate_param!(attr_name, params)
19-
return unless hash_like?(params)
20-
2119
param = params[attr_name]
2220

2321
return unless param.respond_to?(:length)

‎lib/grape/validations/validators/oneof_validator.rb‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@ def initialize(attrs, options, required, scope, opts)
1818
end
1919

2020
def validate_param!(attr_name, params)
21-
return unless hash_like?(params)
22-
2321
value = params[attr_name]
2422
return if value.nil? && !required?
2523

‎lib/grape/validations/validators/presence_validator.rb‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,12 @@ def validate_param!(attr_name, params)
1111

1212
validation_error!(attr_name)
1313
end
14+
15+
private
16+
17+
def validates_missing?
18+
true
19+
end
1420
end
1521
end
1622
end

0 commit comments

Comments
 (0)