Juw
Juw

Reputation: 2089

REST mixing JSON and XML?

I am working on a small web service. Up until now I have been responding with JSON. But the problem I am having right now is the server my web service talks to responds with an XML that looks something like this:

<obj somedata="h1" somedata2="h5" xmldata="<xm debug="yes"/></xm>"/>

The xml data attribute contains XML. I could have just run json_encode() (PHP). But json_encode doesn't seem to want to encode the XML data attribute.

Is it bad practice if my web service responded with xml in this case and JSON in other cases? Of course I would set the Content-Type to application/xml and this will also be documented in the documentation for the service.

But is this bad? Should I do everything in my power to convert it to JSON just because I responded with JSON in other API functions?

Upvotes: 2

Views: 925

Answers (1)

kjhughes
kjhughes

Reputation: 111541

Is it bad practice if my web service responded with xml in this case and JSON in other cases?

Yes, it'd be horrible practice to return JSON in some cases and XML in others. But you already knew that.

Worse still, the "XML" you mention,

<obj somedata="h1" somedata2="h5" xmldata="<xm debug="yes"/></xm>"/>

is not XML at all as it is not well-formed: Attribute values cannot contain raw XML; yours has unescaped:

  • double quote characters (")
  • less than characters (<).

Recommendation: Have a JSON interface, or an XML interface, or ideally both separately.

If you cannot have both, use JSON unless:

  • Your data is document-centric.
  • There is an industry standard XML schema that governs your data.
  • You already know that your developer audience prefers XML.

Upvotes: 3

Related Questions