API Versioning — Best Practices
Advertisement
API versioning allows evolution without breaking clients. Multiple strategies for different needs.
URL Path Versioning
app.get("/api/v1/users", (req, res) => {
res.json({ users: [], version: "v1" });
});
app.get("/api/v2/users", (req, res) => {
res.json({
data: [{ id: 1, name: "Alice" }],
meta: { total: 1 },
version: "v2",
});
});
Header Versioning
app.get("/api/users", (req, res) => {
const version = req.headers["api-version"] || "1";
if (version === "2") {
res.json({
data: [{ id: 1, name: "Alice" }],
meta: { total: 1 },
});
} else {
res.json({ users: [] });
}
});
Best Practices
const router = Router();
// Version in path
router.get("/v1/users", (req, res) => {
// V1 response
});
router.get("/v2/users", (req, res) => {
// V2 response
});
// Sunset old versions
app.use((req, res, next) => {
if (req.path.includes("/v1")) {
res.set("Sunset", new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toUTCString());
res.set("Deprecation", "true");
}
next();
});
app.use("/api", router);
FAQ
Q: Should I version the API? A: Only if changes break clients. Add backward compatibility first.
Q: How long to support old versions? A: 6-12 months typically. Give warning via headers.
Q: Path or header versioning? A: Path is clearer. Headers for content negotiation.
Good versioning strategy enables confident API evolution.
Advertisement