jfcalvo
jfcalvo

Reputation: 485

Creating a route with Sinatra to only accept a certain Content-type

I'm trying to create a route with Sinatra that only accepts POST with an Content-type: application/json without success.

My approach is as follows:

post '/dogs', :provides => :json do
  # returns here a json response
end

Testing with curl, I have seen that :provides => :json configures the route to respond with an Content-Type: application/json.

That's right because I want also to respond with a JSON message to the POST request but I really need that this route only respond to POST requests with a Content-Type: application/json and not, for example, to others (e.g. Content-Type: application/xml).

Is there any way in Sinatra to restrict the route to only accept requests with a certain Content-Type?

Upvotes: 10

Views: 10250

Answers (3)

Mischa Molhoek
Mischa Molhoek

Reputation: 164

i would think it is something like:

pass unless request.accept? == 'application/json'

Upvotes: 0

Geoff
Geoff

Reputation: 111

Read this

http://rack.rubyforge.org/doc/classes/Rack/Request.html

request.content_type will tell you

Phil might be right regarding RFC but in reality many things put a content-type in a POST request, therefore it is useful to know what it is.

Upvotes: 11

phil pirozhkov
phil pirozhkov

Reputation: 4899

Requests do not contain "Content-Type" header, but rather have "Accept". Sinatra should basically only respond to requests with "Accept" containing "application/json". Just to make sure:

post '/gods', :provides => :json do
  pass unless request.accept? 'application/json'
...
end

Upvotes: 12

Related Questions