Skip to content

Commit 575e6fc

Browse files
committed
Merge pull request ruby-grape#195 from ppadron/master
Updating "Describing and Inspecting an API" to reflect actual behavior
2 parents eb1055e + ef39b39 commit 575e6fc

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

README.markdown

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -650,13 +650,13 @@ Parameters can also be tagged to the method declaration itself.
650650

651651
``` ruby
652652
class StringAPI < Grape::API
653-
get "split/:string", { :params => [ "token" ], :optional_params => [ "limit" ] } do
653+
get "split/:string", { :params => { "token" => "a token" }, :optional_params => { "limit" => "the limit" } } do
654654
params[:string].split(params[:token], (params[:limit] || 0))
655655
end
656656
end
657657

658-
StringAPI::routes[0].route_params # yields an array [ "string", "token" ]
659-
StringAPI::routes[0].route_optional_params # yields an array [ "limit" ]
658+
StringAPI::routes[0].route_params # yields a hash {"string" => "", "token" => "a token"}
659+
StringAPI::routes[0].route_optional_params # yields a hash {"limit" => "the limit"}
660660
```
661661

662662
It's possible to retrieve the information about the current route from within an API call with `route`.
@@ -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+
return unless route.route_params
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)