Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Content Type of Request

To find the incoming content type, docs say:

 request.headers["Content-Type"] # => "text/plain"

But I found by trial-and-error, that doesn't work, but this does:

 request.headers["CONTENT_TYPE"]=='application/json'

So what's the most robust+portable way to do it?

like image 908
mahemoff Avatar asked Mar 05 '13 15:03

mahemoff


People also ask

What is Content-Type for GET request?

The content type of the requests for these is always x-www-form-urlencoded, since that is all that is allowed for GET and DELETE requests by the HTTP protocol. The client indicates what content type it can accept in the response by supplying an Accept header.

Do I need Content-Type for GET request?

Since (by validity of the input spec) there are no content types for GET requests, you will always default to application/json .

Is Content-Type for request or response?

Content-type is about the content of the current request or response, depending on which kind of HTTP message it is applied. So if a request has no payload, you don't have to send a content-type request header, and the same goes for your response: no body, no header necessary.

Is Content-Type a request header?

The Content-Type http request header specifies the content type of the http request payload. The Content-Type header is NOT tied to the content type of the response sent by the server. Here's an example using pure JavaScript to make an asynchronous HTTP request from the browser.


3 Answers

I would usually go for request.format and request.content_type for reading these header fields.

EDIT: found a bit more on this that might help: https://stackoverflow.com/a/1595453/624590

like image 198
DRobinson Avatar answered Oct 12 '22 11:10

DRobinson


You don't need to parse the content_type string, Rails has already done this for you. Just check:

request.format.symbol == :json
like image 25
Kent Mewhort Avatar answered Oct 12 '22 11:10

Kent Mewhort


Another way of writing it:

request.format.json?
like image 21
montrealmike Avatar answered Oct 12 '22 12:10

montrealmike