Can a RESTful service return both JSON and XML for the same resource, depending on the request header?

44,526

Solution 1

The same resource may return either XML or JSON depending upon the request, but it shouldn't return both at the same time. You will know which one to return based upon the request, so there is no need to generate both -- just generate the one you'll be returning.

Here is how you might choose to decide which to return. Evaluate in order, stopping when you've determined the format to return:

  1. If an extension has been added to the resource (GET /user/1234.json or GET /user/1234.xml), use that as the requested format.
  2. If an Accept header is set, use that header's value as the requested format.
  3. If there is a request body (as in the case of a POST), and the Content-Type header specifies JSON or XML, use that.
  4. Use a default format if none of the above apply (generally use JSON as your default unless your customers are generally still using XML).

Solution 2

No. The way you represent your resource should be defined by what your clients expect (there is a http-header to say what representations the client accept). This means your server should check what is the representation the current client accepts and send the response in this representation (or send a response that says he cannot represent the resource in that media-type)

Share:
44,526
Nital
Author by

Nital

Updated on July 18, 2022

Comments

  • Nital
    Nital almost 2 years

    I have a simple RESTful method which currently returns JSON representation of an object.

    My question is more of from the architectural perspective and not completely technical.

    Should a RESTful service be designed in such a way that it returns both JSON and XML at the same time?

    As far as I know this is a bad practice and separate resources should be defined for this. One resource should return JSON data and other one XML.

    Am I thinking it correctly?