Skip to Content
Course content

197: API Versioning Strategies in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen a dozen times: a developer pushes a "small" change to a JSON response to make it cleaner, and suddenly, the mobile app team is screaming because their app is crashing in production. It usually looks something like this.

// UserProfileController.php (The "Updated" Version)
public function show($id) {
    $user = User::find($id);
    
    return response()->json([
        'id' => $user->id,
        'first_name' => $user->firstName,
        'last_name' => $user->lastName,
        'email' => $user->email,
    ]);
}

The "Breaking Change" Disaster

At first glance, this looks great. It's more granular than the old version. But here is the problem: your existing API clients (like a React Native app or a third-party integration) are expecting a key called full_name. They aren't looking for first_name or last_name. When they try to access data.full_name, they get null or an undefined error, and the UI collapses.

You can't just tell your users to "update their app" immediately. Some users don't update for months. You've just violated the "API Contract"β€”the implicit agreement that once you publish a response format, you don't change it without warning.

Isolating Versions via URI Routing

The most straightforward way to fix this is by introducing versioning directly into your URL. This allows the old code to keep running exactly as it was, while new clients can opt into the improved data structure. I prefer this method because it's explicit; you can see exactly which version is being hit in your server logs without digging into request headers.

Here is how I would restructure the logic to support both the legacy and the new format:

// routes/api.php

// Legacy Version 1
Route::prefix('v1')->group(function () {
    Route::get('/user/{id}', [Api\V1\UserProfileController::class, 'show']);
});

// Current Version 2
Route::prefix('v2')->group(function () {
    Route::get('/user/{id}', [Api\V2\UserProfileController::class, 'show']);
});

By splitting these into different namespaces (Api\V1 and Api\V2), you avoid the nightmare of having a single controller filled with if ($version == 1) blocks. That approach becomes unmaintainable the moment you hit version 3 or 4.

Maintaining the Legacy Contract

Now, you simply move the original logic into the V1 controller. It stays frozen in time. You don't touch it unless there is a critical security bug.

// Api/V1/UserProfileController.php
public function show($id) {
    $user = User::find($id);
    return response()->json([
        'id' => $user->id,
        'full_name' => $user->firstName . ' ' . $user->lastName, // The expected contract
        'email' => $user->email,
    ]);
}

// Api/V2/UserProfileController.php
public function show($id) {
    $user = User::find($id);
    return response()->json([
        'id' => $user->id,
        'first_name' => $user->firstName,
        'last_name' => $user->lastName,
        'email' => $user->email,
    ]);
}

URI vs. Header Versioning

You'll often hear people argue that you should use "Accept Headers" (e.g., Accept: application/vnd.myapi.v2+json) instead of the URL. In a perfect academic world, that's more "RESTful" because the URL represents the resource, not the version of the representation.

In the real world? Header versioning is a pain to test in a browser and often gets stripped by aggressive caching layers or proxies. If you're building a public-facing API, stick to the URI versioning. It's easier for your developers to understand and significantly easier to debug.

  • V1: Becomes your "Maintenance Mode" code.
  • V2: Becomes your "Active Development" code.
  • Deprecation: Once your logs show that 0% of traffic is hitting /v1/, you can finally delete that folder with a clear conscience.



πŸ“‹ Practical Task

Implementing a Versioned Product Catalog API

You are managing a product API. Currently, the /v1/products/{id} endpoint returns a flat structure where the category is just a string. You need to upgrade this to /v2/ where the category is a full object containing an id and a slug.

Your Task:

  1. Create two separate controller methods: ProductControllerV1::show()` and ProductControllerV2::show()`.
  2. Ensure V1 returns this exact structure: {"id": 1, "name": "Mechanical Keyboard", "category": "Peripherals"}.
  3. Ensure V2 returns this exact structure: {"id": 1, "name": "Mechanical Keyboard", "category": {"id": 10, "name": "Peripherals", "slug": "peripherals"}}.
  4. Set up the routing logic to differentiate between /api/v1/products/1 and /api/v2/products/1.

Test both endpoints to ensure that changing the logic in V2 does not accidentally alter the output of V1.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.