API Versioning in PHP: How to Create /v1 and /v2 Without Breaking Your Clients
Quick answer: Versioning an API means keeping /api/v1 working while you build /api/v2 with the changes that would break existing clients. In plain PHP, send every request to index.php through .htaccess, read the version from the URL and dispatch to controllers separated by version. Create a new version only for breaking changes, and announce well in advance before you turn the old one off.
As an API grows, new rules, fields, response formats and integrations appear. Changing an endpoint that is already in use can break old systems, mobile apps that users haven't updated, partner integrations and admin panels that depend on the current behavior.
Versioning solves this. In plain PHP, a simple and effective way is to expose routes such as /api/v1 and /api/v2, so the old version keeps working while the new one evolves. This article covers when to version, how to organize files by version, how to stay compatible and how to retire old versions.
What is API versioning?
It is the practice of keeping separate versions of your endpoints so you can make changes without affecting clients that still use the old one:
/api/v1/users
/api/v2/users
/api/v1/users keeps returning the old format, while /api/v2/users returns a new structure with new fields, rules or response shape. Clients migrate on their own schedule.
Which changes break clients?
- Renaming a field in the JSON;
- Removing a field from the response;
- Changing a value's type, such as a number becoming a string;
- Changing the date format;
- Changing pagination rules;
- Changing the error format;
- Changing how authentication works;
- Changing what an existing endpoint does.
When do you need a new version?
Not every change needs one. A new version is needed when the change breaks the API's contract: the URL, HTTP method, parameters, request body, JSON response, status codes and core rules that clients rely on.
| Change | New version? | Example |
|---|---|---|
| Add an optional field to the response | Usually not | Add phone without removing anything |
| Fix an internal bug | No | Correct a calculation without changing the response |
| Remove a field | Yes | Drop full_name |
| Rename a field | Yes | user_name becomes name |
| Change the date format | Yes | 05/04/2026 becomes 2026-05-04 |
| Change authentication | Yes | From a static API key to JWT Bearer tokens |
Adding fields is safe only if clients ignore fields they don't know. Most JSON clients do, but it's worth saying so in your documentation.
Ways to version an API
In the URL
/api/v1/users
/api/v2/users
The easiest to understand, test (you can open it in a browser), cache and document. Widely used by public and internal APIs.
In a header
Accept: application/vnd.yourapi.v1+json
Accept: application/vnd.yourapi.v2+json
Keeps URLs clean, but is less visible and harder to test by hand.
In a query parameter
/api/users?version=1
/api/users?version=2
Works, but is usually less organized than a URL segment.
Folder structure for v1 and v2
/api
/core
response.php
database.php
auth.php
/services
UserService.php
/v1
/controllers
UserController.php
routes.php
/v2
/controllers
UserController.php
routes.php
index.php
Shared code lives in /core and /services; routes and controllers that differ live in each version's folder.
Send every request to index.php
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
Now /api/v1/users and /api/v2/users both reach your PHP router.
A router that reads the version
<?php
require __DIR__ . '/core/response.php'; // jsonResponse()
$path = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
$parts = explode('/', $path);
// Expected: api/v1/users
$version = $parts[1] ?? null;
$resource = $parts[2] ?? null;
$method = $_SERVER['REQUEST_METHOD'];
$versions = ['v1', 'v2'];
if (!in_array($version, $versions, true)) {
jsonResponse(404, [
'success' => false,
'message' => 'API version not found. Available: ' . implode(', ', $versions)
]);
}
require __DIR__ . "/{$version}/routes.php";
Because $version is checked against an allowlist before it is used in a file path, nobody can make the router include an arbitrary file.
Same data, two contracts
Suppose version 1 returns users like this, and an old frontend depends on it:
{
"success": true,
"data": [
{ "id": 1, "user_name": "Jane Smith", "email": "jane@example.com", "status": "A" }
]
}
Version 2 cleans up the names, uses readable status values and ISO 8601 dates, and adds metadata:
{
"success": true,
"data": [
{
"id": 1,
"name": "Jane Smith",
"email": "jane@example.com",
"status": "active",
"created_at": "2026-05-04T10:30:00-03:00"
}
],
"meta": { "version": "v2" }
}
Clients on v1 keep working; new clients use v2.
Share the logic, transform the output
Versioning doesn't mean copying everything. A shared service reads the data, and each version's controller decides how to present it:
<?php
class UserService
{
public function __construct(private PDO $pdo) {}
public function list(): array
{
return $this->pdo
->query('SELECT id, name, email, status, created_at FROM users ORDER BY id DESC LIMIT 50')
->fetchAll(PDO::FETCH_ASSOC);
}
}
<?php // v1/controllers/UserController.php
class UserControllerV1
{
public function __construct(private UserService $users) {}
public function index(): void
{
$data = array_map(fn(array $u) => [
'id' => (int) $u['id'],
'user_name' => $u['name'],
'email' => $u['email'],
'status' => $u['status'] === 'active' ? 'A' : 'I',
], $this->users->list());
jsonResponse(200, ['success' => true, 'data' => $data]);
}
}
<?php // v2/controllers/UserController.php
class UserControllerV2
{
public function __construct(private UserService $users) {}
public function index(): void
{
$data = array_map(fn(array $u) => [
'id' => (int) $u['id'],
'name' => $u['name'],
'email' => $u['email'],
'status' => $u['status'],
'created_at' => (new DateTime($u['created_at']))->format(DATE_ATOM),
], $this->users->list());
jsonResponse(200, ['success' => true, 'data' => $data, 'meta' => ['version' => 'v2']]);
}
}
Mapping explicitly also means your database column names never leak into the public contract: you can rename a column without breaking any client.
Routes for each version
<?php // v2/routes.php
require_once __DIR__ . '/../services/UserService.php';
require_once __DIR__ . '/controllers/UserController.php';
$controller = new UserControllerV2(new UserService(db()));
if ($resource === 'users' && $method === 'GET') {
$controller->index();
}
jsonResponse(404, ['success' => false, 'message' => 'Route not found in v2.']);
v1/routes.php is the same with UserControllerV1. db() is a small helper in core/database.php that returns the shared PDO connection. For a full router with parameters and 405 responses, see how to create a REST API in plain PHP.
Document each version
If you use Swagger/OpenAPI, publish one document per version (/api/docs/v1, /api/docs/v2) or set the version in the spec:
info:
title: My API
version: 2.0.0
Include a changelog that lists exactly what changed between v1 and v2.
Retiring an old version
Never switch off a version without warning, especially when partners integrate with it. Announce a date, then mark every v1 response with the standard headers:
<?php // at the top of v1/routes.php
header('Deprecation: @1767139200'); // since Dec 31, 2025 (Unix time)
header('Sunset: Thu, 31 Dec 2026 23:59:59 GMT'); // when v1 stops working
header('Link: <https://www.example.com/docs/v2>; rel="successor-version"');
Deprecation (RFC 9745) says the version is deprecated and since when, and Sunset (RFC 8594) says when it will stop responding. You can also add a meta.deprecated field to the JSON for clients that never look at headers. Before the sunset date, check your access logs to see who is still calling v1, and contact them.
Before creating v2
Don't copy everything blindly. First list exactly what changes:
- Does the JSON response change?
- Do field names change?
- Does the date format change?
- Does authentication change?
- Does pagination change?
- Does the error format change?
- Are fields removed?
If the change is big enough to break existing clients, create the new version. If it only adds things, keep it in the current one.
Common versioning mistakes
1. Changing v1 in place
Once v1 is in production, don't change its contract. Put breaking changes in v2.
2. Duplicating business rules
Share services and keep only the input and output layers different.
3. Not documenting the differences
If v2 renames fields or changes formats, the documentation has to say so clearly.
4. Retiring a version without notice
Clients need time to migrate. Announce early and use the Deprecation and Sunset headers.
5. Creating a version for every small change
Adding an optional field doesn't need v2.
Checklist for PHP API versioning
- Is the version clearly visible in the URL?
- Are v1 and v2 routes separated?
- Is shared code in services or core?
- Do old JSON responses remain compatible?
- Is the new version documented, with a list of breaking changes?
- Is there a plan and a date for retiring old versions?
- Were API clients told?
- Do tests cover both v1 and v2?
v1 vs. v2 at a glance
| Item | v1 | v2 |
|---|---|---|
| Name field | user_name | name |
| Status | A / I | active / inactive |
| Dates | Not included | 2026-05-04T10:30:00-03:00 |
| Metadata | None | meta.version |
Conclusion
Versioning lets a PHP API evolve without breaking existing integrations. With separate /api/v1 and /api/v2 routes, old applications keep working while new clients get the improvements.
Use a new version for breaking changes to the contract: renamed or removed fields, a different response format, new authentication or changed core rules. Even in plain PHP, routes per version, separate controllers and shared services give you an API that can grow safely. For consistent errors across versions, see error handling in a PHP API.
Frequently asked questions about PHP API versioning
What is API versioning?
Keeping separate versions of the API, such as /api/v1 and /api/v2, so endpoints can evolve without breaking clients of the old version.
When should I create a new API version?
When a change breaks the contract that clients rely on: renaming fields, removing data or changing the response format.
What is the best way to version a PHP API?
For plain PHP projects, URL versioning such as /api/v1/users is usually the simplest to build, test and document.
Do I need to duplicate all the code for v2?
No. Share services, the database connection, authentication and validation. Only controllers, routes and response mapping should differ.
Can v1 and v2 use the same database?
Yes. What changes is how data is received, processed and returned.
How do I announce that an old version will be retired?
Document it, add a meta.deprecated field to responses, and send the Deprecation and Sunset HTTP headers with the dates.