Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating "Describing and Inspecting an API" to reflect actual behavior #195

Merged
merged 3 commits into from Jul 3, 2012
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
33 changes: 30 additions & 3 deletions README.markdown
Expand Up @@ -650,13 +650,13 @@ Parameters can also be tagged to the method declaration itself.

``` ruby
class StringAPI < Grape::API
get "split/:string", { :params => [ "token" ], :optional_params => [ "limit" ] } do
get "split/:string", { :params => { "token" => "a token" }, :optional_params => { "limit" => "the limit" } } do
params[:string].split(params[:token], (params[:limit] || 0))
end
end

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

It's possible to retrieve the information about the current route from within an API call with `route`.
Expand All @@ -670,6 +670,33 @@ class MyAPI < Grape::API
end
```

You can use this information to create a helper that will check if the request has
all required parameters:

``` ruby
class MyAPI < Grape::API

helpers do
def validate_request!
# skip validation if no parameter is declared
if route.route_params.nil?; return end
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe unwrap this line?

return unless route.route_params

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hah, that's much better.

route.route_params.each do |k, v|
if !params.has_key? k
error!("Missing field: #{k}", 400)
end
end
end
end

before { validate_request! }

desc "creates a new item resource", :params => { :name => 'name is a required parameter' }
post :items do
...
end
end
```

## Anchoring

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