24

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?

mahemoff
  • 44,526
  • 36
  • 160
  • 222

7 Answers7

44

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

Community
  • 1
  • 1
DRobinson
  • 4,441
  • 22
  • 31
  • #binding.pry respond_to do |format| if (request.content_type == "application/json") format.json {render json: @user} elsif (request.content_type == "application/xml") format.xml {render xml: @user} else format.html end end –  Aug 01 '17 at 18:25
26

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

request.format.symbol == :json
montrealmike
  • 11,433
  • 10
  • 64
  • 86
Kent Mewhort
  • 1,158
  • 12
  • 11
23

Another way of writing it:

request.format.json?
montrealmike
  • 11,433
  • 10
  • 64
  • 86
12

No need to call #symbol since equals is overloaded:

request.format == :json
Tim Scott
  • 15,106
  • 9
  • 65
  • 79
3

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

    if request.content_type =~ /json/
Leszek
  • 39
  • 1
2

request.format == 'application/json'

amn
  • 180
  • 2
  • 6
1

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']

Bhaveshkumar
  • 479
  • 4
  • 9