47

In Sinatra is it possible to make content_type 'application/json' the default? Because I'm building a REST API.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

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
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