Dealing with different API versions

I've recently developed a new custom module for a Drupal project.

It pulls in an initial set of data from an API, builds a block that includes a form, makes another API request based on the form selections and displays the result to the user.

Part of the API base URL is v1 so I assume that, at some point, there could be breaking changes in the API response and the endpoint will change to be v2.

If this happens, I don't to have to change the existing code to make it work with a new version of the API.

I want to be able to write new code to work with the new version.

For the version 1 of the API, I've written a V1ApiClient that makes and processes the response from the v1 endpoint.

If we move to version v2, I'll write a V2ApiClient that will work with the version 2 response.

Each implementation will have its own logic but implement a ClientInterface to ensure both have the same required methods to make them interchangeable.

Then I can switch between implementations as needed and not have to change the existing code.

Similar to feature toggles, this allows me to deploy new code without making it immediately active.

I don't need to hold back merging changes until I'm ready to change the API version.

The same approach works in other situations, like payment gateways.

What if you need to switch to a different payment gateway or map service?

Instead of tightly coupling to one implementation, creating different implementations and strategies makes the code more flexible and easier if you need to change implementations or support multiple implementations at once.