Preventing breaking changes in your JSON API

December 27, 2016 REST, JSON

JSON has become the de facto standard when developing RESTful services. There are multiple reasons why, which I'm not going to explain; instead, I'll give you a tip on how to prevent breaking changes.

The tip: wrap your business objects!

Take, for instance, this completely fictional use case.

{
  "name": "Jeroen Bellen",
  "age": 28,
  "country": 32
}

This code was designed to retrieve some user data, including the user's country. The developer added the "country id" because the screen which renders this object contains a list of countries. Initially, there were no problems; the screen worked. However, a few weeks after the release, we needed to reuse this object to render a cool, new feature, but we did not have the list of countries available! We wanted to limit API calls as transatlantic latency is an issue, so we decided to add the country name to the object, but how?
We certainly did not want to tell the client we have to redo the previous work! So, we added a new property, "countryName."

{
  "name": "Jeroen Bellen",
  "age": 28,
  "country": 32,
  "countryName": "Belgium"
}

OK, this saved the day, but we certainly aren't going to win any prizes with this solution! We are polluting the user contract to fit our specific needs. We see a clear violation of the user domain.
What if we had proactively foreseen the initial contract and designed it like this?

{
  "name": "Jeroen Bellen",
  "age": 28,
  "country":  {
    "id": 32
  }
}

Now, we are ready to add the country name, population, average taxable income or whatever info that is related to the country object!
In my opinion, this small tip can make your life a bit easier when developing RESTful services.

Jeroen Bellen
Alken
Dissident blogger!