HTTP
Versioning
Change your API without breaking the clients that use the old one.
Once clients depend on your API you cannot change it freely: renaming a field or changing a response breaks apps you do not control (a mobile app a user has not updated). Versioning lets old and new behaviour live side by side: version 1 keeps working while version 2 introduces the change.
app.http(adapter) {
enableVersioning(Versioning(VersioningType.URI)) // /v1/users, /v2/users
// enableVersioning(Versioning(VersioningType.HEADER, header = "x-api-version", defaultVersion = "1"))
// enableVersioning(Versioning(VersioningType.MEDIA_TYPE, key = "v")) // Accept: application/json;v=2
}
@Controller("/users") @Version("1") class UsersV1 { @Get fun all() = listOf(UserV1("Ann Lee")) } // { "name": "Ann Lee" }
@Controller("/users") @Version("2") class UsersV2 { @Get fun all() = listOf(UserV2("Ann", "Lee")) } // { "first": "Ann", "last": "Lee" }
@Controller("/health") class Health { @Get fun ok() = "ok" } // no @Version: answers every version| Type | The client sends | Example |
|---|---|---|
URI | the version in the path (prefix v by default) | GET /v2/users |
HEADER | a header | x-api-version: 2 |
MEDIA_TYPE | a parameter of Accept | Accept: application/json;v=2 |
@Version goes on a controller or a single handler, and takes several values (@Version("1", "2") for something unchanged between versions). With HEADER and MEDIA_TYPE, defaultVersion is used when the client states none. A version nobody serves is a 404.
Which type should I use?
| URI | Header / media type | |
|---|---|---|
visible and easy to try in a browser or curl | yes | no |
| easy to cache and route (CDNs, gateways) | yes | harder |
| keeps URLs stable ("a resource has one URL") | no | yes |
URI versioning is the right default for public APIs: simple and obvious.
Doing it without duplicating everything
Version the edge (controllers and their response classes), not the logic. Both controllers call the same service; only the shape of the answer differs. Often only a few endpoints change between versions: give just those new controllers a new @Version, and keep the rest @Version("1", "2").
Good practice
- Add, do not change. Adding an optional field or a new endpoint is not a breaking change and needs no new version. Renaming, removing or changing a meaning is.
- Announce deprecations: mark old operations
deprecatedin the OpenAPI docs and send aSunsetheader (custom headers) with the date. - Keep at most two or three versions alive; remove old ones on a published schedule.
- Test each version: the same request path with different versions must give different, correct shapes.