Get Content Type of Request

37,363

Solution 1

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

Solution 2

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

request.format.symbol == :json

Solution 3

Another way of writing it:

request.format.json?

Solution 4

No need to call #symbol since equals is overloaded:

request.format == :json

Solution 5

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

    if request.content_type =~ /json/
Share:
37,363

Related videos on Youtube

mahemoff
Author by

mahemoff

Home http://mahemoff.com GitHub https://github.com/mahemoff Blog http://softwareas.com Twitter @mahemoff LinkedIn Mahemoff

Updated on August 26, 2020

Comments

  • mahemoff
    mahemoff over 3 years

    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?

    • Intrepidd
      Intrepidd about 11 years
      What version of rails are you working with ?
    • DRobinson
      DRobinson about 11 years
      Judging by the tags he attached, probably 3.1
  • Admin
    Admin almost 7 years
    #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
  • Nathan B
    Nathan B almost 3 years
    But if the request accept header is /, it will still be false, right?