Ehsan Bagherzadegan
Back to articles
7 min read

Laravel Rest API 3.0: Typed Fields, Metrics, and OpenAPI Docs

Laravel Rest API 3.0 rebuilds the package around typed field objects that drive filters, validation, responses, and OpenAPI docs via Scramble — plus new metric endpoints and 428-based confirmations for safe destructive operations.

Laravel Rest API 3.0, released in early November 2026, is a complete rebuild of the lomkit/laravel-rest-api package. The headline change is typed fields — a shift from declaring simple column names to defining field objects (Text, Integer, Enum, Date, Json, and more) that simultaneously drive filters, validation, response serialization, and OpenAPI documentation.

If you build JSON APIs with Laravel, this release is worth studying. It consolidates concerns that usually live in separate places — request validation, query filtering, resource transformation, API docs — into a single source of truth. The package now requires PHP 8.3+ and Laravel 13.30+ (Laravel 12 projects stay on the 2.x line).

Typed Fields: One Declaration, Four Jobs

In version 2, a resource listed column names and attached validation rules separately. Version 3 replaces that with field objects. Each field knows its type, its validation rules for creation and update, how it should be filtered, and how it appears in the OpenAPI schema.

use Lomkit\Rest\Http\Fields\ID;
use Lomkit\Rest\Http\Fields\Text;
use Lomkit\Rest\Http\Fields\Integer;
use Lomkit\Rest\Http\Fields\Enum;
use Lomkit\Rest\Http\Fields\Date;
use Lomkit\Rest\Http\Fields\Json;

public function fields(): array
{
    return [
        ID::make('id'),
        Text::make('title')
            ->rules('max:80')
            ->creationRules('required'),
        Integer::make('seats')
            ->rules('min:0'),
        Enum::make('status', ShowStatus::class)
            ->offered([ShowStatus::Planned, ShowStatus::OnSale]),
        Date::make('starts_on')
            ->creationRules('required'),
        Json::make('metadata')->nullable(),
    ];
}

A Text field automatically registers a contains filter. An Integer field gets eq, gt, lt, gte, lte. An Enum field restricts the filter to the enum's cases. The offered() method on Enum is particularly useful: it limits writable values to a subset (e.g., only Planned and OnSale during creation) while still allowing the full enum range to be read and filtered — handy for workflows where some statuses are set only by the system.

Field classes also carry serialization logic. A Date field returns an ISO 8601 string; a Json field returns a parsed object or array. You no longer need a separate transformer layer.

OpenAPI Documentation via Scramble

Version 2 shipped a custom documentation generator. Version 3 removes it entirely and delegates to Scramble (the OpenAPI generator by Dedoc). Because Scramble reads your actual route definitions, validation rules, and now the typed fields, the generated /docs/api endpoint stays in sync with the running code — no separate rest:documentation command to remember.

The payoff: every field's type, validation rules, and filter operators appear in the spec automatically. Enum fields show their allowed values. Nested resources and relations are documented. The test suite can even assert that the OpenAPI spec matches actual responses (rest:check does this in CI).

If you already use Scramble, the integration is zero-config. If you don't, the package installs it for you.

Metrics: Declarative Dashboard Endpoints

Version 3 introduces a new concept: metric resources. These are read-only endpoints that return aggregated data — counts, sums, averages, trends over time, partitioned breakdowns, progress toward a target, or tabular summaries. You define them similarly to regular resources:

use Lomkit\Rest\Http\Metrics\Value;
use Lomkit\Rest\Http\Metrics\Trend;
use Lomkit\Rest\Http\Metrics\Partition;
use Lomkit\Rest\Http\Metrics\Progress;
use Lomkit\Rest\Http\Metrics\Table;

public function metrics(): array
{
    return [
        Value::make('total_revenue')
            ->query(fn ($q) => $q->sum('amount'))
            ->format(fn ($v) => '$' . number_format($v, 2)),

        Trend::make('revenue_trend')
            ->query(fn ($q) => $q->selectRaw('DATE(created_at) as date, SUM(amount) as total')
                ->groupBy('date'))
            ->dateRange('30 days')
            ->timezone('UTC'),

        Partition::make('revenue_by_status')
            ->query(fn ($q) => $q->select('status', DB::raw('SUM(amount) as total'))
                ->groupBy('status'))
            ->label(fn ($row) => $row->status)
            ->value(fn ($row) => $row->total),

        Progress::make('sales_target')
            ->query(fn ($q) => $q->sum('amount'))
            ->target(100_000),

        Table::make('top_events')
            ->query(fn ($q) => $q->select('name', 'venue', DB::raw('SUM(tickets_sold) as total'))
                ->groupBy('name', 'venue')
                ->orderByDesc('total')
                ->limit(10)),
    ];
}

Metrics respect policies and filters automatically. They support date ranges, time zones, period comparisons, and caching via ->cacheFor(now()->addMinutes(5)). This replaces the ad-hoc controller methods many teams write for admin dashboards.

Confirmations: Safe Destructive Operations

A common API problem: how to prevent accidental bulk deletes or irreversible actions without adding a separate "confirm" endpoint or relying on session state. Version 3 solves this with the 428 Precondition Required pattern.

When a resource or action declares ->confirmable(), the first request returns 428 with a signed token in the response body. The client resends the same request with that token in a X-Confirm-Token header. The token is single-use, time-limited, and bound to the exact request parameters. No session, no extra route, no frontend-specific flow.

// Resource-level: bulk destroy requires confirmation
public function destroy(BulkDestroyRequest $request): JsonResponse
{
    return $this->bulkDestroy($request)->confirmable();
}

// Action-level: irreversible operation
public function publish(PublishAction $action): JsonResponse
{
    return $action->confirmable()->handle(fn () => $this->event->publish());
}

This is a small but practical addition that eliminates a whole class of "oops I didn't mean to delete all 50,000 records" incidents.

Search, Writes, and Actions: The Rest of the Upgrade

Search

The search system now supports relation filter groups, aggregate columns, and Laravel Scout full-text search. A new Rest::search() facade method lets you reuse the search logic from jobs or CLI commands — not just HTTP requests.

Writes

Nested creates and updates now run in a single transaction by default. Optimistic locking via ->versioned() returns 409 Conflict when the resource has changed since the client fetched it. Deadlock retries are built in.

Actions

Actions can target a single resource, a search result set, or nothing at all (fire-and-forget). Chunked/queued execution with progress reporting handles large batches without timing out.

Authorization

Policies run on every reached resource and row before any write. A new perimeterQuery() method lets you scope the visible dataset per user (e.g., "only events in organizations the user belongs to"). Decision caching avoids repeated policy checks within one request.

Limits

Global limits live in config/rest.php — maximum list size, relation depth, response row count, and more. Requests that exceed them are rejected with 422 before the query runs, protecting the database from runaway requests.

Migration: What Breaks

The upgrade guide (in the 3.x branch on GitHub) lists every breaking change. The big ones:

  • PHP 8.3+ and Laravel 13.30+ required. Laravel 12 projects must stay on 2.x.
  • Field declarations change completely. Column strings become field objects.
  • Custom filters and serialization move into field classes.
  • The rest:documentation command is gone. Switch to Scramble.
  • Some config keys renamed or restructured. Check config/rest.php.

The package includes a rest:quick-start command that inspects your database and generates resource skeletons with typed fields — useful for both new projects and seeing how your existing models map.

When to Reach for This Package

Laravel Rest API shines when you need a full-featured, policy-aware, self-documenting API with minimal boilerplate — admin panels, partner integrations, multi-client backends. The typed field model pays off most when the same fields are filtered, validated, and documented in multiple places.

It's less ideal if you:

  • Need highly customized response shapes per endpoint (the resource model is opinionated)
  • Want to avoid the Scramble dependency
  • Are on Laravel 12 or PHP 8.2 (you're locked to 2.x)

Takeaway

Version 3.0 is a cohesive redesign around a single idea: describe your data once, get filters, validation, serialization, and docs for free. The typed field system is the linchpin — it turns what used to be scattered configuration into structured, reusable PHP classes. Metrics and confirmations address real gaps in typical API tooling. If you're starting a new API on Laravel 13+, it's a strong default choice.

Sources