JSON vs XML in API

George Reese recently wrote a blog post about API design, William Vambenepe commented here. This is an interesting topic, I have a post on this subject too - it’s titled Developing API Server - Practical Rules of Thumb. In this post I would like to expand on the first point George made in his post - JSON vs XML.

As you may know, I led design and development of VPN-Cubed API at CohesiveFT, therefore I am approaching this subject primarily from perspective of API server side, not client.

We designed VPN-Cubed API to be able to support both JSON and XML. Since GET requests in HTTP have no body, arguments must be passed in query string. For all other HTTP methods, we take the arguments as a hash, convert them to JSON (or XML), set Content-Type header appropriately and send the resulting representation of arguments as a body of our request. Client also selects the format in which it wants to get response by using Accept header. We assume default value of application/json - which means JSON responses are sent by default.

Despite being designed for both JSON and XML, VPN-Cubed API ended up shipped with JSON only. And there is a reason why we chose JSON over XML.

Generally speaking, API is exchange of messages - client submits a request, server returns its response (example: “need new instance with these parameters” - “here is current representation of the instance object you requested”). In most domains, overwhelming majority of messages map nicely to nested lists (arrays) and hashes (dictionaries). This is a key insight that plays a role in JSON vs XML battle.

There is no easy and universal way how to represent nested hashes and arrays using XML (if there is, I hope to hear from you about it - I need stable libraries that can convert arrays and hashes to XML and back that could interop among each other for all major programming languages). Of course it’s possible and not terribly difficult, but it’s something that one must do.

Contrast this situation with JSON - you don’t need to worry about this, it’s already taken care of for you. The only limitation of JSON that we faced was that JSON doesn’t like integers as hash keys, it wants you to convert them to strings or use an array instead of a hash.

There are certainly some features in XML that JSON doesn’t have, but this is a show stopper. While your mileage may vary, I think this is the biggest reason why JSON has been slowly making ground against XML in API world recently. See also this post on Programmable Web.

Categories: software-engineering | cohesiveft |