mahemoff
mahemoff

Reputation: 46379

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?

Upvotes: 25

Views: 43088

Answers (8)

Bhaveshkumar
Bhaveshkumar

Reputation: 509

Seriously require focus to understand here. Ref. Rails 6.x with api only project

You have to make sure why you want request.content_type OR request.headers['Content-Type'] ? Explained below...

  1. request.format OR request.headers['Accept'] is what format client is expecting to request's response by API(Service or Server).

  2. request.content_type OR request.headers['Content-Type'] is what API(Service or Server) is expecting data format from request.

So if API(Service or Server) wants to request's data in application/json then you are right with request.content_type OR request.headers['Content-Type']

Upvotes: 3

Nick Roz
Nick Roz

Reputation: 4230

I think all the previous answers are misleading a bit, although some of them are correct, and the most precise one is not formatted enough to highlight the problem. Other did not mention explicitly that there are two different headers, so the answers which suggested to use request.format put you in a very risky situation of checking the wrong thing.

First of all, Rails (verified with >=4.2) treats these headers as case-insensitive

request.headers['CONTENT_TYPE'] # "application/json"
request.headers['Content-type'] # "application/json"
request.headers['Content-Type'] # "application/json"

May be your question was related to previous Rails version, since it was asked in 2013.

To avoid messing with headers is better to use dedicated methods for that:

Method Header Meaning
request.content_type Content-Type What a client is sending to you
request.format Accept What a client is expecting from you

Upvotes: 0

amn
amn

Reputation: 180

request.format == 'application/json'

Upvotes: 2

Kent Mewhort
Kent Mewhort

Reputation: 1158

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

request.format.symbol == :json

Upvotes: 26

montrealmike
montrealmike

Reputation: 11631

Another way of writing it:

request.format.json?

Upvotes: 24

Tim Scott
Tim Scott

Reputation: 15205

No need to call #symbol since equals is overloaded:

request.format == :json

Upvotes: 12

Leszek
Leszek

Reputation: 39

For me the best way to check if incoming request is a json was:

    if request.content_type =~ /json/

Upvotes: 3

DRobinson
DRobinson

Reputation: 4471

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

Upvotes: 46

Related Questions