Implementing API versioning
Fastify provides two mechanisms for supporting multiple versions of the same APIs:
- Version constraints are based on the
Accept-Version
HTTP header (https://www.fastify.io/docs/latest/Reference/Routes/#constraints) - URL prefixes are simpler and my go-to choice (https://www.fastify.io/docs/latest/Reference/Routes/#route-prefixing)
In this section, we will cover how to apply both techniques, starting with the following base server:
// server.js const fastify = require('fastify')() fastify.get('/posts', async (request, reply) => { return [{ id: 1, title: 'Hello World' }] }) fastify.listen({ port: 3000 })
Version constraints
The Fastify constraint system allows us to expose multiple routes on the same URL by discriminating by HTTP header. It’s an advanced methodology that changes how the user must call our API: we must specify an Accept-Version
header containing a semantic versioning...