Lesson 6 of 7
API Versioning Strategies
API versioning lets you evolve your API without breaking existing clients. The most practical strategy for PHP is URL versioning (/api/v1/, /api/v2/) - immediately visible, cacheable, and unambiguous. Header-based versioning (Accept: application/vnd.api.v2+json) is theoretically purer but harder to test and implement.
URL Versioning & Backward Compatibility
<?php
declare(strict_types=1);
// ── URL versioning - recommended ──────────────────────────────
// /api/v1/posts → old clients use this
// /api/v2/posts → new clients use this
// Both can run simultaneously until v1 is deprecated
// ── Router with version namespace ────────────────────────────
class VersionedApiRouter {
private array $routers = [];
public function version(string $version): ApiRouter {
if (!isset($this->routers[$version])) {
$this->routers[$version] = new ApiRouter("/api/$version");
}
return $this->routers[$version];
}
public function dispatch(): void {
$path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH) ?? "/";
$segment = explode("/", trim($path, "/"))[1] ?? ""; // "v1", "v2"
if (!isset($this->routers[$segment])) {
http_response_code(404);
echo json_encode(["success" => false, "error" => ["code" => "NOT_FOUND", "message" => "API version '$segment' not found."]]);
exit;
}
$this->routers[$segment]->dispatch();
}
}
// ── Setup ─────────────────────────────────────────────────────
$router = new VersionedApiRouter();
// V1 routes - maintained for existing clients
$v1 = $router->version("v1");
$v1->get("/api/v1/posts", fn($req) => $postController->index($req));
$v1->post("/api/v1/posts", fn($req) => $postController->store($req));
// V2 routes - new features, different response shape
$v2 = $router->version("v2");
$v2->get("/api/v2/posts", fn($req) => $postV2Controller->index($req));
// ── Deprecation headers ───────────────────────────────────────
// Inform v1 clients their version is sunset
header("Sunset: Sat, 01 Jan 2027 00:00:00 GMT"); // when v1 dies
header("Deprecation: true");
header("Link: </api/v2/posts>; rel="successor-version"");
// ── Backward compatible changes (no version bump needed) ──────
// ✅ Adding a NEW optional field to response
// ✅ Adding a NEW optional request parameter
// ✅ Adding a NEW endpoint
// ✅ Relaxing a validation rule (was required, now optional)
// ── Breaking changes (require new version) ────────────────────
// ❌ Removing a field from a response
// ❌ Renaming a field
// ❌ Changing a field's type (int → string)
// ❌ Making an optional param required
// ❌ Changing the URL structure
// ❌ Changing authentication mechanism
// ── API changelog / documentation ─────────────────────────────
// GET /api → return version info
$router->version("v1")->get("/api", fn($req) => ApiResponse::success([
"current_version" => "v1",
"versions" => [
"v1" => ["status" => "deprecated", "sunset" => "2027-01-01"],
"v2" => ["status" => "stable", "docs" => "https://docs.example.com/v2"],
],
]));Quick Quiz
Tip
Tip
Practice API Versioning Strategies in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
API Versioning Strategies Diagram
Practice Task
Note
Practice Task - (1) Write a working example of API Versioning Strategies from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with API Versioning Strategies is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?