How do you version a REST API, and why would you?
Versioning lets you change the API without breaking existing clients. The common way is a URL prefix such as /api/v1. Other options are a custom header or media type. Avoid breaking changes inside a version.
Explain it simply
Suppose your mobile app is already installed on 50,000 phones, and you rename a field from name to fullName on the server. All those old apps break until users update. Versioning keeps the old contract running at /v1 while new clients use /v2.
Example
Three ways to carry the version:
URL path: GET /api/v2/students
Header: GET /api/students X-API-Version: 2
Content type: GET /api/students Accept: application/vnd.myapp.v2+jsonURL versioning is the most common because it is easy to see, test in a browser, and route:
const express = require("express");
const app = express();
app.use("/api/v1/students", require("./routes/v1/students"));
app.use("/api/v2/students", require("./routes/v2/students"));What counts as a breaking change:
- Removing or renaming a field.
- Changing a field's type, for example a number to a string.
- Making an optional input required.
Adding a new optional field is usually safe and needs no new version. Plan to retire old versions with advance notice, for example via a Deprecation or Sunset header and documentation.
What to say in the interview
"I version when a change would break existing clients. I prefer a URL prefix for clarity, keep additive changes within a version, and announce a retirement date for old versions."
Common mistakes
- Creating a new version for every small change.
- Removing a field without notice.