Rails HTML Render JSON Request

In my controller, I support HTML and JSON in my index method by doing:

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

When pulling it in a browser, it visually displays the HTML. However, when I make a curl call with the application/json content type in the /user resource (since this is an index method), I still get HTML as an answer.

How can I get JSON as an answer? What else do I need to specify?

+4
source share
1 answer

You must add .json to the requested URL if the format is specified in the path in routes.rb . This value is used when using resources . For example, rake routes should give you something like:

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

To get a user in HTML

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

To get a user in JSON:

 curl http://localhost:3000/users/1.json 
+7
source

Source: https://habr.com/ru/post/1485564/


All Articles