Python – Handle backward compatibility on API changes

apiArchitecturebackward compatibilitylibrariespython

I have an API which allows me to communication with a device.
The communication protocol is stored in a JSON file. It list the events that the device can raise, the functions, the frames format, etc.

But this JSON file changes often, and i need to keep my API backward compatible with all the JSON files.

I imagined some solutions (i am using Python):

  1. Use decorators on my functions (@api_1, @api_2 …) but it will be too heavy when i will reach api 5 or more

  2. Make a folder for each API changes

    1. /APIs
      1. API_1
        1. frame_translation.py …
      2. API_2
        1. frame_translation.py …
  3. A strategy pattern ?

The second solution seems already better than the first one, but probably not the best.

How would you do it ?

Best Answer

Given your current approach, the change in communication protocol shouldn't lead to API change: since the communication protocol is stored in a JSON file, the API structure remains the same for all the devices as soon as their communication protocol can effectively be described through JSON.

When communicating with a given device, the caller of your API simply has to specify the version of the communication protocol—either by specifying the JSON or by using an actual device ID and/or version, if it allows the API to find the corresponding JSON.

When you'll have to actually change the version of the API is if newer devices use features which aren't supported by the previous API, no matter how you modify a given JSON.

As a comparison, look at how USB standard works: you (luckily) don't have to update your operating system every time a new USB device is released; what you need, however, to do is to install the devices' drivers which indicate to the operating system how to communicate with a device—this is similar to your JSON files. However, USB 2 was superseded by USB 3 to provide higher speed and many other enhancements—something which wouldn't be possible by simply adding a driver.

Related Topic