11 February, 2009...1:21 am

Setting the default request format for a Rails app

Jump to Comments

While working on an external api for an application we are developing at the moment  (we being the company I work for, www.tty.nl), I came across a small problem which I could not find the answer for, how to set the default response format for a url or set of urls (eg. /people  would use display xml to the client without the need for the .xml extension or format=xml querystring parameter).

Well, I personally could not find any good sample code to do so, I did find one at the Ruby is Beautiful blog which suggested a bit of code that modified the request headers and request environment but not using the rails conventions, it was a bit intrusive for my liking. So I instead decided to see if there was a better was to go about this.

Solving the problem turned out to be quite easy. Rails uses two methods to determine what response format to use, the first is the request header, and the second is the request parameter ‘format’, with the latter taking priority over the former. Have a read up on Routes Inside Out at Rails Guides for a bit more information on the request header. I also recommend you get your hands dirty with some of the internal workings of the rails code base, have a read into request.rb of actionpack (2.2.2) (line 144), as well as mime_responds.rb. 

Anyhow, the simple code is as follows….

  before_filter :set_default_response_format

  protected

    def set_default_response_format
      request.format = 'xml'.to_sym if params[:format].nil?
    end

Sorry but due to WordPress formatting, I had to use the to_sym method instead of just a straight symbol as WordPress would then turn it into one of those annoying smiley face images.

Anyhow, as you can see, if the url is missing a .<ext> or ?format=<ext> (both of which are then added to params[:format]) then the default request format is set to :x ml (see what I mean, annoying smiley face image!), which is normally :html or decided from the Accept header. (The Rails docs pretty much tell you how to use the format= method - RailsBrain)

I hope this helps,

Josh

1 Comment

  • Great post. For the public APIs I have been building the users have been sending Content-type application/xml (when sending XML) and Accept text/xml for receiving xml. I respond with YAML by default, eg. in the HTML response block. I may change the default to something like you have shown though because it is more explicit what is happening.

    BTW, you can completely disable smilies/emoticons if you wish… I am happy with text version myself ;)

    http://codex.wordpress.org/Using_Smilies

    I wonder if thinsp would help… : )


Leave a Reply