Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default content_type for Sinatra

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

like image 516
ma11hew28 Avatar asked Jan 08 '11 03:01

ma11hew28


2 Answers

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
like image 153
Adam Lassek Avatar answered Nov 04 '22 22:11

Adam Lassek


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.

like image 26
Pere Joan Martorell Avatar answered Nov 04 '22 21:11

Pere Joan Martorell