<!-- Source: @site/projects/frontline-api-for-laravel/docs/04-routes.md -->
<!-- Canonical: https://docs.pushery.com/frontline-api-for-laravel/routes/ -->

# Declaring routes

> How every route on the API host tells the gateway how to treat it, how a package declares its own routes, the test that checks them all, and the route list the gateway reads.

Every route on the API host, `frontline-api.host`, tells the gateway how to treat it. Declare it
with `frontline()` on the route or on its group, the way you give it middleware. A field you leave
out takes the default under `frontline-api.declaration`. The ability comes from the middleware that
already enforces it: Sanctum's `CheckAbilities` and `CheckForAnyAbility`, or a middleware of your own
that you add to `frontline-api.ability_middleware`. An alias such as Sanctum's `abilities` counts as
well, in a command or a queued job too, since the package reads a route's middleware the way a
request runs it.

```php
use App\Http\Controllers\Api\ProjectController;
use App\Http\Controllers\Api\ReceivePaymentEventController;
use Illuminate\Support\Facades\Route;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Pushery\FrontlineApi\Http\Middleware\VerifyFrontlineSignature;
use Pushery\FrontlineApi\Routing\Behavior;
use Pushery\FrontlineApi\Routing\GuardLimit;
use Pushery\FrontlineApi\Routing\Reason;

Route::domain('api.example.com')
    ->middleware(VerifyFrontlineSignature::class)
    ->frontline(limitClass: 'standard')
    ->group(function (): void {
        Route::get('v1/projects', [ProjectController::class, 'index'])
            ->name('api.projects.index')
            ->middleware(CheckAbilities::class.':projects:read')
            ->frontline(cache: true);
    });

Route::domain('api.example.com')->middleware(VerifyFrontlineSignature::class)->group(function (): void {
    Route::post('v1/payment-events/{connection}', ReceivePaymentEventController::class)
        ->name('api.payment-events.store')
        ->frontline(
            behavior: Behavior::Bypassed,
            reason: Reason::ForeignSignature,
            guardLimit: GuardLimit::perParameter('connection', perMinute: 600),
        );
});
```

A checked route names one ability, or declares `anyAbility: true` when every valid key may call
it. A route the gateway lets through without a key needs a reason and a guard limit, and takes no
limit class. A route a package registers is declared by its name under `frontline-api.routes`, and
that entry wins over what the route declares itself:

```php
'routes' => [
    'inbound-mail.receive' => [
        'behavior' => 'bypassed',
        'reason' => 'foreign_signature',
        'guard_limit' => ['per' => 'ip', 'per_minute' => 600],
    ],
],
```

A package can ship the declaration of its own route without depending on this package: it writes
the same fields into the route's action under `frontline`, as a list of layers. An entry under
`frontline-api.routes` still has the last word:

```php
Route::post('inbound/mail', [
    'uses' => ReceiveMailController::class,
    'as' => 'inbound-mail.receive',
    'frontline' => [[
        'behavior' => 'bypassed',
        'reason' => 'foreign_signature',
        'guard_limit' => ['per' => 'ip', 'per_minute' => 600],
    ]],
]);
```

Like every route on the API host, the route of a package sits on that host and runs
`VerifyFrontlineSignature` first, or the check names it. Put it there through what the package
offers for the domain and the middleware of its routes.

## Every field of a declaration

`frontline()` takes these arguments. An entry under `frontline-api.routes`, and the layer a package
writes into its route's action, take the same fields by their keys, with the values as plain text.
A field nobody sets takes its default.

| Argument | Key | Values | Default |
|---|---|---|---|
| `behavior` | `behavior` | `Behavior::Checked` or `Behavior::Bypassed`; by key `checked` or `bypassed` | `checked` |
| `reason` | `reason` | `Reason::ForeignSignature`, `SignedUrl`, `TokenInPath` or `Public`; by key `foreign_signature`, `signed_url`, `token_in_path` or `public`. A bypassed route needs one, a checked route takes none | none |
| `effect` | `effect` | `Effect::Read`, `Write` or `Delete`; by key `read`, `write` or `delete`. A route that writes or deletes also counts against `writes_per_minute` | the strongest of the route's methods: `delete` for `DELETE`, `write` for `POST`, `PUT` and `PATCH`, `read` for `GET` and `HEAD` |
| `limitClass` | `limit_class` | a limit class every tier names; a checked route only | `frontline-api.declaration.limit_class` |
| `guardLimit` | `guard_limit` | `GuardLimit::perIp($perMinute)` or `GuardLimit::perParameter($parameter, $perMinute)`; by key `['per' => 'ip', 'per_minute' => 600]` or `'per' => 'parameter:<name>'`. A bypassed route needs one, a checked route takes none | none |
| `maxBodyBytes` | `max_body_bytes` | the largest request body the gateway forwards, 0 to `2^53 - 1` bytes | 0 for a route without `POST`, `PUT` or `PATCH`, otherwise `frontline-api.declaration.max_body_bytes`, 1,048,576 as shipped |
| `mediaTypes` | `media_types` | `['request' => [...], 'response' => [...]]`, each a media type without parameters; the gateway answers another request type with 415, and with 406 only on a route whose responses include `application/vnd.api+json`, by the rule of JSON:API 1.1 that [the gateway's refusals](#the-gateways-refusals) spell out | request: `application/vnd.api+json` where the route takes a body, none otherwise; response: `application/vnd.api+json` |
| `cache` | `cache` | `true` lets the gateway keep a response, which still needs its own permission, as [caching](https://docs.pushery.com/frontline-api-for-laravel/caching.md) describes | `false` |
| `stream` | `stream` | `true` makes the gateway forward the response as it comes, without buffering it | `false` |
| `timeoutSeconds` | `timeout_seconds` | 1 to 3,600 | `frontline-api.declaration.timeout_seconds`, 30 as shipped; for a stream `frontline-api.declaration.stream_timeout_seconds`, 300 as shipped |
| `operationHeader` | `operation_header` | the header the operations of the route travel in, or `OperationHeader::MCP` | none |
| `operations` | `operations` | each operation with its limit class, as [Operations](#operations) shows | none |
| `stealth` | `stealth` | `true` makes the gateway send no rate-limit headers, and a refusal look like an unknown path | `false` |
| `anyAbility` | `any_ability` | `true` lets every valid key call the route, without an ability | `false` |

## Checking every route on the API host

Add one test to your suite, so that no route reaches the API host that the gateway does not know,
or knows otherwise than Laravel does:

```php
use Pushery\FrontlineApi\Testing\RouteDeclarationCheck;

it('declares every route on the API host', function () {
    expect(RouteDeclarationCheck::problems())->toBe([]);
});
```

In PHPUnit, `$this->assertSame([], RouteDeclarationCheck::problems());` does the same. Each line
says what is missing or wrong, and names the route with its methods and pattern where the problem is
one route's: a route without a name, with a name the gateway does not take, given twice or starting
with `frontline.`, a route without a limit class, a checked route that asks for no ability or for
one your catalog does not name, a limit class your tiers do not name, a declaration the gateway
would not take, such as an operation header without operations, operations without one or a bypassed
route without a reason or a guard limit, an operation whose limit class your tiers do not name, a
bypassed route whose middleware still asks for an ability, a method other than `GET`, `HEAD`,
`POST`, `PUT`, `PATCH` and `DELETE`, no method at all, a pattern longer than the 512 characters the
gateway takes, a segment the gateway does not match, a constraint it does not take or one that takes
a `/`, which the gateway checks against one segment of the path, a timeout above the 3,600 seconds
the gateway takes, two routes it would not tell apart, and a route that does not run
`VerifyFrontlineSignature` before its other middleware. Routes on other hosts are not checked. The
other lines concern the product sheet as a whole: no API host or no route on it, an entry under
`routes` in the config that names no route, tiers that cannot be read, no tier or tiers that name
different limit classes, and a setting under `backend` or `declaration` that a published config sets
to a number the gateway does not take, such as a `max_concurrency` of 0, since the gateway would
refuse the whole sheet.
List the abilities your keys can carry under `abilities` in the published config,
or bind your own `Pushery\FrontlineApi\Contracts\AbilityCatalog` where they live elsewhere.
`php artisan frontline:routes` runs the same check before it writes or compares the list.

## The route list

`php artisan frontline:routes` writes the routes of the API host into `frontline-api.routes_file`,
`resources/api/frontline-routes.json` by default, each as its entry of the product sheet, in the
order Laravel matches them. Commit the file: a change to a route or its declaration then shows in
the pull request. `php artisan frontline:routes --check` writes nothing, names each route that was
added, removed or changed, and fails while the file and the routes differ, so your test pipeline
can run it.

A field a route does not declare stands in the file at its default under `frontline-api.declaration`,
so write the file under the configuration your test pipeline checks it with. A timeout or a body
size set only in a local `.env` would otherwise show as a change of every route that takes it.

Both refuse routes the gateway would not take, print each problem and write nothing: a route
without a name, a declaration they cannot read, an entry under `frontline-api.routes` that names no
route, a name given twice or starting with `frontline.`, which the gateway keeps for its own
requests, and two routes that serve one method with one pattern. Laravel keeps one route per method
and pattern whatever the constraints, so the second replaces the first, while the gateway would
take the first.

## Operations

Behind some routes one path serves many operations, such as the tools of an MCP server. Name the
header the operation travels in and the operations the gateway counts and limits apart, each with a
limit class of your tiers:

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

Route::post('v1/batch', BatchController::class)
    ->name('api.batch.store')
    ->frontline(operationHeader: 'Batch-Operation', operations: ['create' => 'default', 'delete' => 'heavy']);
```

The gateway counts an operation against its own class, for the key, the tenant and the requests in
flight. Any other value of the header, a request without it and a request that sends it more than
once count as `other` against the class of the route. A route takes up to 64 operations, the header and the operations together or neither, and only
a checked route takes them. A name starts with a letter or a digit and goes on with up to 127
letters, digits, `.`, `_`, `:`, `/` and `-`, and `other` is taken.

For an MCP server, name `OperationHeader::MCP`. The operation is then the method, and for a call of a
tool, a read of a resource or a get of a prompt the method, a colon and the name, such as
`tools/call:search`, for a request of protocol version 2026-07-28 or later. A name the request sends
in Base64, as `=?base64?…?=`, counts by the text it decodes to. Such a call without a name counts as
`other`. A request without `MCP-Protocol-Version`, with it twice, or with a version that is no date
from 2026-07-28 on gets 400 `malformed_request` with that header as its source, from the gateway
outside observe mode and from Laravel's own limits in either: a server runs the tools of an earlier
version without comparing any header with the message. So does a name in Base64 that is no standard
Base64 of UTF-8 text, with `Mcp-Name` as its source. A server whose clients speak an earlier version
is declared without operations, so that every request counts against the class of the route. For a
server of `laravel/mcp`, end the chain with `frontlineMcp()`:

```php
use App\Mcp\Servers\LinksServer;
use Illuminate\Support\Facades\Route;
use Laravel\Mcp\Facades\Mcp;
use Laravel\Sanctum\Http\Middleware\CheckAbilities;
use Pushery\FrontlineApi\Http\Middleware\VerifyFrontlineSignature;
use Pushery\FrontlineApi\Routing\OperationHeader;

Route::domain('api.example.com')->middleware(VerifyFrontlineSignature::class)->group(function (): void {
    Mcp::web('v1/mcp', LinksServer::class)
        ->name('api.mcp')
        ->middleware(CheckAbilities::class.':mcp:use')
        ->frontline(operationHeader: OperationHeader::MCP, operations: ['tools/call:search' => 'heavy', 'tools/list' => 'default'])
        ->frontlineMcp();
});
```

`Mcp::web()` registers two more routes on the same path, GET and DELETE, which answer 405 with
`Allow: POST` and have no name. The gateway knows a route only by its name, so without
`frontlineMcp()` no declaration on the API host can be read. Called last, `frontlineMcp()` names the
two after the route, `api.mcp.listen` and `api.mcp.end`, and gives them its ability middleware and
what it declares for itself, but for the fields that follow from a route's method and transport. It
declares the transport of the protocol on all three: `api.mcp` takes `application/json` and answers
with `application/json` or `text/event-stream` as a stream, `api.mcp.listen` answers with
`text/event-stream` as a stream, and `api.mcp.end` answers with `application/json`. The gateway then
forwards a GET or a DELETE, and the client gets the 405 the protocol expects rather than the 404 of an
unknown path. On a POST route of your own, `frontlineMcp()` declares the transport of that route
alone. The two take no other middleware of the route, so put `VerifyFrontlineSignature` on the
group around the server: on the route alone, `RouteDeclarationCheck` names the two. A server in
`routes/ai.php` belongs in the same group there: on another host or on none, the check does not
read it, and the product sheet does not carry it.

The gateway and the package read the operation from the headers alone, never from the message, so a
call could name a cheap tool in `Mcp-Name` and call another one in the message. Protocol version
2026-07-28 requires the server to refuse a request whose `Mcp-Method` or `Mcp-Name` does not match its
message, and a server of `laravel/mcp` answers one with 400 and the JSON-RPC error `-32020` before any
tool runs. On a route of your own that names `OperationHeader::MCP`, compare the two before you run
anything.

[Laravel's own limits](https://docs.pushery.com/frontline-api-for-laravel/limits.md) pick the class of a request the same way, and the
[counts](https://docs.pushery.com/frontline-api-for-laravel/meter.md) name the operation of each count.

## The OpenAPI document

Where your application describes its API with [Scramble](https://scramble.dedoc.co), attach the
package's transformer to it in the `boot` method of a service provider:

```php
use Dedoc\Scramble\Scramble;
use Pushery\FrontlineApi\OpenApi\RouteDeclarationTransformer;

Scramble::configure()->withOperationTransformers(RouteDeclarationTransformer::class);
```

Every operation of a route on the API host then carries what the route declares, written from the
same declaration as the route list, so the two cannot disagree, and a stealth route and the
gateway's health probe are left out:

| Field | What it holds |
|---|---|
| `security` | the `bearer` scheme with the route's ability as its role, or with no role where every valid key may call the route; an empty list for a route the gateway lets through without a key |
| `x-frontline-behavior` | `checked` or `bypassed` |
| `x-frontline-limit-class` | the limit class of a checked route |
| `x-frontline-guard-limit` | the guard limit of a route the gateway lets through without a key |
| `x-frontline-effect` | `read`, `write` or `delete` |
| `x-frontline-max-body-bytes` | the largest request body the gateway forwards |
| `x-frontline-operation-header` | the header the operations of the route travel in, where it declares operations |
| `x-frontline-operations` | each operation of the route with its limit class, where it declares operations |
| `responses` | besides your application's own answers, the refusals of the gateway the operation can meet, listed below |

The transformer adds the `bearer` scheme, an API key sent as `Authorization: Bearer <key>` with
`frontline-key/1` as its `bearerFormat`, unless your document defines a scheme of that name
already. A stream of server-sent events describes one
event as the item schema of `text/event-stream`, which a document of OpenAPI 3.2 carries and one of
3.1 leaves out. Every response loses the `Transfer-Encoding` header Scramble requires of a streamed
one, a stream of events or of JSON lines and a download alike: the header belongs to one connection,
a client of the API host only ever has one with the gateway, and HTTP/2 has no such header. Routes
on other hosts stay as Scramble describes them, and so does a route on the API host without a name,
which the product sheet cannot carry and `php artisan frontline:routes --check` refuses: name every
route on the API host, a stealth one included, or the document cannot tell what the gateway does
with it. The package itself needs no Scramble, since nothing loads the transformer until your
application names it.

A route declared with `stealth: true` does not appear in the document. The gateway answers a caller
without the route's ability as it answers a path that does not exist, and a document that listed
the route would name it to every reader. The transformer adds
`Pushery\FrontlineApi\OpenApi\HideStealthRoutes` to the document transformers of the configuration
it runs under, so the one line above is enough. That transformer takes out the route's operation,
its path where no other operation is left on it, and every tag, schema and response that only the
route brought into the document. A schema that refers to itself stays, since its own definition
still refers to it.

The gateway's health probe does not appear either: the route `frontline.health`, which the package
registers on the API host at `frontline-api.gateway.health_path`. The gateway calls it itself and
answers every other caller on its path as it answers a path that does not exist, so the document
would offer a request no caller can make. The same transformer takes it out, under whichever path
it has.

### The gateway's refusals

Each operation also names the answers the gateway gives in place of your application when a request
breaks a rule the route declares. They are responses among the document's components, in
`application/vnd.api+json` with the schema `FrontlineErrorDocument`, the gateway's error document:
one error with its `status`, `code`, `title` and `detail`, the `source` it points at where there is
one, and the request id in `meta.request_id`.

| Status | Response | Error `code` | Which operations |
|---|---|---|---|
| `401` | `FrontlineUnauthenticated` | `unauthenticated` | a checked route, for a request without a valid key; it names `WWW-Authenticate` |
| `403` | `FrontlineForbidden` | `forbidden` | a checked route, for a key that lacks the route's ability or whose rules do not let it call the route or call from the caller's address |
| `406` | `FrontlineNotAcceptable` | `not_acceptable` | a route that answers in JSON:API, for an `Accept` header in which every instance of `application/vnd.api+json` carries a parameter other than `ext` and `profile`, the weight `q` aside, as JSON:API 1.1 refuses; `application/json`, `text/html` and `*/*` pass |
| `413` | `FrontlinePayloadTooLarge` | `payload_too_large` | a route whose `max_body_bytes` is above 0, for a larger body |
| `415` | `FrontlineUnsupportedMediaType` | `unsupported_media_type` | a route whose `max_body_bytes` is above 0, for a body of a media type the route does not take |
| `429` | `FrontlineRateLimited` | `rate_limited` | every route, at a limit: the key's for the route's limit class, the guard limit of a route the gateway lets through without a key, or the one on invalid keys from one address; it names `Retry-After` |

A status your application describes on an operation keeps your description, and a response or schema
your document defines under one of these names stays yours. The gateway's other answers, such as
`400` for a request it cannot read or `502` and `504` for a backend that fails, can meet any request
whatever the route declares, so no operation lists them.
