Pythonium

Python, What else ?

How to handle API versioning without breaking existing clients

Evolving an API is inevitable. Over time, new features are added, some data needs to be restructured, and existing behaviors may need improvements or fixes.

The problem is that every change can affect applications that already use the API. A change that seems harmless on the server side can be enough to break a mobile application, cause errors in a third-party integration, or interrupt an automated process.

About twenty years ago, even the smallest change to a SOAP web service, such as adding a field or changing the order of elements, could break everything on the client side. Some clients were extremely picky about response structures (even the order of tags in the response was sometimes fixed...). Fortunately, things have moved on since then (or at least, I hope so!).

This is precisely why API versioning matters. It allows an interface to evolve without forcing all its users to adopt changes immediately.

But choosing a versioning strategy is not enough. You also need to know which changes are compatible, how to support older clients, and when to retire an obsolete version.

Understand why API changes can cause problems

An API is a contract between a provider and its clients. This contract defines the available endpoints, accepted parameters, response structures, and expected behavior.

Let's take a simple example. An API currently returns a user's information in the following format:

{
  "id": 42,
  "name": "John Doe",
  "email": "john@example.com"
}

A client application retrieves this information and directly uses the name property to display the user's name.

A few months later, following a request for a change, we decide to split the first and last names:

{
  "id": 42,
  "first_name": "John",
  "last_name": "Doe",
  "email": "john@example.com"
}

The new structure may be better suited to the project's needs, but the old client will no longer find the name property.

As a result, a feature that was working perfectly can start failing even though the client itself hasn't been modified.

This is known as a breaking change.

Here are a few examples of changes that can break compatibility:

  • Removing or renaming a property in a JSON response.
  • Changing the type of a property, for example, from a string to a number.
  • Making a previously optional parameter mandatory.
  • Changing the format of a date or identifier.
  • Changing the behavior of an existing endpoint.
  • Modifying authentication rules or the HTTP status codes returned.

The important thing to understand is that a change doesn't have to cause an HTTP error to be incompatible. A client may continue receiving a 200 OK response while interpreting the data incorrectly.

Choose an appropriate versioning strategy

There are several ways to handle API versions. The choice depends on factors such as the complexity of the project, the number of clients, and how the API is distributed.

Versioning in the URL

This is the most common approach and probably the easiest to understand.

Each version has its own path:

/api/v1/users
/api/v2/users

A client using the first version continues calling /api/v1/users, while new clients can use /api/v2/users.

This approach has several advantages:

  • Versions are easy to identify.
  • Multiple versions can run simultaneously.
  • Routing is relatively straightforward to configure.
  • Tests and documentation can be separated by version.

The main drawback is that it can lead to some duplication of endpoints and their business logic.

However, it's possible to share internal services and common components instead of maintaining two completely independent applications.

Versioning with HTTP headers

Another option is to specify the requested version in an HTTP header.

For example:

GET /api/users HTTP/1.1
Host: api.example.com
Accept: application/vnd.example.v2+json

The server then uses the Accept header to determine the expected response format.

This approach allows multiple versions to use the same URLs, but versioning becomes less visible and sometimes harder to track in logs. It also requires more careful handling of routing, HTTP caching, and documentation.

Versioning with a query parameter

It's also possible to specify the version in the URL as a query parameter:

/api/users?version=2

This solution is easy to implement, but it's generally less recommended for public APIs. It can make cache management more complicated and URLs less consistent.

For most projects, URL versioning is a good starting point. It's easy to understand and doesn't require any special mechanism on the client side.

Distinguish between compatible and incompatible changes

Not every API change requires a new version. Fortunately, otherwise, after ten years, we'd have an unmanageable number of versions to maintain. It's therefore important to distinguish changes that are compatible with existing clients from those that aren't.

Here are a few examples:

ChangeGenerally compatible?
Adding an optional property to a JSON responseYes
Adding a new endpointYes
Adding an optional parameterYes
Removing an existing propertyNo
Renaming a propertyNo
Changing a property's typeNo
Making an optional parameter mandatoryNo
Changing the meaning of a fieldNo

Keep in mind, though, that these rules depend on how clients behave. For example, adding a property to a JSON response is generally harmless for a client that ignores unknown properties. However, some clients use strict validation and may reject a response containing an additional field (but that's rare these days...).

So don't assume a change is automatically compatible just because it doesn't obviously alter the existing structure.

Maintain multiple versions without duplicating business logic

Supporting multiple API versions doesn't mean maintaining two completely separate implementations of your application.

Let's say your first API version returns a user's full name in a single field:

{
  "id": 42,
  "name": "John Doe"
}

In the second version, you decide to expose the first and last names separately:

{
  "id": 42,
  "firstName": "John",
  "lastName": "Doe"
}

The underlying data and business logic haven't necessarily changed. Only the public representation of the user is different.

In this case, both versions can share the same internal service while using separate response transformations. Version 1 keeps returning name, while version 2 exposes firstName and lastName.

This approach avoids duplicating database queries, validation rules, and business operations just to support different API contracts.

However, don't try to force every version through the same code path if their behavior genuinely differs. Sometimes, a change in requirements also means a change in business logic, and hiding those differences behind a collection of conditionals can quickly become harder to maintain than separate implementations.

The goal isn't to share as much code as possible. It's to keep the internal logic independent of the public API format wherever that makes sense.

Plan a transition period for older versions

Deploying a new version doesn't mean you have to disable the old one immediately.

Clients can't always update quickly. Some depend on mobile applications whose users need to install a new version. Others use integrations developed by external teams.

A transition period gives these users enough time to make the necessary changes. A reasonable approach is to:

  • Release the new version without removing the old one.
  • Inform users about the changes.
  • Provide detailed documentation to make migration easier.
  • Announce an end-of-support date for the old version.
  • Monitor usage of existing versions before retiring them.

It can also be useful to indicate that a version is deprecated directly in HTTP responses.

For example:

HTTP/1.1 200 OK
Deprecation: @1798761600
Sunset: Tue, 30 Jun 2027 23:59:59 GMT
Link: <https://api.example.com/docs/migration-v2>; rel="deprecation"

These headers indicate that a version is approaching its end of life and provide a link to the information needed for migration. You can also send email notifications or display alerts in the developers' dashboard.

The important thing is to avoid letting users discover that a version has been removed only when their requests start failing.

Of course, getting some clients to move on isn't always easy, especially when you're dependent on a large customer...

Automate compatibility testing

Maintaining multiple versions naturally increases the number of scenarios that need testing. A change that works with the latest version can introduce a regression in an older version that's still being used by some clients.

Automated tests help reduce this risk. It's particularly useful to keep tests that check the expected HTTP responses.

For example:

const response = await fetch('/api/v1/users/42');

const user = await response.json();

if (response.status !== 200) {
    throw new Error('Unexpected HTTP status');
}

if (user.id !== 42 || typeof user.name !== 'string') {
    throw new Error('Invalid API response');
}

This test checks that version 1 continues to return the expected properties.

For more thorough coverage, contract testing can verify that the provider and consumers agree on the same expectations. Tools such as Pact and OpenAPI specifications can help automate these checks.

It's also a good idea to test error scenarios, null values, optional parameters, and different data types. An API may work perfectly with ordinary data while still having problems in certain edge cases.

Document changes clearly

A new API version should come with sufficiently detailed documentation to help developers understand what has changed.

A simple list of new endpoints isn't enough when behavior differs between versions.

Good migration documentation should cover:

  • Modified or removed endpoints.
  • Renamed properties or properties whose types have changed.
  • New mandatory or optional parameters.
  • Behavioral differences.
  • Examples of requests and responses before and after migration.
  • Any changes to the HTTP status codes returned.

OpenAPI is particularly useful for describing different API versions and allowing developers to generate clients or test endpoints.

It's also useful to keep a history of changes between versions. This helps developers quickly identify a change that might explain unexpected behavior or a side effect. I've lost hours because of side effects introduced by changes that I simply didn't have in mind at the time.

When unexpected behavior appears after an API update, the change history can be particularly useful. By providing this documentation to an AI, along with the relevant code and the symptoms observed, it's easier to identify a change that might be causing the problem. This can save time and avoid lengthy searches just to understand what changed between two versions.

Conclusion

Versioning is an important part of API maintenance, particularly when an API is used by multiple applications or external clients. The goal isn't to create more versions, but to allow the API to evolve without forcing all its users to make changes immediately.

To achieve this, you need to identify incompatible changes, choose an appropriate versioning strategy, and separate business logic from data representation as much as possible.

You also need to plan a transition period, automate compatibility tests, and monitor the usage of older versions.

Finally, keep in mind that an API is a contract. Even if a change seems cleaner or more logical from a developer's point of view, it can represent a major regression for a client that depends on the existing behavior. I hadn't really thought about this when I first started developing (and your AI assistant is a bit like the beginner I was back then: you really need to keep an eye on what it produces...).

A good versioning strategy helps reconcile these two needs: evolving your application while preserving the stability of existing integrations.




Popular posts