Ruby Weekly is a weekly newsletter covering the latest Ruby and Rails news.

Specify Rails Response Type via the URL

By Peter Cooper / June 11, 2006

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: 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 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' }


  1. Chris says:

    From David's keynote at RailsConf, the actual URL would become:

    ...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.

  2. Peter Cooper says:

    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 :)

  3. Pingback:

Other Posts to Enjoy

Twitter Mentions