Berislav Lopac
Berislav Lopac

Reputation: 17273

REST services: What is the best practice for formatting request vs. response?

Specifically, here's the scenario in case: A a request can have a body (POST or PUT) which is formatted in a format specified in the Content-Type header -- say, application/json. However, the URI includes a formatting hit for a different format (say as ?_format=xml or resource_uri.xml) which is usually used to denote the response formatting. I see three possible solutions here:

  1. The Content-Type of the request is ignored and the request body is parsed as if it's in the format denoted by URI.
  2. The URI mark is ignored and both request and response are assumed to be formatted as defined by Content-Type.
  3. The request body is parsed according to the Content-Type, and the response is formatted as hinted by the URI.

Personally I like the approach #3, but am a bit worried about the difference in the formats. What is the usual practice here, is it acceptable to have request and response in different formats? If not I'd prefer approach #1, while #2 seems totally off and unintuitive. Any suggestions here?

Upvotes: 1

Views: 256

Answers (2)

William Durand
William Durand

Reputation: 5519

Approach #3 is ok, and I would say you can rely on the Accept header to determine the response format. That way, the Content-Type header sets the request format, and either the Accept header or the _format query parameter sets the response format.

Upvotes: 1

Jon
Jon

Reputation: 437834

Approach #3 is the only sane of the three, also allowing the request and response to be in different formats. This is a good thing, as typically the request is in one fixed format while the response can be rendered in whatever supported format the client prefers.

Approach #1 obviously abuses HTTP and should never see the light of day.

Approach #2 is also quite bad because there is a different header for what response format the client expects: Accept.

So in a nutshell: you can do it the way HTTP intended (using the Accept header), or provide some convenience to the clients by allowing the format to be specified inline in the URL. You could also do both (if the Accept header specifies a format then use that, otherwise also check the URL).

Upvotes: 2

Related Questions