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

allow APIs to declare additional content-types #125

Merged
merged 3 commits into from
Jan 22, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,16 @@ end
end
end

## Content-Types

By default, Grape supports _XML_, _JSON_, _Atom_, _RSS_, and _text_ content-types. Your API can declare additional types to support. Response format is determined by the request's extension or `Accept` header.

```ruby
class Twitter::API < Grape::API
content_type :xls, "application/vnd.ms-excel"
end
```

## Writing Tests

You can test a Grape API with RSpec. Tests make HTTP requests, therefore they
Expand Down
6 changes: 6 additions & 0 deletions lib/grape/api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,12 @@ def error_format(new_format = nil)
new_format ? set(:error_format, new_format.to_sym) : settings[:error_format]
end

# Specify additional content-types, e.g.:
# content_type :xls, 'application/vnd.ms-excel'
def content_type(key, val)
settings.imbue(:content_types, key.to_sym => val)
end

# Specify the default status code for errors.
def default_error_status(new_status = nil)
new_status ? set(:default_error_status, new_status) : settings[:default_error_status]
Expand Down
4 changes: 3 additions & 1 deletion lib/grape/endpoint.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,9 @@ def build_middleware
}
end

b.use Grape::Middleware::Formatter, :default_format => settings[:default_format] || :json
b.use Grape::Middleware::Formatter,
:default_format => settings[:default_format] || :json,
:content_types => settings[:content_types]

aggregate_setting(:middleware).each do |m|
m = m.dup
Expand Down
11 changes: 11 additions & 0 deletions spec/grape/api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,17 @@ def hello
end
end

describe ".content_type" do
it "sets additional content-type" do
subject.content_type :xls, "application/vnd.ms-excel"
subject.get(:hello) do
"some binary content"
end
get '/hello.xls'
last_response.content_type.should == "application/vnd.ms-excel"
end
end

describe ".default_error_status" do
it 'should allow setting default_error_status' do
subject.rescue_from :all
Expand Down