Skip to content

Commit c0bf125

Browse files
author
Pedro Padron
committed
adding parameter validation example to the README file
1 parent 21e5b78 commit c0bf125

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

README.markdown

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,33 @@ class MyAPI < Grape::API
670670
end
671671
```
672672

673+
You can use this information to create a helper that will check if the request has
674+
all required parameters:
675+
676+
``` ruby
677+
class MyAPI < Grape::API
678+
679+
helpers do
680+
def validate_request!
681+
# skip validation if no parameter is declared
682+
if route.route_params.nil?; return end
683+
route.route_params.each do |k, v|
684+
if !params.has_key? k
685+
error!("Missing field: #{k}", 400)
686+
end
687+
end
688+
end
689+
end
690+
691+
before { validate_request! }
692+
693+
desc "creates a new item resource", :params => { :name => 'name is a required parameter' }
694+
post :items do
695+
...
696+
end
697+
end
698+
```
699+
673700
## Anchoring
674701

675702
Grape by default anchors all request paths, which means that the request URL

0 commit comments

Comments
 (0)