# How to Build Reliable Laravel APIs: Responses, Versioning and Idempotency

> Canonical: https://pharaonic.dev/guides/laravel/reliable-laravel-apis  
> Summary: Build Laravel APIs with consistent JSON responses, backward-compatible versions and safe request retries without creating duplicate orders or payments.  
> Published: 2026-11-26  
> Source: https://github.com/Pharaonic/guides/blob/8b162d6f506c7ad9278c9a8762c30b80da6ea227/guides/laravel/reliable-laravel-apis/index.md  
> License: Text CC BY 4.0, code MIT

A customer submits an order from a mobile application. The server creates the order, but the connection drops before the response arrives. The application retries, and a second order appears. Meanwhile, an older version of the application expects a field that a recent backend deployment removed, and its error handler cannot interpret the new validation response.

None of these failures is a database query problem. They are failures of the API contract: what the server returns, how that contract evolves, and what happens when a request is repeated. An API can be perfectly functional on a development machine and still fail all three tests in production.

> **Quick Answer / TL;DR:**
> Use a consistent response contract with real HTTP status codes, preserve incompatible representations through explicit API versions, and reserve idempotency keys atomically before executing retryable writes. Laravel provides the primitives for all three; reusable infrastructure becomes useful when the same rules must hold across many endpoints.

## Three independent guarantees

| Concern | Question the API must answer | Example failure |
| --- | --- | --- |
| Response contract | How does a client interpret the result? | Validation and authorization errors have unrelated shapes. |
| Versioning | Which contract did the client request? | An older application cannot read a renamed field. |
| Idempotency | Has this logical operation already been attempted? | Retrying an order creates another order. |

A request ID identifies an HTTP attempt for diagnostics. An idempotency key identifies a logical operation across attempts. An API version identifies a contract. Do not substitute any one of these identifiers for another.

## Start with native Laravel

### Define an explicit response contract

Laravel's [API resources](https://laravel.com/docs/13.x/eloquent-resources) separate your public representation from your database model. Its JSON response helper gives you control over status codes and headers. For a small API, these are enough.

For example, assume an authenticated order belongs to the current user and an `OrderResource` exposes only the fields intended for clients. A controller can return:

```php
return response()->json([
    'success' => true,
    'message' => null,
    'data' => (new OrderResource($order))->resolve($request),
    'meta' => null,
], 201);
```

A validation failure could use this contract instead:

```php
return response()->json([
    'success' => false,
    'message' => 'The submitted data is invalid.',
    'code' => 'order.invalid_quantity',
    'errors' => ['quantity' => ['The quantity must be at least 1.']],
    'meta' => null,
], 422);
```

The important part is the HTTP status, not just the boolean. A client should distinguish `401`, `403`, `404`, `409`, `422`, `429` and `503` without parsing a human-readable message. A `204` response must not carry a JSON body.

Centralize this logic in an application response factory and register exception rendering through Laravel's [exception configuration](https://laravel.com/docs/13.x/errors). Keep authentication challenges, rate-limit headers and retry instructions. Do not expose stack traces or database messages in production.

### Introduce a second API version

Suppose the original order representation exposes `total` in minor currency units. A newer contract needs a structured amount containing both currency and minor units. Changing the existing representation in place breaks clients that still read `total`.

Native [route groups](https://laravel.com/docs/13.x/routing) are a straightforward solution:

```php
use App\Http\Controllers\V1\OrderController as V1Orders;
use App\Http\Controllers\V2\OrderController as V2Orders;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::prefix('v1')->group(function () {
        Route::get('orders/{order}', [V1Orders::class, 'show']);
    });

    Route::prefix('v2')->group(function () {
        Route::get('orders/{order}', [V2Orders::class, 'show']);
    });
});
```

This example assumes Sanctum is installed and the controllers enforce order ownership. Keep pricing, inventory and order creation in shared domain services; only the public representation and genuinely different request semantics belong in version-specific code.

Path versioning is explicit and easy to inspect. Header versioning can keep URLs stable, but requires version negotiation and cache isolation. Query versioning is also possible, although generated pagination links must preserve the version parameter. Adding a field does not always justify a new major API contract: consider strict clients, documented compatibility guarantees and the meaning of existing fields.

### Make retries safe at the database boundary

A transaction protects a group of database changes, but two successful transactions can still create two orders. A unique business identifier is a stronger starting point. If your client supplies a stable order reference, enforce uniqueness for each customer in the database:

```php
Schema::table('orders', function (Blueprint $table) {
    $table->uuid('client_reference');
    $table->unique(['user_id', 'client_reference']);
});
```

For an existing populated table, add and backfill the reference before enforcing the constraint. The example assumes `Schema` and `Blueprint` are imported in a migration and `user_id` already exists.

With a unique index, Laravel's `createOrFirst()` can find the winner of a duplicate insert rather than create another row:

```php
$order = Order::query()->createOrFirst(
    [
        'user_id' => $request->user()->getAuthIdentifier(),
        'client_reference' => $validated['client_reference'],
    ],
    [
        'total_minor' => $serverCalculatedTotal,
        'currency' => 'USD',
    ],
);
```

This fragment assumes validated input, a configured model and a total calculated by the server, not supplied by the client. Compare the original operation's immutable inputs before treating an existing reference as a successful retry. A reused reference with different order contents is a conflict.

The uniqueness constraint protects this database invariant. It does not save the original HTTP response, track whether another request is still running, or deduplicate an external payment. Laravel's [atomic cache locks](https://laravel.com/docs/13.x/cache#atomic-locks) can coordinate concurrent workers, but a lock alone does not provide durable replay or resolve uncertain outcomes after a crash.

## Where the native approach grows complicated

As an API grows, the response factory needs to handle collections, resources and three different pagination modes. Exception handling needs to cover failures outside controllers. Version negotiation needs to reject unsupported contracts, preserve route behavior and communicate retirement. Retry handling needs an atomic state machine, request comparison, expiration and a recovery policy.

These are cross-cutting concerns. The danger is not that Laravel cannot implement them; it is that individual controllers implement subtly different versions of the same infrastructure.

A reusable solution should remain independent of business logic. In the rest of this guide, the order service still calculates prices, enforces ownership and updates inventory. The HTTP layer deals with contracts, compatibility and retry coordination.

## A reusable HTTP layer

The following examples target Laravel 13 and Laravel API Response 13.2.0 and the 13.1.0 releases of Laravel API Versioning and Laravel API Idempotency. Select the corresponding package line for other supported Laravel versions and check its PHP requirements before installation.

```bash
composer require pharaonic/laravel-api-response:^13.2 pharaonic/laravel-api-versioning:^13.1 pharaonic/laravel-api-idempotency:^13.1
php artisan vendor:publish --tag=api-response-config
php artisan vendor:publish --tag=api-versioning-config
php artisan vendor:publish --tag=api-idempotency-config
php artisan vendor:publish --tag=api-idempotency-migrations
php artisan migrate
```

The migration is needed for the default database idempotency store. An application using only the Redis store does not need that table.

### Keep the response envelope stable

[Laravel API Response](https://pharaonic.dev/packages/laravel/api-response) wraps results without replacing the resources that define your public fields. Inside an order controller, return the resource rather than serializing the entire model:

```php
use Pharaonic\Laravel\ApiResponse\Response;

return Response::success(new OrderResource($order))
    ->status(201)
    ->message('Order created.');
```

For a resource that returns an `id` and a `total`, the default success shape, before optional fields, is:

```json
{
  "success": true,
  "message": "Order created.",
  "data": {"id": 42, "total": 1299},
  "meta": null
}
```

A known business conflict can return:

```php
return Response::error('This order cannot be cancelled.', 409)
    ->code('order.not_cancellable');
```

The default error envelope is now:

```json
{
  "success": false,
  "message": "This order cannot be cancelled.",
  "code": "order.not_cancellable",
  "errors": null,
  "meta": null
}
```

The top-level `code` is always present on errors in 13.2.0, even when it is `null`. Choose stable application-defined identifiers and let clients branch on them rather than translated messages. HTTP status still describes the protocol outcome. Calling `code()` on a success throws an `InvalidArgumentException`; a profile can rename the error code field. Success responses do not acquire a code field.

If you previously published a 13.1.x contract, account for the additional field when testing strict clients or JSON schemas. See the [13.2.0 release notes](https://github.com/Pharaonic/laravel-api-response/releases/tag/13.2.0).

For a paginated order history, retain the resource and scope the query to the authenticated user:

```php
$orders = Order::query()
    ->where('user_id', $request->user()->getAuthIdentifier())
    ->orderByDesc('id')
    ->paginate(20);

return Response::success(OrderResource::collection($orders))
    ->withQueryString(['status', 'version']);
```

Only include `status` in the links if the endpoint actually applies that filter. The package places pagination information in `meta.pagination`; the paginator determines which fields are meaningful. Length-aware pagination provides totals, simple pagination avoids a total count, and cursor pagination uses cursors rather than arbitrary page numbers. Choose a stable, uniquely ordered query for cursor pagination. Never assume all three modes have a last page.

Profiles can change the envelope for a particular client contract using `profile()` with a registered profile name. Changing a published profile can itself be a breaking change. `notify()` adds client-facing notification data, not a Laravel notification delivery job. Clients should suppress duplicate success toasts when a response is replayed. For example, a successful creation can include an actionable notification:

```php
return Response::success(new OrderResource($order))
    ->status(201)
    ->notify('Order created.', 'success',
        title: 'Order confirmed',
        code: 'order.created',
        action: ['label' => 'View order', 'url' => '/orders/'.$order->id],
        duration: 5000,
        position: 'top-right');
```

The notification code is independent of the top-level error code. The optional fields are omitted when null; a duration of zero requests a persistent notification. The frontend decides how to display it and should validate action destinations.

SEO metadata is optional and requires a compatible Laravel SEO installation plus an explicit `withSEO()` call; it has no role in creating an order.

### Handle failures and trace attempts

Register the opt-in exception renderer and request ID middleware in the application's existing `bootstrap/app.php` configuration. For this API, prepend request IDs globally so negotiation failures that occur before route middleware can also be traced:

```php
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Pharaonic\Laravel\ApiResponse\ExceptionRenderer;
use Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId;

// In the existing Application::configure() chain:
->withMiddleware(function (Middleware $middleware) {
    $middleware->prepend(AssignRequestId::class);
})
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(new ExceptionRenderer);
})
```

Merge these callbacks with existing configuration rather than replacing other middleware and exception rules. The renderer does not replace Laravel's exception reporting and intentionally defers certain custom responses to Laravel. Errors built by the response exception renderer have `code: null`; it does not automatically copy identifiers from exceptions. Exceptions with their own rendering may produce a different contract. If clients need stable identifiers for versioning or idempotency failures, explicitly map those failures in application-owned rendering while preserving their statuses and headers. Unexpected exceptions in debug mode can also retain Laravel's debug response. Test the production configuration with debugging disabled.

Use `X-Request-ID` to correlate an attempt with logs. A replay can contain the original response body's request ID because its body is stored; the outer middleware can attach the current attempt's header. Do not assume these identifiers match on replays, and avoid using the body identifier as the sole tracing reference. Verify this behavior in your middleware stack.

### Negotiate versions before choosing a representation

[Laravel API Versioning](https://pharaonic.dev/packages/laravel/api-versioning) adds version constraints and controller selection to native routes. For reads with a shared URL, a controller map can select the appropriate contract using the resolved version. For writes, path versioning is particularly useful when combined with idempotency, as explained below.

In `config/pharaonic/api-versioning.php`, change the following entries of the published configuration:

```php
'versions' => ['v1', 'v2'],
'default' => null,
'resolvers' => ['path'],
'path' => [
    'prefix' => '{version}',
    'name' => '{version}.',
    'parameter' => 'version',
],
```

Assuming the standard `/api` prefix is already applied to `routes/api.php`, this produces `/api/v1/...` and `/api/v2/...` without doubling the prefix. A version list is ordered by configuration, not by a lexical comparison of its names.

A single resource can express a small representation difference while preserving the existing field. Create `app/Http/Resources/OrderResource.php`:

```php
<?php

namespace App\Http\Resources;

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

class OrderResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'total' => $this->total_minor,
            'amount' => $this->whenVersion('>=v2', fn () => [
                'minor' => $this->total_minor,
                'currency' => $this->currency,
            ]),
        ];
    }
}
```

Here `amount` is absent from v1, rather than `null`. Both versions retain `total`, allowing a gradual migration. If v2 changes validation rules or operation semantics substantially, prefer separate controllers with a shared domain service. For example, with header resolution enabled and no path prefix, a single read route may use `controllers(['v1' => [V1Orders::class, 'show'], 'v2' => [V2Orders::class, 'show']])` instead of registering duplicate method-and-URI pairs.

Version negotiation also supports lifecycle announcements. Use the `Deprecation` and `Sunset` headers described in [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745) and [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594) to communicate migration dates. Announcing a sunset does not automatically retire a version in this package; retirement requires an explicit lifecycle status change. A retired version returns `410` by default. Do not silently route an old client to a new incompatible contract.

### Reserve retries before executing a write

[Laravel API Idempotency](https://pharaonic.dev/packages/laravel/api-idempotency) adds an opt-in middleware to routes. A shared database or Redis store coordinates reservations. The request fingerprint distinguishes a legitimate retry from a different request that reuses a key.

The integrated route definitions below assume `OrderController` implements `index` and `store`, authenticates through Sanctum, and delegates actual creation to the application's order service. Both versions share business logic and use the version-aware resource above.

```php
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;

foreach (['v1', 'v2'] as $version) {
    Route::version($version)
        ->middleware('auth:sanctum')
        ->group(function () {
            Route::get('orders', [OrderController::class, 'index'])
                ->name('orders.index');

            Route::post('orders', [OrderController::class, 'store'])
                ->idempotent(ttl: 86400)
                ->name('orders.store');
        });
}
```

The version-specific path and name templates keep both route definitions distinct. The one-day replay window is an example policy, not a universal recommendation. Select a window appropriate to your clients' retry schedules.

A mobile client generates a random key once per intended purchase, persists it with the pending operation, and resends the same JSON and URL after a timeout:

```bash
curl -i https://example.com/api/v2/orders \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Accept: application/json' \
  -H 'Content-Type: application/json' \
  -H 'Idempotency-Key: 3f7682b2-9d25-42d9-813d-bb65ca693e44' \
  -d '{"product_id":15,"quantity":1,"client_reference":"971c501a-b62a-47ef-b1b2-0c7a393ed225"}'
```

The example assumes a product with ID 15, valid credentials and a store action that validates those three inputs. Repeat the command unchanged to simulate a lost response. For a completed, replayable request, the second response preserves the original status and body and includes `Idempotency-Replayed: true`. The controller should not create another order.

The key is scoped to a principal and operation. The same key with changed input, or a request arriving while the original is still in progress, receives a conflict rather than executing the write again. Clients must distinguish an in-progress conflict, which can be retried with backoff, from a fingerprint conflict, which requires correcting the operation. Use the idempotency package’s documented error representation and honor retry instructions where supplied. Do not assume its identifiers are automatically copied into the API Response `code` field.

The middleware is designed for JSON requests or requests without bodies. Do not apply it indiscriminately to multipart uploads, streaming endpoints or responses carrying session cookies. Replaying a stored response is not equivalent to regenerating it from current database state.

## The integration trap: versioning and replay

The three packages solve related problems but their boundaries still matter. In particular, the idempotency fingerprint does not include a version supplied only through an HTTP header. A retry of the same request under a different header version can therefore replay the representation stored by the earlier attempt. Path versions avoid that particular ambiguity because the routes differ.

However, separate paths also mean separate idempotency reservations. If a customer starts an order through v1 and retries through v2, the HTTP middleware alone cannot prevent a new execution. The unique business reference at the database boundary remains essential. Keep the same operation reference when migrating a pending request between contracts, and compare its immutable intent before returning an existing order.

For header-based versioning, freeze the negotiated version for the full retry cycle. If you need custom version-aware idempotency scoping, design and test it deliberately rather than assuming the packages automatically include every negotiated header. Consider language, tenant identity and other representation-affecting inputs too. A cached response may contain an older translation or notification; changing locale during a retry should not silently change the intended operation.

A useful conceptual request pipeline is:

```text
Assign attempt ID
    -> resolve API contract
    -> authenticate and authorize
    -> reserve or replay operation
    -> execute domain action
    -> build versioned resource and envelope
    -> persist replayable HTTP result
```

This is a responsibility diagram, not a replacement for Laravel's actual middleware ordering. Route matching and version negotiation can happen before route-level authentication; the idempotency middleware is prioritized after authentication, binding and authorization. Controller-level authorization alone is not sufficient for a replay that bypasses the controller. Apply relevant access checks before the idempotency middleware, and test access revocation and tenant isolation.

## Design for failure, not just duplicate requests

The difficult scenario is a process that commits an order and dies before saving the replay response. Automatically unlocking the operation and running the controller again is unsafe. The idempotency package takes a fail-closed approach to uncertain outcomes, including server failures, rather than assuming that an exception means nothing happened.

Use a durable order reference and reconcile the domain state before resolving an uncertain record. For payments, pass a stable operation identifier to the payment provider's own idempotency mechanism and persist the provider reference. An outbox can make delivery of downstream events more reliable, but consumers must still deduplicate them. Neither a database transaction nor this middleware can provide exactly-once execution across arbitrary external systems.

The default database store coordinates through atomic database operations. Redis is another option, but its persistence, eviction and failover configuration must match the risk of losing reservation records. Treat a store outage as a failure to establish safety, not permission to process the request unprotected.

Keep the replay window long enough for expected client retries, and separate ordinary expiration from uncertain outcomes. The package's pruning command previews its work by default:

```bash
php artisan idempotency:prune
php artisan idempotency:prune --apply
```

Review unresolved operations before explicitly removing their records. Do not schedule destructive recovery merely to keep the table small. Once an ordinary key expires or is removed, a later request can execute again; a domain uniqueness constraint can outlive that window.

Stored response bodies may contain personal information. Minimize their contents, restrict access to the store, and apply a retention policy. Never expose another principal's response or log raw client keys and sensitive bodies.

## Test the contract across all three boundaries

A useful integration test uses an authenticated actor, a valid product fixture and a fresh test database, including the idempotency migration. The following test body assumes `$user`, `$product` and the application order endpoint have been set up. It belongs inside a Laravel feature test using `RefreshDatabase` and Sanctum authentication.

```php
use Laravel\Sanctum\Sanctum;
use Illuminate\Support\Str;

Sanctum::actingAs($user);

$payload = [
    'product_id' => $product->id,
    'quantity' => 1,
    'client_reference' => (string) Str::uuid(),
];
$headers = ['Idempotency-Key' => (string) Str::uuid()];

$first = $this->postJson('/api/v2/orders', $payload, $headers);
$first->assertCreated()
    ->assertJsonPath('success', true)
    ->assertJsonStructure(['data' => ['id', 'total', 'amount']]);

$retry = $this->postJson('/api/v2/orders', $payload, $headers);
$retry->assertCreated()
    ->assertHeader('Idempotency-Replayed', 'true');

$this->assertSame($first->getContent(), $retry->getContent());
$this->assertDatabaseCount('orders', 1);

$changed = array_replace($payload, ['quantity' => 2]);
$this->postJson('/api/v2/orders', $changed, $headers)
    ->assertStatus(409);
$this->assertDatabaseCount('orders', 1);
```

A sequential test does not establish concurrency safety. Run parallel requests against the same production-like store in a separate integration test and verify the number of actual domain writes. An in-memory database per worker will not exercise cross-worker coordination.

| Scenario | Expected invariant |
| --- | --- |
| v1 and v2 order responses | v1 omits `amount`; v2 includes it. |
| Invalid order input | A 422 response retains field-level validation errors; the response renderer supplies `code: null`. |
| Explicit business conflict | A 409 response contains `code: order.not_cancellable`. |
| Successful order | The success envelope has no top-level `code` field. |
| Concurrent identical requests | At most one request owns the reservation. |
| Same key, changed body | A conflict is returned without a second write. |
| Same key, different authenticated users | No response is shared across principals. |
| Retry after successful commit and lost response | Replay returns the original result when it was stored. |
| Crash before replay persistence | No automatic second execution of an uncertain operation. |
| Same business reference through another API version | Domain uniqueness still prevents a duplicate order. |
| Retired API version | A request is rejected rather than silently upgraded. |
| Store unavailable | A protected write is not executed without a reservation. |
| Cached routes and configuration | Negotiation and protected writes still work. |

Test authorization before replay, the shape of translated errors from both packages, response headers on conflicts, and tracing across repeated attempts. Also test the actual cache policy when header versioning is enabled: `Vary` is necessary for shared representations but is not a substitute for private caching rules on authenticated data.

## When to use each approach

| Situation | Recommended approach |
| --- | --- |
| A small internal API with a handful of endpoints | Native JSON resources and a shared response factory. |
| Two versions with entirely separate paths and few endpoints | Native Laravel route groups may be sufficient. |
| Multiple clients with changing response shapes | Shared response infrastructure and explicit version contracts. |
| A simple write with a permanent unique business key | A database constraint and conflict handling may suffice. |
| Retryable POST endpoints with replay and concurrent requests | Atomic HTTP idempotency plus domain constraints. |
| Payments or other distributed effects | HTTP idempotency, domain invariants and provider-side deduplication. |

You do not need to install all three packages just because you use one. An API that does not expose incompatible versions may not need a versioning package. A read-only API may not need idempotency middleware. A small application with a stable envelope may already have enough response infrastructure.

## Summary

Reliable API design requires three separate decisions: how to describe an outcome, how to preserve that description as clients evolve, and how to handle uncertainty when the same operation arrives twice.

Use Laravel resources to define the representation, HTTP statuses to describe outcomes, version boundaries to protect compatibility, and atomic reservations to coordinate retries. Keep business invariants in the domain and database, where they remain effective even after a replay window expires. The HTTP layer should make these rules easier to apply consistently, not pretend that it can eliminate every distributed-system failure.
