Search Sreeni's Insights

Filter by content type
technical March 16, 2017 6 min read

API versioning strategies - URI vs header vs query string

API versioning compares URI, query string, custom header and media type approaches, with guidance on breaking changes, ASP.NET Core configuration and deprecation policy.

Share:

API versioning strategies - URI vs header vs query string

An API contract is becoming difficult to change when existing clients are depending on its response shape. Adding a field is normally safe, but renaming a field, changing a status code or removing a required property is breaking the client. A fund API needs a clear way to evolve while old SPA and mobile releases are still in use.

In this article, we are going to compare URI, query-string, custom-header and media-type API versioning. We will also see breaking versus non-breaking changes, a deprecation policy and ASP.NET Core MVC versioning for a fund API.

TL;DR Summary

  • Version an API when the contract is breaking, not for every internal implementation change.
  • URI versioning is visible and discoverable, query-string versioning is easy to test, and header or media-type versioning keeps the URI stable.
  • Cacheability, discoverability, REST purity and tooling are the main trade-offs.
  • Keep old versions during a defined sunset period and measure usage before removal.
  • Microsoft.AspNetCore.Mvc.Versioning 1.x can map requests to controller versions in ASP.NET Core 1.1.
  • Semantic versioning helps communicate compatibility, but an HTTP API also needs a client migration policy.

Challenges

Clients are released at different speeds

The SPA can be deployed today, while a mobile application may remain installed for months. Removing fundName from a response because the new SPA uses name is breaking a client which has not been updated.

Version labels are not enough

An API may say v1 while the implementation has already changed behaviour in several incompatible ways. Versioning must be connected to a contract, tests, documentation and a sunset decision.

Multiple routes create confusion

If URI, header and query versions are accepted without a rule, support teams do not know which contract a client is receiving. The API should select one primary strategy and document exceptions.

What is API versioning?

API versioning is the practice of exposing and maintaining compatible API contracts while allowing the implementation to evolve.

In simple terms, it is giving a client a stable promise. A fund API can continue serving v1 clients while v2 returns a new factsheet shape, and the team can remove v1 only after its consumers migrate.

The following diagram compares the four common ways to communicate an API version.

API versioning strategies
API versioning strategies

The purple path is the explicit URI version, while header and media-type versions keep the resource URI stable.

Why API versioning is important?

API versioning is important because it is protecting consumers from accidental breaking changes. It is also making a deliberate migration possible: clients can move from /api/v1/funds to /api/v2/funds while both contracts are observable.

In our case, a v1 fund response can expose unitValue and v2 can expose a richer price object. The application service can remain shared while the controllers map the result to different representations.

Breaking and non-breaking changes

ChangeUsually safeAction
Add an optional response fieldYesDocument and monitor
Add an optional request fieldYesKeep the old default
Add a new endpointYesPublish documentation
Rename or remove a fieldNoNew version or migration
Change a field typeNoNew version or compatible field
Change authorization or error meaningUsually noReview as a contract change

Semantic versioning from the 2016 article is useful for packages and public contracts, but API versioning must also consider deployed clients and a sunset process.

Versioning strategies

URI versioning

GET /api/v1/funds/FUND001
GET /api/v2/funds/FUND001

It is visible, easy to discover, simple to cache and well supported by tools. The URI is exposing the contract version, but some teams consider it less pure REST because the version is part of the resource path.

Query-string versioning

GET /api/funds/FUND001?api-version=1.0

It is easy to try in a browser and visible in logs. Caches can vary by query string, but clients can forget the parameter and the URI is less clean.

Custom header

GET /api/funds/FUND001
api-version: 1.0

The resource URI remains stable and the version is an HTTP concern. Discoverability is lower because a browser request without the header is not showing the contract.

Media type

Accept: application/vnd.fe.fund.v1+json

The representation contract is explicit and the URI is stable, but client tooling, caching and debugging are requiring more care.

ASP.NET Core 1.1 example

Install the MVC versioning package used by the application,

dotnet add package Microsoft.AspNetCore.Mvc.Versioning

Note: [confirm: package version available by Mar 2017] Confirm the exact compatible 1.x package version in the configured NuGet feed before publishing the command.

Register it,

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddApiVersioning();
}

Create two controllers or actions,

[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/funds")]
public class FundsV1Controller : Controller
{
    [HttpGet("{fundId}")]
    public IActionResult Get(string fundId)
    {
        return Ok(new { fundId, unitValue = 10.50m });
    }
}

[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/funds")]
public class FundsV2Controller : Controller
{
    [HttpGet("{fundId}")]
    public IActionResult Get(string fundId)
    {
        return Ok(new { fundId, price = new { value = 10.50m, currency = "EUR" } });
    }
}

The versioning package can also read a query string or header through its configured reader. Keep one primary strategy, test it through the real HTTP pipeline and publish the example request in the API documentation.

Document the version in the OpenAPI or API reference, include representative fund responses and show the error contract. A consumer should not need to inspect controller code to understand whether unitValue is decimal, string or a nested price object.

Run contract tests for the SPA and mobile clients against each supported version. A response can be syntactically valid JSON and still be breaking when a client is depending on a field, status code or ordering rule. Keep the test fixtures close to the version documentation.

Version the documentation and examples with the contract as well. When support is receiving a request from a mobile release, the team should be able to identify the request version from logs and open the matching example without searching through old deployments.

Selection criteria and sunset

Choose URI versioning for public APIs where discoverability, cacheability and simple client tooling are important. Choose header or media type when a stable URI and representation negotiation are more valuable. Choose query string when existing infrastructure and simple adoption are the strongest constraints.

Set a sunset date, publish migration guidance and measure calls by version. Return a useful deprecation header or documentation link where the client can understand the next step. Do not remove v1 because the new implementation is ready; remove it when supported consumers are migrated and the owner accepts the risk.

Must Do / Should / Don’t

Must Do

  • Must define what is breaking before creating a new version.
  • Must test every supported version through HTTP.
  • Must track usage and announce a sunset policy.
  • Must keep authorization and error semantics documented per version.

Should

  • Should choose URI versioning for a discoverable public fund API.
  • Should share application rules while mapping each representation explicitly.
  • Should publish examples for the selected header or query strategy.

Don’t

  • Don’t create a new version for an internal refactoring which keeps the contract.
  • Don’t remove a version without usage evidence and a migration plan.
  • Don’t support three strategies accidentally across different controllers.

Wrap up

In this article, we have looked at breaking changes, URI, query-string, custom-header and media-type versioning, ASP.NET Core 1.1 configuration and sunset policy.

I really appreciate that you took the time to read this article. In the next article, I will walk you through distributed caching, hot spots and cache invalidation.

Related Posts