Skip to content
Puneetpal Arneja.Start a project
By • Published • Updated

Laravel API Versioning for Mobile Apps That Cannot Force-Update

A web frontend deploys with its API. A mobile app does not. The build you shipped in March is still running on phones in December, calling the endpoints it was compiled against, and nothing you deploy can change that. API versioning for a mobile backend is the discipline of never breaking those builds while still moving the API forward, and then retiring old versions once the numbers say it is safe.

This article is the versioning chapter of a larger guide to Laravel as a backend for mobile apps. It covers the Laravel side (route groups, API Resources, middleware, tests), a small protocol for telling an installed app that it must or should update, and the Swift the client needs to honour it. The PHP targets Laravel 12 and 13; the Swift targets iOS 17 and later.

The Protocol in One Screen

Everything below implements one small contract between the app and the API. It is worth reading first, because the middleware, the endpoint, the Swift, and the tests all follow from it.

  1. The app sends three headers on every request: X-App-Version (semantic version, for example 1.4.0), X-App-Build (integer build number, optional), and X-App-Platform (ios or android).
  2. The API publishes GET /app/version-policy?platform=ios, which returns {"platform", "minimum", "recommended", "latest", "store_url", "message"}. The three version fields are semantic versions; latest is the version currently in the store.
  3. A request whose X-App-Version is below minimum gets 426 Upgrade Required with that same JSON body. The app shows a blocking screen with the store link (a hard update).
  4. A request whose version is below recommended is served normally, with Deprecation, optionally Sunset, and a Link header to the store added to the response. The app shows a dismissible prompt (a soft update).
  5. A fully retired API version (/api/v1 after its sunset) answers 410 Gone. That is a statement about the URL, not about the app version, and the two are kept distinct.

Why Mobile Is Different

Three facts about app distribution decide everything else here.

  • Review and rollout take days. Even a one-line fix waits in App Store review, then rolls out through phased release if you use it, then waits for the user to open the store.
  • Automatic updates are a user setting, not a guarantee. Part of any install base has them off, is on a low-storage device that defers them, or is on an OS version your new build no longer targets.
  • Old builds are frozen clients. The JSON decoder, the URL paths, the error handling, and the auth flow in a shipped build are fixed. If a key they decode as a non-optional string becomes a number, every screen that touches it fails, and the crash report lands on your desk.

So the API has to be correct for several clients at once, because it has several: the newest build and a build from a year ago are both live users until you decide, with data, to stop supporting one.

URL Versioning vs Header Versioning in Laravel

The two mainstream options are a version segment in the path (/api/v1/orders) or a version carried in a header, usually a vendor media type in Accept. In Laravel the URL approach is a route group and nothing else.

<?php
// routes/api.php
// bootstrap/app.php already mounts this file under /api via withRouting(api: ...)

use App\Http\Controllers\Api\V1;
use App\Http\Controllers\Api\V2;
use Illuminate\Support\Facades\Route;

Route::prefix('v1')->name('v1.')->group(function () {
    Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
        Route::get('/orders', [V1\OrderController::class, 'index'])->name('orders.index');
        Route::get('/orders/{order}', [V1\OrderController::class, 'show'])->name('orders.show');
    });
});

Route::prefix('v2')->name('v2.')->group(function () {
    Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
        Route::get('/orders', [V2\OrderController::class, 'index'])->name('orders.index');
        Route::get('/orders/{order}', [V2\OrderController::class, 'show'])->name('orders.show');
    });
});

V1 and V2 are controller namespaces. Naming the groups v1. and v2. means $request->routeIs('v1.*') works in middleware later. If you want the version to replace api rather than follow it, withRouting() in bootstrap/app.php accepts an apiPrefix argument, but /api/v1 is the convention most SDK generators and gateways expect.

Header versioning needs a middleware that parses Accept, decides a version, and either swaps the controller or sets a value the controllers read. It keeps one canonical URL per resource, which REST purists prefer. I do not use it for mobile backends, for three reasons:

  • A missing or malformed header has to fall back to something, so some client will get a version it did not ask for, and the failure is silent.
  • Access logs, CDN rules, WAF rules, and load balancer routing all see the path for free. Routing by header means teaching each of those layers to inspect Accept.
  • The person writing the Android client, or the QA engineer pasting a URL into a browser, can see the version in the path and cannot see it in a header.

The trade-off is duplicated routes and some duplicated controllers. That duplication is the point: a v1 route file is a frozen contract you can read, and the diff between v1 and v2 is the migration guide.

Additive Changes vs Breaking Changes

Most of the time you do not need a new version at all. A version bump is for breaking changes, and the test for “breaking” is whether a strict client decoder, like Swift’s JSONDecoder with non-optional properties, would throw. Inside a version you may:

  • Add a new key to any response object.
  • Add a new endpoint.
  • Add an optional query parameter or request body field with a default.
  • Add a new value to a list the client treats as opaque strings.
  • Relax validation (accept more than before).

You may not, without a new version:

  • Remove or rename a key.
  • Change a type, including number to string or object to array.
  • Return null for a key that was always present before.
  • Add a case to an enum the client decodes as a Swift or Kotlin enum. The decoder throws on the unknown case.
  • Change the shape or status code of an error response.
  • Tighten validation so a request that used to succeed now returns 422.

Two of those catch teams out. The enum case is the common one: the backend adds "status": "on_hold" to orders, and every build whose OrderStatus enum lacks the case fails to decode the whole list. The fix is on the client, an unknown fallback case from day one; until the installed base has it, treat a new enum value as breaking. The second is an envelope change dressed as additive: wrapping a previously bare array in { data: [...] } is a rename of everything.

API Resources Are the Contract

Laravel’s API Resources are where the version lives. Models, services, policies, and queries are shared across versions; the only thing that differs per version is the JsonResource that turns a model into JSON, and the Form Request that validates input. Keep resources in versioned namespaces and never return a model directly from a controller, because a model’s toArray() changes every time someone adds a column.

<?php

namespace App\Http\Resources\V1;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'status' => $this->status,            // v1 clients know: pending, paid, shipped
            'total' => (string) $this->total,     // v1 shipped totals as strings; keep it
            'currency' => $this->currency,
            'placed_at' => $this->created_at->toIso8601String(),
            'items' => OrderItemResource::collection($this->whenLoaded('items')),
        ];
    }
}
<?php

namespace App\Http\Resources\V2;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'status' => $this->status,            // v2 clients decode unknown cases safely
            'total_minor' => $this->total_minor,  // breaking: integer minor units replace the string
            'currency' => $this->currency,
            'placed_at' => $this->created_at->toIso8601String(),
            'fulfilment' => new FulfilmentResource($this->whenLoaded('fulfilment')),
            'items' => OrderItemResource::collection($this->whenLoaded('items')),
        ];
    }
}

The v1 resource keeps casting total to a string even after the column became an integer of minor units, because that is what v1 clients decode. Nothing about the model changed for them. A practical rule: once a version has shipped in an app build, its resource files are append-only. Add keys, add $this->when() conditions, but do not touch an existing line. Code review can enforce that with a CODEOWNERS rule or a CI check that fails when a diff removes lines under app/Http/Resources/V1.

The same applies to the error envelope. Whatever shape your bootstrap/app.php exception renderer produced when v1 shipped, including the key name for the machine-readable code, is now part of v1.

Step 1: Identify Every Request With Three Headers

You cannot sunset what you cannot count, and you cannot answer 426 to a client you cannot identify. Every request from the app carries three headers, and the API records them.

  • X-App-Version: the semantic version, CFBundleShortVersionString on iOS and versionName on Android, in the form major.minor.patch. This is the value the policy compares against, so it must be a plain release version with no suffix.
  • X-App-Build: the integer build number, CFBundleVersion or versionCode. Optional. It is not used for policy decisions; it is there so a server log line can be matched to a crash report, which is per build.
  • X-App-Platform: ios or android. This selects which policy applies and which store the client is sent to.

The Context facade attaches the values to every log line written during the request, including from queued jobs it dispatches. The cache counter is a cheap substitute for a log pipeline.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Context;
use Symfony\Component\HttpFoundation\Response;

class RecordClientVersion
{
    public function handle(Request $request, Closure $next): Response
    {
        $platform = strtolower((string) $request->header('X-App-Platform', 'unknown'));
        $version = (string) $request->header('X-App-Version', 'unknown');
        $build = (int) $request->header('X-App-Build', 0);
        $apiVersion = $request->segment(2) ?? 'none';   // "v1" from /api/v1/orders

        Context::add([
            'app_platform' => $platform,
            'app_version' => $version,
            'app_build' => $build,
            'api_version' => $apiVersion,
        ]);

        // Daily counter per platform, API version and app version, kept for 90 days.
        // Enough to answer "who still calls v1?" without a log pipeline.
        $key = sprintf('app_versions:%s:%s:%s:%s', now()->toDateString(), $platform, $apiVersion, $version);
        Cache::add($key, 0, now()->addDays(90));
        Cache::increment($key);

        return $next($request);
    }
}

To install it:

  1. Create the file with php artisan make:middleware RecordClientVersion and replace the generated body with the class above.
  2. In bootstrap/app.php, inside withMiddleware(), add $middleware->api(append: [RecordClientVersion::class]); so it runs for every API route, in every version, including the policy endpoint.
  3. Verify with curl -H "X-App-Platform: ios" -H "X-App-Version: 1.4.0" https://api.example.test/api/v2/orders followed by php artisan tinker and Cache::get('app_versions:'.now()->toDateString().':ios:v2:1.4.0'), which should return 1.

If your logs already land somewhere that can aggregate JSON fields, the Context call is enough and you can drop the cache counter. If not, a short Artisan command that scans the last seven days of keys gives you requests per app version per API version. Watch the share of all requests, not the raw count: 40 daily requests from a single device is a different decision than 0.4 percent of traffic spread across thousands of devices.

One trap: requests with no X-App-Version header are not “old versions”. They are builds that predate the header, or scrapers, or your own curl. Count them separately, and send the headers from the very first build you ship so that bucket stays empty.

Step 2: Publish the Version Policy Endpoint

The API publishes, per platform, the minimum version it will serve, the version it recommends, and the version currently in the store, plus the store URL and a message the app can show. The values live in config so raising them is a deploy or an environment change, not a code change.

<?php
// config/api.php
return [
    'policy' => [
        'ios' => [
            'minimum' => env('APP_VERSION_IOS_MINIMUM', '1.0.0'),
            'recommended' => env('APP_VERSION_IOS_RECOMMENDED', '1.0.0'),
            'latest' => env('APP_VERSION_IOS_LATEST', '1.0.0'),
            'store_url' => env('APP_VERSION_IOS_STORE_URL', 'https://apps.apple.com/app/id000000000'),
            'message' => env('APP_VERSION_IOS_MESSAGE', 'Please update the app to keep using it.'),
            'deprecated_at' => env('APP_VERSION_IOS_DEPRECATED_AT'),   // date you raised "recommended", e.g. 2026-11-01
            'sunset_at' => env('APP_VERSION_IOS_SUNSET'),           // date you plan to raise "minimum", optional
        ],
        'android' => [
            'minimum' => env('APP_VERSION_ANDROID_MINIMUM', '1.0.0'),
            'recommended' => env('APP_VERSION_ANDROID_RECOMMENDED', '1.0.0'),
            'latest' => env('APP_VERSION_ANDROID_LATEST', '1.0.0'),
            'store_url' => env('APP_VERSION_ANDROID_STORE_URL', 'https://play.google.com/store/apps/details?id=com.example.app'),
            'message' => env('APP_VERSION_ANDROID_MESSAGE', 'Please update the app to keep using it.'),
            'deprecated_at' => env('APP_VERSION_ANDROID_DEPRECATED_AT'),
            'sunset_at' => env('APP_VERSION_ANDROID_SUNSET'),
        ],
    ],
];
<?php

namespace App\Support;

final class VersionPolicy
{
    /** The six keys the app decodes, or null when the platform is not one we publish. */
    public static function body(string $platform): ?array
    {
        $policy = config("api.policy.{$platform}");

        if (! is_array($policy)) {
            return null;
        }

        return [
            'platform' => $platform,
            'minimum' => $policy['minimum'],
            'recommended' => $policy['recommended'],
            'latest' => $policy['latest'],
            'store_url' => $policy['store_url'],
            'message' => $policy['message'],
        ];
    }

    /** Accept only plain release versions; anything else is treated as "no version sent". */
    public static function isSemver(string $version): bool
    {
        return preg_match('/^\d+\.\d+\.\d+$/', $version) === 1;
    }
}
<?php
// routes/api.php (outside any version prefix, so the URL never moves)

use App\Http\Middleware\EnforceVersionPolicy;
use App\Support\VersionPolicy;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/app/version-policy', function (Request $request) {
    $request->validate(['platform' => ['required', 'in:ios,android']]);

    return response()
        ->json(VersionPolicy::body($request->query('platform')))
        ->header('Cache-Control', 'public, max-age=300');
})
    ->middleware('throttle:60,1')
    // Step 3 adds this middleware to every API route; a blocked app must still be able to read the policy.
    ->withoutMiddleware(EnforceVersionPolicy::class);

With the default /api prefix the full URL is https://api.example.com/api/app/version-policy?platform=ios, and the response is:

{
  "platform": "ios",
  "minimum": "1.2.0",
  "recommended": "1.4.0",
  "latest": "1.5.1",
  "store_url": "https://apps.apple.com/app/id000000000",
  "message": "Please update the app to keep using it."
}

Three details:

  • The endpoint is public and unauthenticated. A build that can no longer log in still has to be able to learn that it must update.
  • It sits outside the version prefix so its URL never changes; it is the one path every build must agree on forever. Never change its shape either. New keys are allowed, the six above are not negotiable.
  • Cache-Control: public, max-age=300 lets a CDN absorb the launch-time traffic. Five minutes is also the longest a policy change takes to reach every device that is online.

Verify it with curl -i "https://api.example.test/api/app/version-policy?platform=ios". You should see a 200 with the six keys; ?platform=web should return 422 through your normal validation envelope. If you see a 404, the route is inside a prefix group or routes/api.php is not registered in withRouting().

Step 3: Enforce the Policy in Middleware

The endpoint informs; this middleware enforces. It runs on every API request, reads the two headers it needs, and does one of three things: answers 426 for a version below minimum, decorates the response with deprecation headers for a version below recommended, or does nothing.

<?php

namespace App\Http\Middleware;

use App\Support\VersionPolicy;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Symfony\Component\HttpFoundation\Response;

class EnforceVersionPolicy
{
    public function handle(Request $request, Closure $next): Response
    {
        $platform = strtolower((string) $request->header('X-App-Platform', ''));
        $version = (string) $request->header('X-App-Version', '');
        $body = VersionPolicy::body($platform);

        // Not the app (curl, a partner, a build that predates the headers): never block it.
        if ($body === null || ! VersionPolicy::isSemver($version)) {
            return $next($request);
        }

        // Hard update: below minimum gets the policy body with 426 Upgrade Required.
        if (version_compare($version, $body['minimum'], '<')) {
            return response()->json($body, 426);
        }

        $response = $next($request);

        // Soft update: below recommended is served, with advisory headers attached.
        if (version_compare($version, $body['recommended'], '<')) {
            $deprecatedAt = config("api.policy.{$platform}.deprecated_at");
            $sunsetAt = config("api.policy.{$platform}.sunset_at");

            // RFC 9745: Structured Fields date, "@" + Unix seconds. No date configured means "deprecated now".
            $deprecatedTimestamp = $deprecatedAt ? Carbon::parse($deprecatedAt)->timestamp : now()->timestamp;
            $response->headers->set('Deprecation', '@'.$deprecatedTimestamp);

            if ($sunsetAt) {
                // RFC 8594: HTTP-date, always GMT, never earlier than the Deprecation date
                $response->headers->set('Sunset', Carbon::parse($sunsetAt)->toRfc7231String());
            }

            $response->headers->set('Link', '<'.$body['store_url'].'>; rel="alternate"');
        }

        return $response;
    }
}
  1. Create it with php artisan make:middleware EnforceVersionPolicy and paste the class.
  2. Register it after the recording middleware: $middleware->api(append: [RecordClientVersion::class, EnforceVersionPolicy::class]);. Order matters: a 426 should still be counted.
  3. Set APP_VERSION_IOS_MINIMUM=1.2.0 in .env, run php artisan config:clear, and verify: curl -i -H "X-App-Platform: ios" -H "X-App-Version: 1.1.0" https://api.example.test/api/v2/orders returns HTTP/1.1 426 with the policy JSON, and the same request with 1.3.0 returns your normal 401 or 200 with Deprecation: and Link: headers if recommended is 1.4.0.

On the status code: RFC 9110 defines 426 for protocol upgrades, and a strict reading says it does not belong here. It is nonetheless the code mobile APIs have settled on for “this client must update”, because no other 4xx carries that meaning, no HTTP library retries it, and no existing error handler in an old build will mistake it for something it already knows how to show. The body is what the app acts on; the status is a signal that the body is a policy, not an error envelope.

On the headers: RFC 9745 (March 2025) defines Deprecation with a Structured Fields date, an @ followed by Unix seconds; a date in the past means “already deprecated”, in the future means “will be”. RFC 8594 defines Sunset, an HTTP-date after which the resource is expected to stop responding, which must not be earlier than the deprecation date. RFC 9745 also defines a deprecation link relation, but it is meant for documentation about the deprecation. For a first-party app the useful destination is the store page, so the middleware sends it as rel="alternate": the place to get the version that is not deprecated. Your own iOS app will not read these headers unless you write code to, so for a first-party client they are mainly documentation that travels with the response, visible to a partner integration or to an engineer with a proxy open. The enforcement is the 426.

Step 4: The Client Side in Swift

The app needs four things: the three headers on every request, a fetch of the policy at launch and on foreground, a semantic version comparison, and a single place that notices a 426. Kept to the decision and the two outcomes:

import UIKit

struct VersionPolicy: Decodable {
    let platform: String
    let minimum: String
    let recommended: String
    let latest: String
    let storeUrl: URL
    let message: String
}

enum UpdateRequirement {
    case none
    case soft(VersionPolicy)   // below recommended: dismissible prompt, remembered per "recommended"
    case hard(VersionPolicy)   // below minimum: blocking screen with one button, the store link
}

enum AppIdentity {
    static let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0.0"
    static let build = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0"

    /// Call this from the one place every URLRequest is built.
    static func addHeaders(to request: inout URLRequest) {
        request.setValue(version, forHTTPHeaderField: "X-App-Version")
        request.setValue(build, forHTTPHeaderField: "X-App-Build")
        request.setValue("ios", forHTTPHeaderField: "X-App-Platform")
    }
}

/// Numeric semver comparison: "1.10.0" is newer than "1.9.2", which a string compare gets wrong.
func isVersion(_ lhs: String, olderThan rhs: String) -> Bool {
    let l = lhs.split(separator: ".").map { Int($0) ?? 0 }
    let r = rhs.split(separator: ".").map { Int($0) ?? 0 }
    for i in 0..<max(l.count, r.count) {
        let a = i < l.count ? l[i] : 0
        let b = i < r.count ? r[i] : 0
        if a != b { return a < b }
    }
    return false
}

func requirement(for policy: VersionPolicy) -> UpdateRequirement {
    if isVersion(AppIdentity.version, olderThan: policy.minimum) { return .hard(policy) }
    if isVersion(AppIdentity.version, olderThan: policy.recommended) { return .soft(policy) }
    return .none
}

private let policyDecoder: JSONDecoder = {
    let decoder = JSONDecoder()
    decoder.keyDecodingStrategy = .convertFromSnakeCase   // store_url -> storeUrl
    return decoder
}()

func fetchVersionPolicy() async throws -> VersionPolicy {
    var request = URLRequest(url: URL(string: "https://api.example.com/api/app/version-policy?platform=ios")!)
    AppIdentity.addHeaders(to: &request)
    let (data, _) = try await URLSession.shared.data(for: request)
    return try policyDecoder.decode(VersionPolicy.self, from: data)
}

/// Run this on every API response before normal error handling. A 426 body is the policy itself.
func upgradeRequired(in response: URLResponse, data: Data) -> VersionPolicy? {
    guard let http = response as? HTTPURLResponse, http.statusCode == 426 else { return nil }
    return try? policyDecoder.decode(VersionPolicy.self, from: data)
}

@MainActor
func openStore(_ policy: VersionPolicy) {
    UIApplication.shared.open(policy.storeUrl)
}
  1. Route every request through AppIdentity.addHeaders(to:). If you use a networking layer with a request interceptor, that is where it goes; if not, the one function that builds URLRequests.
  2. Call fetchVersionPolicy() at launch and on UIApplication.willEnterForegroundNotification, pass the result to requirement(for:), and treat a network failure as .none, never as a block.
  3. Call upgradeRequired(in:data:) in the response path shared by every API call and show the hard screen when it returns a policy. This is the path a build that predates the launch check will take.
  4. The hard screen has exactly one button, the store link. The soft prompt remembers a dismissal per recommended value so it does not nag on every foreground, and reappears when recommended moves again.
  5. Verify with a debug build whose CFBundleShortVersionString is below your staging minimum: the first API call after login should show the hard screen, not a decode error.

CFBundleShortVersionString must be a plain major.minor.patch. App Store Connect enforces that already; if a CI script appends anything to it, the server treats the header as absent and the build is never blocked, which is the safe failure but not the one you want.

Step 5: Contract Tests That Pin Old Response Shapes

The append-only rule for resources needs a test that fails when someone breaks it by accident. The simplest reliable form is a fixture file per endpoint per version, holding the exact JSON the version returned when it shipped, and a feature test that asserts the current response matches it key for key. Laravel’s HTTP tests give you assertExactJson() for strict equality and assertJsonStructure() or the fluent whereAllType() when only keys and types matter. The same test class is where the policy middleware gets pinned.

<?php

namespace Tests\Feature\Api\V1;

use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Testing\Fluent\AssertableJson;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class OrderContractTest extends TestCase
{
    use RefreshDatabase;

    private array $clientHeaders = [
        'X-App-Platform' => 'ios',
        'X-App-Version' => '1.2.0',   // the first version that shipped against v1
        'X-App-Build' => '120',
    ];

    public function test_v1_order_matches_the_shipped_contract(): void
    {
        Carbon::setTestNow('2026-01-15 10:00:00');
        config(['api.policy.ios.minimum' => '1.0.0', 'api.policy.ios.recommended' => '1.0.0']);

        $user = User::factory()->create();
        $order = Order::factory()->for($user)->create([
            'id' => 1001,
            'status' => 'paid',
            'total_minor' => 4999,
            'currency' => 'USD',
        ]);

        Sanctum::actingAs($user);

        $response = $this->withHeaders($this->clientHeaders)->getJson("/api/v1/orders/{$order->id}");

        $response->assertOk();

        // Exact pin: the JSON this endpoint returned when 1.2.0 shipped.
        $response->assertExactJson(
            json_decode(file_get_contents(base_path('tests/Fixtures/v1/order.json')), true)
        );

        // Type pin: catches string-to-int flips even if a value legitimately differs.
        $response->assertJson(fn (AssertableJson $json) => $json
            ->whereAllType([
                'data.id' => 'integer',
                'data.status' => 'string',
                'data.total' => 'string',
                'data.currency' => 'string',
                'data.placed_at' => 'string',
            ])
            ->etc()
        );
    }

    public function test_versions_below_minimum_get_426_with_the_policy_body(): void
    {
        config(['api.policy.ios.minimum' => '1.3.0', 'api.policy.ios.recommended' => '1.4.0']);

        $this->withHeaders($this->clientHeaders)
            ->getJson('/api/v1/orders')
            ->assertStatus(426)
            ->assertJsonStructure(['platform', 'minimum', 'recommended', 'latest', 'store_url', 'message'])
            ->assertJsonPath('minimum', '1.3.0');
    }

    public function test_versions_below_recommended_are_served_with_deprecation_headers(): void
    {
        config(['api.policy.ios.minimum' => '1.0.0', 'api.policy.ios.recommended' => '1.4.0']);

        Sanctum::actingAs(User::factory()->create());

        $this->withHeaders($this->clientHeaders)
            ->getJson('/api/v1/orders')
            ->assertOk()
            ->assertHeader('Deprecation')
            ->assertHeader('Link');
    }
}

Fixture discipline is what makes this work. Generate the file once from the real response when the version ships, commit it, and never regenerate it for v1. If a test fails because the fixture is “out of date”, the fixture is right and the code is wrong; that is the whole point. For v2, the fixture is editable until the first v2 build is in the store, then it freezes too. Freeze Carbon::setTestNow() and seed explicit IDs so the fixture is deterministic; an exact-match test with a random timestamp in it is useless.

When a version has many endpoints, one data-provider test that loops over a directory of fixtures is less code than a class per endpoint. Use the exact-JSON assertion for list and detail endpoints, and the type-only assertion where values cannot be seeded, such as signed URLs.

Step 6: Sunsetting an API Version Safely

Retiring v1 is a sequence, and skipping a step is how you end up with support tickets from people who cannot log in. In order:

  1. Ship the first app version that uses v2 and let it reach the installed base. Watch api_version in the counter; v1 traffic should start falling within a release cycle.
  2. Raise recommended to that version and set deprecated_at to today. Every v1-era app now sees the soft prompt on each foreground, and every response it gets carries Deprecation and the store Link. Write the release note.
  3. Set sunset_at to a date your numbers support. If partners call the API, email them a migration page now; the header alone is not a notice anyone reads.
  4. When v1 traffic from identifiable app versions is below the threshold you chose (I use well under one percent of requests, and I check that the remaining versions are not a single enterprise customer), raise minimum to the first v2 version. From this point those apps get 426 and the hard screen.
  5. On the sunset date, replace the v1 route group with a fallback that answers 410 Gone for any path under /api/v1. Keep it for a few more months so the response stays explanatory, then delete it.
  6. Delete the V1 resources, controllers, Form Requests, and finally the contract tests and fixtures, in that order, in one pull request titled so that git log explains itself later.
<?php
// routes/api.php, after sunset: every former v1 path answers the same way.
// Clients that send X-App-Version never reach this; EnforceVersionPolicy has already answered 426.
// This is for everything else: builds that predate the headers, partner scripts, bookmarked URLs.

use Illuminate\Support\Facades\Route;

Route::prefix('v1')->group(function () {
    Route::any('{any}', function () {
        return response()->json([
            'error' => [
                'code' => 'api_version_retired',
                'message' => 'API v1 was retired. Update the app or move to /api/v2.',
                'docs_url' => 'https://api.example.com/docs/migrating-to-v2',
            ],
        ], 410);
    })->where('any', '.*');
});

Keep the two status codes distinct in your head and in your code. 426 says “this app version is too old” and carries the version policy; it is decided per request by the middleware and goes away when the user updates. 410 says “this URL is gone for good” and carries the error envelope; it is a property of the route and never changes. An old build that sends the headers only ever sees 426.

Do not sunset the authentication endpoints before the rest. A build that can still log in but gets 426 on its first data call shows the update screen; a build that cannot log in shows whatever its login error handler shows, written before anyone thought about this. And never let the /app/version-policy endpoint move or change shape, for the same reason.

When should you not do any of this? If the app is a managed fleet (field devices, kiosks, an internal tool pushed through MDM), you control installs and a single version with a short overlap is enough. If the only client is a web app you deploy, you do not need versioning at all. The machinery above is for when you have given up control over when the client updates, which is every consumer app in a public store.

Common Errors

  • Every request returns 426, including from curl. The middleware is treating a missing header as a version below minimum. Check that isSemver() runs before version_compare() and that an empty X-App-Version falls through.
  • The policy endpoint itself returns 426 to an old build. The ->withoutMiddleware(EnforceVersionPolicy::class) call was dropped from the route, so the enforcing middleware appended to the api group answers first. The app must always be able to read the policy.
  • A version like 1.4 is never blocked. isSemver() requires three components. Either fix the build setting or relax the regex to ^\d+(\.\d+){1,2}$.
  • Raising minimum in .env changed nothing. Config is cached in production; run php artisan config:cache as part of the deploy.
  • The soft prompt shows on every foreground. The dismissal is being stored per launch instead of per recommended value. Persist the dismissed value and compare.

Sources

Open-Source Implementations

The protocol in this guide is published as two open-source packages that share it exactly: the same three headers, the same /app/version-policy response, 426 below the minimum, and Deprecation and Sunset headers below the recommended version. laravel-app-version is the Laravel side (middleware, the policy endpoint, and config driven by the APP_VERSION_IOS_* and APP_VERSION_ANDROID_* environment variables). AppUpdateGate is the Swift side: it sends the headers, reads the policy, handles the 426, and shows a soft or hard update prompt in SwiftUI or UIKit. Use them as they are, or read them as a reference for your own.

Where This Fits

Versioning decides whether old builds keep working; it does not decide whether they keep working safely. An old build that still authenticates is also an old build with whatever token handling and certificate validation it shipped with, so pair this with the Laravel API security checklist and set token expiry so a sunset also ends old sessions. If you would rather have the versioned API, the version tracking, and the update flow designed for you, see backend API development.

Frequently Asked Questions

Should a Laravel API for a mobile app use URL or header versioning?

Use the URL, as in /api/v1/orders. A URL prefix is one Route::prefix() group in Laravel, shows up in every access log and CDN rule without configuration, and is impossible for a client to send by accident. Header versioning (Accept: application/vnd.example.v2+json) keeps URLs stable but needs custom middleware, is invisible in most logs, and falls back silently when a client forgets the header.

What counts as a breaking change for a mobile client?

Anything a strict decoder will reject: removing or renaming a key, changing a type (string to number, object to array), returning null where the client expects a value, changing the meaning of an existing enum value, or changing an error shape. Adding a new key, a new optional query parameter, or a new endpoint is additive and does not need a new version, provided the client ignores unknown keys.

Which headers should a mobile app send so the API knows its version?

Three headers on every request: X-App-Version with the semantic version from CFBundleShortVersionString or versionName (for example 1.4.0), X-App-Build with the integer build number (optional, useful for matching crash reports), and X-App-Platform set to ios or android. The server compares X-App-Version against the published policy and logs all three so you can see which versions still call each API version.

How do you force a mobile app to update when the API changes?

You cannot force the install, but you can refuse to serve. Publish GET /app/version-policy?platform=ios, which returns the platform, minimum, recommended and latest versions, a store_url and a message. The app fetches it at launch and on foreground: below minimum it shows a blocking screen with the store link, below recommended a dismissible prompt. On the server, a middleware answers any request whose X-App-Version is below minimum with 426 Upgrade Required and the same JSON body, so even builds that predate the prompt fail with a readable message.

What are the Deprecation and Sunset HTTP headers and when does this API send them?

Deprecation (RFC 9745, March 2025) carries a Structured Fields date such as Deprecation: @1767225599 and says a resource is or will be deprecated. Sunset (RFC 8594) gives the HTTP-date after which it is expected to stop responding. In the protocol described here the API adds Deprecation, optionally Sunset, and a Link header pointing at the app store to every response for an app version below recommended. They are advisory; the 426 response for versions below minimum is what enforces.

How long should an old API version stay available for mobile apps?

Until your own request logs say the app versions that depend on it are gone, not until a date on a calendar. Log X-App-Version on every request, watch the share of traffic per API version weekly, raise recommended so old versions see the soft prompt, raise minimum so they get 426, and only then replace the old route group with a 410 Gone fallback. For a consumer app that is typically several months; for a managed fleet of devices it can be days.

Puneetpal Arneja, Senior iOS, Web & Software Developer

Written by

Senior iOS, Web & Software Developer · 13+ years building apps and software

I've shipped 18+ mobile applications across banking, healthcare, and consumer products — including work for Citibank, Apple, PNC, and Albertsons. Everything here comes out of production work, not theory.

Need an API That Old Builds Can Trust?

I build Laravel APIs for iOS, Android, and Flutter apps, with versioned resources, client version tracking, and the update prompt wired into the client, so you can retire old versions on your numbers rather than on a guess.

Related Services & Further Reading