Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 616
jfcalvo Avatar asked Nov 22 '11 10:11

jfcalvo


1 Answers

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
like image 166
phil pirozhkov Avatar answered Sep 30 '22 18:09

phil pirozhkov