My Tech Blog

API Versioning in REST

Published on

As APIs evolve, maintaining backward compatibility becomes crucial. This article explores common strategies for versioning RESTful APIs and provides best‑practice recommendations.

Why Version Your API?

Versioning Strategies

URI Versioning

GET /v1/users
GET /v2/users?include=address

Embedding the version number directly in the URL is explicit and easy to route.

Header Versioning

GET /users
Accept: application/vnd.myapi.v2+json

Clients specify the desired version in a custom media type. This keeps URLs clean but requires more sophisticated content negotiation.

Query Parameter Versioning

GET /users?api-version=2

Simple to implement, but can be overlooked by caching layers.

Best Practices

  1. Never break existing contracts. Treat older versions as read‑only.
  2. Provide clear deprecation timelines. Communicate changes well in advance.
  3. Document each version. Keep separate OpenAPI specs per version.
  4. Maintain a default version. Serve the latest stable version when none is specified.

Sample Implementation (Node.js/Express)

const express = require('express');
const app = express();

app.get('/v1/users', (req, res) => {
  res.json([{id:1,name:'Alice'}]); // legacy fields
});

app.get('/v2/users', (req, res) => {
  res.json([{id:1,fullName:'Alice Smith',address:{city:'NY'}}]); // new schema
});

app.listen(3000,()=>console.log('API running on :3000'));