Skip to content

Commit 8049469

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`. 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. 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 19e5dad commit 8049469

11 files changed

Lines changed: 103 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@
5454
* [#3083](https://github.com/ruby-grape/grape/pull/3083): Apply a mounting API's `default_error_status` to routes defined before the mount - [@ericproulx](https://github.com/ericproulx).
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).
57+
* [#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).
5758
* Your contribution here.
5859

5960
### 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/base.rb‎

Lines changed: 15 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,15 @@ 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. Only PresenceValidator is, to report it missing. Every
122+
# other validator sees only the params a request sent, whether they
123+
# are required or not, so a missing one is reported once, and a
124+
# custom validator is never handed one that is not there.
125+
def validates_missing?
126+
false
127+
end
128+
119129
# A scope's parent, optionality, dependency and type are all set
120130
# before its block declares anything, so these are settled by the
121131
# time a validator is built. See #validate and #validate!.
@@ -138,7 +148,7 @@ def validate_attributes!(params)
138148
array_errors = nil
139149

140150
@attrs.each do |attr_name|
141-
validate_param!(attr_name, params) if required? || params.key?(attr_name)
151+
validate_param!(attr_name, params) if @validates_missing || params.key?(attr_name)
142152
rescue Grape::Exceptions::Validation => e
143153
(array_errors ||= []) << e
144154
end
@@ -196,11 +206,12 @@ def validate_iterated!(params)
196206
end
197207

198208
# 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.
209+
# one when this validator reports a missing one (see
210+
# #validates_missing?), and returns +array_errors+ with what failed
211+
# appended, allocating it on the first failure.
201212
def validate_element_attributes(element, array_errors)
202213
@attrs.each do |attr_name|
203-
validate_param!(attr_name, element) if required? || (hash_like?(element) && element.key?(attr_name))
214+
validate_param!(attr_name, element) if @validates_missing || (hash_like?(element) && element.key?(attr_name))
204215
rescue Grape::Exceptions::Validation => e
205216
(array_errors ||= []) << e
206217
end

‎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

‎spec/grape/validations/params_scope_spec.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1065,7 +1065,7 @@ def initialize(value)
10651065
post '/lines', { lines: [[{ name: 'x' }]] }.to_json, 'CONTENT_TYPE' => 'application/json'
10661066

10671067
expect(last_response.status).to eq(400)
1068-
expect(last_response.body).to eq('lines[0] is invalid, lines[0][name] is missing, lines[0][name] is invalid')
1068+
expect(last_response.body).to eq('lines[0] is invalid, lines[0][name] is missing')
10691069
end
10701070

10711071
it 'rejects elements wrapped in several extra arrays' do

‎spec/grape/validations/validators/oneof_validator_spec.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@
234234
it 'responds with a validation error instead of raising a TypeError' do
235235
post '/items', { items: ['str'] }.to_json, 'CONTENT_TYPE' => 'application/json'
236236
expect(last_response.status).to eq(400)
237-
expect(JSON.parse(last_response.body)['error']).to include('items[0][value] is invalid')
237+
expect(JSON.parse(last_response.body)['error']).to eq('items[0] is invalid, items[0][value] is missing')
238238
end
239239
end
240240

‎spec/grape/validations/validators/presence_validator_spec.rb‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def app
4242
it 'requires when missing' do
4343
get '/requires'
4444
expect(last_response.status).to eq(400)
45-
expect(last_response.body).to eq('{"error":"email is required, email has no value"}')
45+
expect(last_response.body).to eq('{"error":"email is required"}')
4646
end
4747

4848
it 'requires when empty' do
@@ -96,7 +96,7 @@ def app
9696
it 'requires when missing' do
9797
get '/'
9898
expect(last_response.status).to eq(400)
99-
expect(last_response.body).to eq('{"error":"email is missing, email is empty"}')
99+
expect(last_response.body).to eq('{"error":"email is missing"}')
100100
end
101101

102102
it 'requires when empty' do

‎spec/grape/validations/validators/regexp_validator_spec.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@
118118
it 'refuses inapppopriate' do
119119
get '/nested_regexp_with_array', people: 'invalid name'
120120
expect(last_response.status).to eq(400)
121-
expect(last_response.body).to eq('{"error":"people is invalid, people[names] is missing, people[names] is invalid"}')
121+
expect(last_response.body).to eq('{"error":"people is invalid, people[names] is missing"}')
122122
end
123123
end
124124

‎spec/grape/validations/validators/values_validator_spec.rb‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ def post_json(path, body)
254254
it 'reports a missing param the way the root scope does' do
255255
post_json '/address', address: {}
256256
expect(last_response.status).to eq 400
257-
expect(last_response.body).to eq({ error: 'address[country] is missing, address[country] does not have a valid value' }.to_json)
257+
expect(last_response.body).to eq({ error: 'address[country] is missing' }.to_json)
258258
end
259259

260260
it 'does not allow nil in a given block whose dependency is met' do
@@ -1190,7 +1190,7 @@ def app
11901190
get 'values_wrapped_by_with_block'
11911191

11921192
expect(last_response.status).to eq 400
1193-
expect(last_response.body).to eq({ error: 'type is missing, type does not have a valid value' }.to_json)
1193+
expect(last_response.body).to eq({ error: 'type is missing' }.to_json)
11941194
end
11951195
end
11961196
end

0 commit comments

Comments
 (0)