Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Rails to respond with json based on headers

I'm building an API with Rails 4 and in my controller I'm using respond_to to differentiate between html and json request which all works fine. While testing my API in Postman, I've added the following header: Content-Type: application/json but in my request I still need to add .json at the end of it like so: https://myapi.com/api/users.json otherwise Rails will respond with html even though the aforementioned header is present.

My question is this: is there a way that Rails can recognise the Content-Type: application/json header and respond with json without me using the .json part in the url like so: https://mypai.com/api/users?

like image 235
WagnerMatosUK Avatar asked Oct 19 '25 05:10

WagnerMatosUK


1 Answers

You also need to set the Accept header to Accept: application/json

If you're curious as to why, and the difference between the two headers, the answers to this post explain it best: https://webmasters.stackexchange.com/questions/31212/difference-between-the-accept-and-content-type-http-headers

like image 174
iam3v4n Avatar answered Oct 21 '25 20:10

iam3v4n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!