Specify Rails Response Type via the URL
One of the features of Rails 1.1 was the ability to automatically detect clients that could understand XML and send XML responses to them using the respond_to method. This also works for AJAX requests and HTML, of course. Unfortunately, though, this relies on XML and API clients sending the correct Accept headers in most cases, and, as we all know, users aren't necessarily so smart (even API users!).
In response to this problem, Edge Rails now accepts the format parameter on the URL, like so: http://www.yourapp.com/post/show/1?format=xml So while the Accept header method still works, you can also pass in the format directly via the URL. I suggested that also allowing a subdomain to specify the content type could also work (e.g: all requests to api.yourapp.com could require an XML response), and Ryan Daigle came up with an elegant solution here. For reference:
map.connect '/post/show', :controller => 'post', :action => 'show', :format => 'xml', :requirements => { :subdomain => 'api' }
June 27, 2006 at 6:41 pm
From David's keynote at RailsConf, the actual URL would become:
http://www.yourapp.com/post/show/1.xml
...and Rails would strip off the extension to do it's normal routing, but set the respond_to answer as XML, so you can spit that format back out. So instead of a special parameter to handle format desired, just add on the extension to the URL of the content format you'd like back and if the app supports it, you'll get it.
June 27, 2006 at 7:37 pm
Thanks for clarifying this, Chris. The original post was made before the keynote and was based on the 'current' edge Rails knowledge, but the changes covered in the keynote are significant and important :)
Pingback: http://www.securedpersonalloan.org.uk