Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails HTML Request Render JSON

In my controller, I'm supporting HTML and JSON in my index method by doing:

respond_to do |format|
  format.html
  format.json { render json: @user }
end

When pulling it up in the browser, it renders in HTML naturally. However, when I do a curl call with content-type being application/json to the /user resource (since it's the index method), I still get the HTML as a response.

How can I get the JSON as a response? What else do I need to specify?

like image 306
darksky Avatar asked Jun 11 '13 06:06

darksky


1 Answers

You should append .json to the requested url, provided format is defined in the path in routes.rb. This is default when using resources. For example, rake routes should give you something like:

show_user GET    /users/:id(.:format) users#show

To get user in HTML

curl  http://localhost:3000/users/1  

To get user in JSON:

curl http://localhost:3000/users/1.json    
like image 107
Baldrick Avatar answered Nov 20 '22 12:11

Baldrick