In Sinatra is it possible to make content_type 'application/json'
the default? Because I'm building a REST API.
Asked
Active
Viewed 2.5k times
2 Answers
77
Sure, add content_type
to the before
callback:
class MyApp < Sinatra::Base
before do
content_type 'application/json'
end
...
end
Sinatra 1.1 introduces pattern-matching before filters:
before '/admin/*' do
check_logged_in
end

Adam Lassek
- 35,156
- 14
- 91
- 107
-
Thanks! How do I create a context so that the before filter is only applied to a specific group of routes and not all? – ma11hew28 Jan 08 '11 at 03:18
-
@MattDiPasquale This should do the trick: http://blog.alastairdawson.com/2010/07/27/a-sinatra-before-only-filter/ – Adam Lassek Jan 08 '11 at 03:20
-
@MattDePasqaule you can also override the content type within individual routes. – Adam Lassek Jan 08 '11 at 23:52
-
1sinatra 1.1 supports pattern before filter, so the patch is not necessary. – Konstantin Haase Jan 10 '11 at 16:37
-
@Konstantin thanks for the heads up, much better than my suggestion. – Adam Lassek Jan 11 '11 at 00:17
-
@Adam Lassek, thanks for all your help! @Konstantin, pretty sweet. Thanks! Oh yeah, I see [before filters with pattern matching](http://www.sinatrarb.com/intro#Filters) on the README now. I must've missed that. Thanks. – ma11hew28 Jan 12 '11 at 20:48
6
For a JSON API the most recommendable way to set a default Content-Type
for all your responses is to add the following in your Sinatra class:
set :default_content_type, :json
It will include a Content-Type: application/json
header in all your responses.

Pere Joan Martorell
- 2,608
- 30
- 29