@@ -650,13 +650,13 @@ Parameters can also be tagged to the method declaration itself.
650650
651651``` ruby
652652class 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
656656end
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
662662It'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
670670end
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
675702Grape by default anchors all request paths, which means that the request URL
0 commit comments