Skip to content

Commit 6d8793f

Browse files
committed
Merge pull request ruby-grape#125 from jaghion/send_data
allow APIs to declare additional content-types
2 parents 34812f9 + aea29fd commit 6d8793f

File tree

4 files changed

+30
-1
lines changed

4 files changed

+30
-1
lines changed

README.markdown

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,16 @@ end
209209
end
210210
end
211211

212+
## Content-Types
213+
214+
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.
215+
216+
```ruby
217+
class Twitter::API < Grape::API
218+
content_type :xls, "application/vnd.ms-excel"
219+
end
220+
```
221+
212222
## Writing Tests
213223

214224
You can test a Grape API with RSpec. Tests make HTTP requests, therefore they

lib/grape/api.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,12 @@ def error_format(new_format = nil)
122122
new_format ? set(:error_format, new_format.to_sym) : settings[:error_format]
123123
end
124124

125+
# Specify additional content-types, e.g.:
126+
# content_type :xls, 'application/vnd.ms-excel'
127+
def content_type(key, val)
128+
settings.imbue(:content_types, key.to_sym => val)
129+
end
130+
125131
# Specify the default status code for errors.
126132
def default_error_status(new_status = nil)
127133
new_status ? set(:default_error_status, new_status) : settings[:default_error_status]

lib/grape/endpoint.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,9 @@ def build_middleware
248248
}
249249
end
250250

251-
b.use Grape::Middleware::Formatter, :default_format => settings[:default_format] || :json
251+
b.use Grape::Middleware::Formatter,
252+
:default_format => settings[:default_format] || :json,
253+
:content_types => settings[:content_types]
252254

253255
aggregate_setting(:middleware).each do |m|
254256
m = m.dup

spec/grape/api_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,17 @@ def hello
679679
end
680680
end
681681

682+
describe ".content_type" do
683+
it "sets additional content-type" do
684+
subject.content_type :xls, "application/vnd.ms-excel"
685+
subject.get(:hello) do
686+
"some binary content"
687+
end
688+
get '/hello.xls'
689+
last_response.content_type.should == "application/vnd.ms-excel"
690+
end
691+
end
692+
682693
describe ".default_error_status" do
683694
it 'should allow setting default_error_status' do
684695
subject.rescue_from :all

0 commit comments

Comments
 (0)