R – Content-Type and Representations


What is the common convention for supporting multiple representation (e.g. html, json, xml) for resources (e.g. blog, user) in django?

First, I don't know how I should format my urls. For example, what your take on using either of these urls to request xml format

  • /<resource>.<format>, e.g. /blogs/123.xml
  • /<format>/<resource>, e.g. /xml/blogs/123
  • /<resource>?format=<format>, e.g. /blogs/123?format=xml

Should I just rely on the Content-Type passed parameter? What about having multiple mobile representation (e.g. iphone, mobile, palm) and full browser representation?

What about views? What's the convention for choosing the right templates without having a lot of if statements or much duplicate code.

Best Solution

What I might do, if this were to work out, is:

  • Your views look for the Accept header (I think that's what you were talking about) and decide which content-type to send back based on the Accept header.
  • You have a middleware which looks for an extension in the Request-URI, removes it, and adds the associated content-type to the request Accept header.

For this solution, content-types in the URL would always be represented as an associated file extension, neither part of the query-string nor part of the resource name. But aside from browser-generated requests, the content-types should be coming in through the Accept header.

So the request comes in as:

GET /blogs/123.xml HTTP/1.1
Host: example.com

The middleware transforms that to:

GET /blogs/123 HTTP/1.1
Host: example.com
Accept: application/xml

Your view sees application/xml and returns a response with XML content.