Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful Content Negotiation in Rails

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!

like image 615
Alexander Trauzzi Avatar asked Jul 04 '09 16:07

Alexander Trauzzi


2 Answers

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.

like image 63
tjercus Avatar answered Oct 31 '22 14:10

tjercus


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.

like image 43
John Topley Avatar answered Oct 31 '22 14:10

John Topley