6

I'm looking to implement content negotiation on some resources in a Rails app. I'm using Mootools and will likely be able to tweak the content type accepted by an XMLHTTPRequest to "application/json".

Is there any way to pick up on this information in my controller and generate JSON responses instead of XHTML?

I'm trying to avoid doing something like:

http://site/resource/1?format=JSON

...as it dirties up my URL, imposes a certain degree of redundancy and is not as flexible.

Thanks!

Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112

4 Answers4

9

http://site/resource/1.json is not correct use of content-negotiation. The point is that the URL should remain the same, but the client asks for a specific representation (JSON, PDF, HTML etc.) based on HTTP headers it sends with the request.

tjercus
  • 91
  • 1
  • 1
  • `http://site/resource/1.json is not correct use of content-negotiation` Why this is not correct? May you provide links to spec or blog post? – Eugen Konkov Mar 19 '18 at 07:56
  • The URL itself `example.com/users/adeynack` represents the resource. In this case, a user. The `Accept` header, as described in the [HTTP RFC](https://tools.ietf.org/html/rfc2616#section-14.1), represent _under which representation do you want to have the resource_. The `json` needs to be in this header and not in the URL. Although I appreciate what Rails did here for convenience, it is not following HTTP standards. tjercus is right here. I hope the link to the RFC helps, eugen-konkov (they tend to be a bit dry to read). – Adeynack Nov 12 '18 at 08:51
4

You can use a respond_to stanza in your controller method, like this:

respond_to do |format|
  format.html { # Generate an HTML response... }
  format.json { # Generate a JSON response... }
end

Rails determines the response format based on the value of the HTTP Accept header submitted by the client.

John Topley
  • 113,588
  • 46
  • 195
  • 237
1

Surely http://site/resource/1.json should work? you may need to set it up in your Rails Environment, though, depending on how current the version of Rails you have is, I doubt it.

Omar Qureshi
  • 8,963
  • 3
  • 33
  • 35
0

After much research, while rails has everything to automatically select a template for output, it still requires the call to respond_to for each one you wish to support.

Alexander Trauzzi
  • 7,277
  • 13
  • 68
  • 112