Custom (non-CRUD) actions¶
Some operations don't fit the CRUD verbs: publish an article, archive a
playlist, upload an avatar, run a one-off command over a collection. The bundle
gives these a first-class home — author-defined custom actions that hang off a
resource type under a reserved -actions URL segment, dispatch through the same
core pipeline as every CRUD operation (so they inherit query validation, the
serving gate, and error rendering for free), and can associate a custom
request/response document while staying valid JSON:API.
An action is a standalone capability: a class implementing
ActionHandlerInterface, declared with #[AsJsonApiAction] and discovered by
autoconfiguration — exactly the standalone-serializer/hydrator pattern from
capability composition. There is no
AbstractResource sugar; an action is its own small unit that names the type it
mounts on.
The URL structure¶
Every action lives under a fixed, reserved -actions segment, at one of two
scopes:
| Scope | Path | The handler gets |
|---|---|---|
| Resource | POST /{uriType}/{id}/-actions/{action} |
the {id} resolved to an entity (via the type's DataProvider) before the handler runs |
| Collection | POST /{uriType}/-actions/{action} |
no entity (null) — the action operates on the type as a whole |
A singleton type serves only resource-scope actions,
at POST /{uriType}/-actions/{action}. The handler gets the caller's resource, loaded
with the id the type resolves, and a caller with none gets a 404. Mounting a
collection-scope action on a singleton fails the container build.
{action} is a single path segment naming one action. -actions is a safe
reserved literal: JSON:API member names cannot begin with a dash, so it can never
collide with a resource id or a relationship name. The route loader
emits action routes before the generic /{uriType}/{id} and
/{uriType}/{id}/{relationship} routes, so the literal is never captured as an
{id} or {relationship} — an action is never shadowed by a CRUD or relationship
route.
POST is the default method, but an action may declare any of GET / POST /
PATCH / PUT / DELETE. A request whose method matches no declared action route
gets Symfony's standard 405.
Declaring an action¶
use haddowg\JsonApiBundle\Action\ActionContext;
use haddowg\JsonApiBundle\Action\ActionHandlerInterface;
use haddowg\JsonApiBundle\Action\ActionInput;
use haddowg\JsonApiBundle\Action\ActionScope;
use haddowg\JsonApiBundle\Attribute\AsJsonApiAction;
use haddowg\JsonApi\OpenApi\Metadata\ActionResource;
use haddowg\JsonApi\Response\DataResponse;
use haddowg\JsonApi\Response\ErrorResponse;
use haddowg\JsonApi\Response\MetaResponse;
use haddowg\JsonApi\Response\NoContentResponse;
#[AsJsonApiAction(
type: 'articles', // mount type: the {uriType} segment + the DEFAULT serializer/hydrator
path: 'publish', // the {action} segment
methods: ['POST'], // default ['POST']
scope: ActionScope::Resource, // Resource (default) | Collection
input: ActionInput::None, // None (default) | Document | Raw
inputType: null, // the type a Document request holds; required for Document, unused otherwise
responds: [new ActionResource('articles')], // the OpenAPI success response set; omitted = a 200 mount-type document
server: null, // multi-server assignment; defaults to the implicit `default`
security: "is_granted('PUBLISH', subject)", // optional authz expression (see Authorization)
name: null, // optional route-name override
asLink: false, // expose as a security-aware `links` member (resource scope only)
tags: [], // OpenAPI tags; empty inherits the mount type's resource tags
summary: null, // OpenAPI operation summary / description
description: null,
accepts: [], // request media types the action takes; empty = its input mode's default
example: null, // OperationExample override for the generated example; false emits none
readOnly: null, // declared safety, stamped as OpenAPI x-safety; null leaves a flag out
destructive: null,
idempotent: null,
extensions: [], // OpenAPI x- extensions for this action's operation only
scopes: null, // OAuth scopes this action needs; null asks the scope resolver (see Scopes)
)]
final class PublishArticle implements ActionHandlerInterface
{
public function handle(ActionContext $context): DataResponse|MetaResponse|NoContentResponse|ErrorResponse
{
$article = $context->entity(); // resolved Article (resource scope)
$article->publish();
// …persist the change…
return $context->data($article); // renders through the outputType serializer
}
}
The two scope/input enums:
ActionScope—Resource|Collection.ActionInput—None|Document|Raw.
That's the whole declaration surface. Autoconfiguration tags the class, the bundle's compiler pass assembles the per-server action route descriptors, and the route loader emits the route — no manual routing, no controller.
The three input modes¶
CRUD writes always take a JSON:API document; actions span a wider range, so the
input contract is permissive and chosen per action with input:.
| Mode | Request handling | What the handler receives |
|---|---|---|
None (default) |
no body read; request Content-Type not required |
$context->input() is null |
Document |
parsed + structurally validated as JSON:API (negotiate, JSON decode, top-level members, optional opis schema) and semantically validated through the Validator bridge against inputType's constraints |
$context->input() is the hydrated object of inputType |
Raw (escape hatch) |
request Content-Type negotiation relaxed (a multipart/form-data upload is not application/vnd.api+json); no JSON-API body parsing or validation |
$context->request() exposes the raw body + uploaded files; $context->input() is null |
In every mode the response Accept negotiation stays intact — only the
request body content-type assertion is relaxed for Raw.
None — no body¶
The simplest action. A resource-scope None action is the classic "do a thing to
this entity" verb:
#[AsJsonApiAction(type: 'playlists', path: 'archive', responds: [new NoContent()])]
final class ArchivePlaylist implements ActionHandlerInterface
{
public function handle(ActionContext $context): NoContentResponse
{
$playlist = $context->entity();
$playlist->archive();
// …persist…
return $context->noContent(); // 204
}
}
The handler returns a 204, so it declares responds: [new NoContent()] — the generated
OpenAPI document then advertises a 204 response instead of a 200 body (see
The response contract below).
Document — a JSON:API body, hydrated and validated¶
Document mode runs the full write pipeline on the body: it is parsed,
structurally validated, semantically validated through the Validator
bridge against inputType's constraints, and hydrated to an
object. A PATCH validates and hydrates the body in the update context, so a field
read-only on create can be written and onUpdate() rules apply; any other method uses
the create context. A Document action must name its inputType: the type the request
document holds. Leaving it out fails the container build, naming the action. The
usual choice is a type that exists only to be that input, declared
relatedOnly so it gets
no endpoints of its own:
#[AsJsonApiResource(relatedOnly: true)]
final class PublicationResource extends AbstractResource
{
public static string $type = 'publications';
public function fields(): array
{
return [Id::make(), DateTime::make('publishedAt')->required()];
}
}
#[AsJsonApiAction(type: 'articles', path: 'publish', input: ActionInput::Document, inputType: 'publications')]
final class PublishArticle implements ActionHandlerInterface, ActionInputFactoryInterface
{
public function newInput(JsonApiRequestInterface $body): object
{
return new Publication(); // the blank object the body is hydrated onto
}
public function handle(ActionContext $context): DataResponse
{
$article = $context->entity(); // the existing entity (resource scope)
$input = $context->input(); // the hydrated Publication from the request body
// input and entity are INDEPENDENT — apply input onto entity yourself:
$article->publishAt($input->publishedAt);
// …persist…
return $context->data($article);
}
}
The body is then a publications document, validated against that type's fields
alone:
inputType may also be the mount type itself, which validates the body as a full
create of it, required fields and all.
No implicit merge. The hydrated
inputand the resolvedentityare kept independent — a resource-scopeDocumentaction reads both and applies one onto the other in the handler. This is deliberate: predictable, no magic merge.
Where the input object comes from. For Document mode the bundle resolves a
fresh input object and hydrates the body into it:
- if the handler also implements
ActionInputFactoryInterface(newInput(JsonApiRequestInterface $body): object), that object is used — this is how a bespoke command DTO backed only by a serializer/hydrator pair (no persister) supplies its blank instance; - otherwise the bundle instantiates via the
inputType's persister, which exists wheninputTypeis a type with a create endpoint, such as the mounttype.
On an object the persister instantiated, each relationship the body names holds the
related models, as a create of the type would: a to-one the related entity, and a to-many
its related entities, refilling a Collection the object already holds. Each member is
loaded through its type's provider, and one that doesn't exist is a 404. A to-many declared
with a foreign key, HasMany::make('members', 'members', 'team'), holds nothing on the model,
so the object gets its members only when its class declares a property or a setter for it.
Otherwise the handler reads the linkage from $context->request(), and the object gains no
dynamic property. A relation with
a fillUsing() hook gets the linkage instead. A to-many declared cannotChangeMembership()
is checked first. On an action called on a resource whose inputType is the mount type, the
members the body names are compared with the ones that resource holds now, read as a PATCH of
it reads them: through the foreign key for a relation declared with one, and keeping the members
the related type's scope hides, so a client restating the members it can see changes nothing.
Restating them passes and adding or removing one is a 403. A collection action has no resource, nor does
an action whose input reads as another type, so it compares them with the blank instance,
which holds none: any member it names is a 403, and an empty list passes. Nothing is
persisted, so the related entities' own sides are left as they are. An input from
ActionInputFactoryInterface is hydrated by core alone, so its relationships hold the
related ids. Its cannotChangeMembership() to-manys aren't checked at all, since the object
the factory builds is no stored resource to compare them with; the factory or the handler
decides what a change of them means.
Raw — a non-JSON:API body (uploads, blobs)¶
Raw is the escape hatch for bodies that aren't JSON:API — a file upload, a CSV,
a binary blob. Nothing is parsed or validated; the handler reads the request
directly. With no accepts list, a Raw action takes a body of any media type except
the three a browser can send cross-origin without a preflight: multipart/form-data,
application/x-www-form-urlencoded and text/plain. An upload sent as a form must
therefore list multipart/form-data in accepts:
#[AsJsonApiAction(
type: 'tracks',
path: 'waveform',
input: ActionInput::Raw,
accepts: ['multipart/form-data'],
responds: [new NoContent()],
)]
final class UploadWaveform implements ActionHandlerInterface
{
public function handle(ActionContext $context): NoContentResponse
{
$track = $context->entity();
$upload = $context->request()->getUploadedFiles()['file'] ?? null;
// …store the file, attach it to $track…
return $context->noContent();
}
}
Accepting several request media types (accepts)¶
accepts lists the request media types an action takes, and each one can be read in
its own mode:
#[AsJsonApiAction(
type: 'tracks',
path: 'import',
scope: ActionScope::Collection,
input: ActionInput::Raw,
inputType: 'track-imports', // the type a JSON:API body holds
accepts: [
'text/csv', // read in the action's mode, Raw
'image/*', // any image type
'application/vnd.api+json' => ActionInput::Document, // a JSON:API document, hydrated
new AcceptedBody('application/json', schema: TrackRows::class),
],
)]
An entry is a media type read in the action's own input mode, a media type key
mapped to the ActionInput it is read in, or core's AcceptedBody, which also gives
the OpenAPI document the body's schema. An action that reads any media type as a
Document must name its inputType, as a Document action does; leaving it out fails
the container build, naming the action and the media type. Wildcards such as image/* match any subtype,
and parameters such as charset or a multipart boundary never stop a match. The three
cross-origin form types match only when listed by name, never through a wildcard.
A body whose Content-Type matches nothing listed is a 415. The handler reads the
matched type from $context->requestMediaType() (image/png for an upload matched by
image/*), and a body read as a Document arrives hydrated on $context->input(). In
the OpenAPI document each entry becomes its own requestBody.content member, and the
operation lists the 415.
The request Content-Type¶
Every POST must send a Content-Type, even one with no body, and so must a PATCH,
PUT or DELETE that has a body. For CRUD writes, Atomic Operations and None or
Document actions it must be application/vnd.api+json; anything else is a 415.
A bodyless POST sent as application/vnd.api+json passes any action,
whatever its accepts, and the handler sees no body: clients send that type on every
POST, and it cannot be sent cross-origin without a preflight. A bodyless PATCH,
PUT or DELETE needs no Content-Type.
Custom input and output types¶
By default an action responds with the mount type, and a Document action names
the type it reads in inputType. Both documents are decoupled from the mount
type: inputType and the response type may each point at any other registered type,
including a relatedOnly resource or a standalone serializer/hydrator pair (a
capability-composed type with no endpoints of its own). So an action can accept a bespoke command
document and return a bespoke result document while both stay valid JSON:API.
#[AsJsonApiAction(
type: 'articles', // mounts under /articles, resolves the Article entity
path: 'publish',
input: ActionInput::Document,
inputType: 'publish-commands', // hydrate the body into a PublishCommand DTO
responds: [new ActionResource('publish-receipts')], // render the response as a PublishReceipt document
)]
final class PublishArticle implements ActionHandlerInterface
{
public function handle(ActionContext $context): DataResponse
{
$article = $context->entity(); // the Article (mount type)
$command = $context->input(); // a hydrated PublishCommand (inputType)
$receipt = $article->publish($command->scheduledFor());
return $context->data($receipt); // serialized as a publish-receipts document (outputType)
}
}
A bespoke command type needs only a serializer + hydrator pair (no provider, no
persister) — see capability composition for
registering a standalone type. When such a type has no persister to instantiate
its blank object, implement ActionInputFactoryInterface::newInput() on the
handler to supply the instance.
The response contract¶
The output side is strict: handle() returns a core response value object,
never a raw HTTP response. The choices:
| Return | Renders | Status |
|---|---|---|
DataResponse |
a JSON:API document, through the response serializer | 200 |
MetaResponse |
a top-level meta-only JSON:API document |
200 |
NoContentResponse |
empty body | 204 |
AcceptedResponse |
an async accept — a job document + Content-Location / Retry-After |
202 |
SeeOtherResponse |
a redirect, such as an async completion, with a Location header and no body; or a URL the action hands out |
303, or 200 with a location document |
ErrorResponse |
a JSON:API error document | the error's status |
Because the response flows through the existing ViewListener,
links, the jsonapi object, content negotiation, and error rendering are all
reused unchanged — an action document is indistinguishable from a CRUD document on
the wire.
A DataResponse loads its resources' relations the way a read does, whether the
handler built it with $context->data() or by hand, and so does the job resource of an
AcceptedResponse. Linkage, ?include and ?withCount go through the related type's
provider, so the scope, filter defaults and default order its relationship endpoint
applies hold in the action's document too. A belongsToMany with pivot fields renders
meta.pivot on its linkage and its included members at every include depth, as it does
on a read; see pivot data.
Advertising the output in OpenAPI¶
The runtime response is whatever the handler returns; the generated OpenAPI
document advertises the success response set, declared on the attribute so it
matches. responds takes one response object or a list of them, from
haddowg\JsonApi\OpenApi\Metadata:
| Declaration | Advertised success response |
|---|---|
| (omitted) | a 200 with the mount type's document schema |
responds: [new ActionResource('receipts')] |
a 200 with the named type's document schema (any registered type) |
responds: [new ActionCreated('orders')] |
a 201 Created with the named type's document schema and an optional Location header; the handler's $context->data(...) is sent as 201 |
responds: [new MetaResult()] |
a 200 referencing the shared MetaDocument component (a meta-only document, no data) |
responds: [new NoContent()] |
a 204 No Content |
responds: [new Accepted('jobs')] |
a 202 Accepted — the jobs type's document + Content-Location + Retry-After (an async accept) |
responds: [new SeeOther()] |
a 303 See Other — a Location header, no body (an async-completion redirect) |
responds: [new SeeOther('A link to the export.', 'text/csv')] |
a 200 location document and a 303; see actions that answer with a URL |
An action that can answer more than one way lists them — a poll endpoint that returns
202 while the work runs and 303 once it is done declares
responds: [new Accepted('jobs'), new SeeOther()]. The set is validated at
declaration time (ActionResponses::validate()), so an impossible set (duplicate
statuses, two job types) fails the build. Omitted, responds defaults to a 200
document of the mount type.
An action that creates the resource it returns, such as duplicating an order, declares
new ActionCreated('orders'). The handler returns $context->data($order) as usual and the
response is sent as 201, so the status cannot drift from the declaration. Add the URL of
the new resource with ->withHeader('Location', ...) if you want it. An action that can
also answer with an existing resource declares both new ActionResource('orders') and
new ActionCreated('orders'); its response then stays 200 unless the handler calls
->withStatus(201).
responds exists because the projector cannot read the handler's body. To stop the
declaration drifting from the handler, the bundle guards at compile time: a
handler whose handle() return type is narrowed to exactly NoContentResponse must
declare a new NoContent(), and one narrowed to exactly MetaResponse must declare a
new MetaResult() — otherwise the container fails to compile with an explanatory
error. A handler that keeps the interface's union return type opts out of the guard.
An action can also describe its operation. summary and description on the
attribute become the operation's summary and description; left out, neither key is
written:
#[AsJsonApiAction(
type: 'products',
path: 'recalculate-prices',
scope: ActionScope::Collection,
summary: 'Recalculate every product price',
description: 'Reprices the whole catalogue from the current cost and margin rules.',
)]
Operation ids¶
Each action operation in the document gets the id action.<type>.<path>. An action that
answers to more than one method gets one id per method, with the lower-case method on the
end, so a methods: ['PUT', 'DELETE'] label action on widgets is
action.widgets.label.put and action.widgets.label.delete. The route is still one route
answering to every declared method.
Client generators and tools that turn operation ids into names usually drop case and punctuation, so the bundle checks a type's actions when the container is built and fails the build, naming the handler class, when:
- one path is declared at both the resource and the collection scope, since both would get the same id;
- an action path flattens to one of the words the type's other operation ids use:
fetchCollection,fetchOne,create,update,delete,fetchRelated,fetchRelationship,updateRelationship,addRelationshiporremoveRelationship. Sodeleteandfetch-oneare refused, but anowneraction beside anownerrelation is fine; - two of the type's action ids differ only in case or punctuation, such as
export-allandexportAll.
The check runs per server, on the actions each server exposes.
Declaring how safe an action is¶
The method alone doesn't tell a client whether an action changes anything. A search sent
as POST reads like a write. readOnly, destructive and idempotent say it outright,
and the document stamps the ones you set on the action's operation as one x-safety
object:
#[AsJsonApiAction(
type: 'albums',
path: 'summary',
scope: ActionScope::Collection,
responds: [new MetaResult()],
readOnly: true,
)]
That operation carries x-safety: {readOnly: true}. A flag left null
is left out, an action that sets none gets no x-safety, and CRUD operations never get
one. readOnly together with destructive fails the container build, since an action
that changes nothing can't destroy anything.
extensions adds OpenAPI vendor extensions to the action's own operation, such as a link
to the Arazzo workflow it belongs to:
#[AsJsonApiAction(
type: 'files',
path: 'purge',
destructive: true,
extensions: ['x-workflows' => ['workflowId' => 'purgeFile']],
)]
They are merged over the mount type's type-wide extensions,
and the action's value wins on a shared name. The names follow the same rules as the
type's: a full x- name, outside the reserved x-oai- and x-oas- prefixes, or the
build fails. A declared x-safety wins over an extension of that name.
deprecated: true marks every method of the action deprecated: true in the document,
and its responses carry a Deprecation header, plus Sunset when the mount type
declares one. An action on a deprecated type is marked either
way.
Raw responses (CSV, PDF, plain JSON)¶
An action can answer with a body that is not JSON:API by declaring a core RawResult
per media type in responds, beside or instead of its JSON:API response. The request's
Accept header picks one before the handler runs, and $context->responseMediaType()
says which; $context->raw() builds the response in that type:
#[AsJsonApiAction(
type: 'albums',
path: 'export',
methods: ['GET'],
scope: ActionScope::Collection,
responds: [
new MetaResult(),
new RawResult('text/csv', schema: ['type' => 'string'], headers: ['Content-Disposition' => 'Names the downloaded file.']),
new RawResult('application/pdf', binary: true),
new RawResult('application/json', schema: AlbumCatalogueStats::class),
],
)]
final class ExportAlbums implements ActionHandlerInterface
{
public function handle(ActionContext $context): MetaResponse|RawResponse
{
return match ($context->responseMediaType()) {
'text/csv' => $context->raw($csv, headers: ['Content-Disposition' => 'attachment; filename="albums.csv"']),
'application/pdf' => $context->raw($pdfStream),
'application/json' => $context->raw(\json_encode($counts)),
default => $context->meta(['albums' => $counts]),
};
}
}
A tie in the Accept weights goes to JSON:API, so */* or no Accept still gets the
document. An Accept that matches none of the declared types is a 406. A body can be
a string, a stream resource or a PSR-7 stream; a stream is sent with Symfony's
StreamedResponse. Every raw response carries Vary: Accept, and the type's cache and
deprecation headers apply as they do to a document. Answering in a media type the request
did not negotiate is a 500, and an error is always a JSON:API document, whatever the
Accept picked. In the OpenAPI document each raw result is a media type under its
status, and a DescribesRawBody schema class becomes a component named by its short
class name.
Actions that answer with a URL¶
A download usually isn't served by the API itself. The action hands out a short-lived
link, such as a presigned storage URL. Declare SeeOther with a description and the
media type the URL serves, application/octet-stream when you don't know it, and
return the URL with its expiry:
use haddowg\JsonApi\OpenApi\Metadata\SeeOther;
use haddowg\JsonApi\Response\SeeOtherResponse;
use Symfony\Component\Clock\Clock;
#[AsJsonApiAction(
type: 'albums',
path: 'download',
methods: ['GET'],
responds: [new SeeOther(description: 'A short-lived link to the album as CSV.', mediaType: 'text/csv')],
readOnly: true,
)]
final class DownloadAlbum implements ActionHandlerInterface
{
public function handle(ActionContext $context): SeeOtherResponse
{
$album = $context->entity();
\assert($album instanceof Album);
return SeeOtherResponse::to(
'https://storage.example.com/albums/' . $album->id . '.csv?signature=example',
expiresAt: Clock::get()->now()->modify('+5 minutes'),
);
}
}
The request's Accept header picks the shape. A request naming
application/vnd.api+json, with nothing else it lists weighing more, gets a 200
document with the URL as its location link:
{
"links": {
"self": { "href": "https://music.example/albums/1/-actions/download" },
"location": {
"href": "https://storage.example.com/albums/1.csv?signature=example",
"type": "text/csv",
"meta": { "expiresAt": "2026-01-01T11:05:00+00:00" }
}
},
"meta": { "expiresAt": "2026-01-01T11:05:00+00:00" },
"jsonapi": { "version": "1.1" }
}
The album resource links the action while the album is released, through an
action link. Anything else gets the 303
to the URL. That covers a browser following the album's download link, curl, a missing Accept and */*. The 303 is there for the
browser. The document is there for a script, because fetch() can't read a 303's
Location. An Accept that lists none of the action's types is still a 303, never a
406. Both shapes send Cache-Control: no-store and Vary: Accept unless the handler
sets its own with withHeader(). Symfony appends private to that Cache-Control.
Errors stay JSON:API documents. withType() overrides the declared media type for one
response, and $context->seeOther($url, $expiresAt) is the same response.
The media type is the opt-in. A bare new SeeOther(), or one with only a description,
stays the plain 303 it always was. The OpenAPI document shows both responses. The
200 references the shared LocationDocument component, and the 303 documents
Location.
Core's location responses
describe the rendering in full.
The ActionContext¶
The handler is handed an ActionContext so it never has to thread the server. It
exposes both the resolved request state and pre-wired response factories:
| Member | Returns |
|---|---|
entity() |
the resolved entity (resource scope) or null (collection scope) |
input() |
the hydrated input (Document mode) or null |
request() |
the JSON:API request — always; the raw body + uploaded files for Raw mode |
requestMeta() |
the request's top-level meta, validated and typed against what the handler declares for the method (see declaring request meta), or empty when it declares none |
writtenMeta() |
the typed top-level meta and, for a Document input, the typed data.meta, empty when its input type declares no resourceMeta() for the write |
requestMediaType() |
the request body's media type as matched against accepts, without parameters, or null with no body |
responseMediaType() |
the media type the Accept header picked from responds: application/vnd.api+json or a raw result's type |
queryParameters() |
the parsed, strict-validated query parameters |
filtered() |
the rows the request's filter[…] parameters select, for a collection action declared with filters (see taking the type's filters) |
serializer() |
the outputType serializer |
server() |
the resolving server |
data($data) |
a DataResponse pre-wired to the response serializer |
meta($array) |
a MetaResponse |
noContent() |
a NoContentResponse (204) |
raw($body, $mediaType, $status, $headers) |
a RawResponse: a string, stream resource or PSR-7 stream sent as it is, in the negotiated raw type by default |
accepted($url, $job) |
an AcceptedResponse (202) — an async accept pointing at the poll URL, with the job as data when given (chain ->withRetryAfter()) |
seeOther($url, $expiresAt) |
a SeeOtherResponse (303): an async-completion redirect, or the URL a download action hands out, with an optional expiry |
afterCommit($callback) |
nothing; runs $callback once the action's transaction commits (see running code after the commit) |
request() is the request as the client sent it, so its body keeps each value as written,
a whole number sent as 5.0 included. The typed, normalised values come from the hydrated
input(), the values a field's fillUsing() or deserializeUsing() hook receives, and
requestMeta().
The data() / meta() / noContent() factories are the ergonomic path; reach for
the raw response value objects directly only when you need to set a status or
header the factories don't.
Declaring request meta¶
A handler declares the members of its request's top-level meta per HTTP method by
implementing core's DeclaresActionRequestMetaInterface. The method comes in an
ActionRequestMetaContext, which carries no request, since the OpenAPI document reads the
declaration with none:
use haddowg\JsonApi\Resource\ActionRequestMetaContext;
use haddowg\JsonApi\Resource\DeclaresActionRequestMetaInterface;
use haddowg\JsonApi\Resource\Field\Boolean;
final class ArchiveNote implements ActionHandlerInterface, DeclaresActionRequestMetaInterface
{
public function requestDocumentMeta(ActionRequestMetaContext $context): iterable
{
return $context->is('POST') ? [Boolean::make('silent')] : [];
}
public function handle(ActionContext $context): MetaResponse
{
$silent = $context->requestMeta()['silent'] ?? false;
// …
}
}
A call sending a member the declaration does not name, or a value it refuses, is a
422 VALIDATION_FAILED at /meta/<member>. A Document input's data.meta is validated and
applied against its input type's resourceMeta(), as a create of that type is. An action taking
a raw body carries no JSON:API meta, so declaring request meta on one fails the cache warm-up.
Taking the type's filters¶
A collection action often works on the rows the collection lists: archive everything
matching a search, export a filtered set. Declare filters and the action takes the
filter[…] parameters its mount type declares for GET /{type}, so the client sends
the same query it would send to list the rows.
#[AsJsonApiAction(
type: 'orders',
path: 'archive',
scope: ActionScope::Collection,
responds: [new MetaResult()],
filters: true,
)]
final class ArchiveOrders implements ActionHandlerInterface
{
public function __construct(private EntityManagerInterface $entityManager) {}
public function handle(ActionContext $context): MetaResponse
{
$archived = 0;
foreach ($context->filtered()->each(200) as $order) {
$order->archive();
if (++$archived % 200 === 0) {
$this->entityManager->flush();
}
}
$this->entityManager->flush();
return $context->meta(['archived' => $archived]);
}
}
filters: true takes every filter the type declares. A list such as
filters: ['status', 'placedAt'] takes only those, and a request naming any other key
gets a 400, even one the type declares. Listing a
filter family's
prefix takes every key the family resolves, and a
list filter
takes its array and comma forms as the collection does. Only a collection-scope action can take
filters. One declared at the resource scope fails the container build, and a listed key
the type does not declare fails cache:warmup, naming the handler class.
Before the handler runs, the bundle does what GET /{type} does:
- It runs the type's collection read gate. That is the
BeforeFetchCollectionEvent, so asecurityListexpression or your own subscriber on that event refuses the caller with a403here too. A caller who can't list the rows can't act on them through a filter. The action's ownsecurityexpression runs after it. - It rejects a filter key the action does not take with the
400the collection fetch gives, and checks each value against its filter's constraints the same way. - It folds in each filter's declared default, so an action reads the rows the collection would list with the same parameters.
The OpenAPI document lists the filter parameters on the action's operation, built as they are for the collection fetch.
$context->filtered() returns a FilteredCollection. It throws a \LogicException
when the action takes no filters, or when the type's data provider does not implement
QueriesFilteredCollectionInterface.
Nothing is read until you call one of its two methods:
query()returns the provider's native query builder: a DoctrineQueryBuilderfor the Doctrine provider, with the type's query extensions and the filters applied and no sort, window or count. Each call returns a new builder, so you can add your own select, update or order. It isnullfor a provider with no native builder, such as the in-memory one.each(int $batch = 500)yields every row in ascending id order,$batchat a time. Each batch reads the rows after the last id of the one before rather than using an offset, so changing or removing rows as you go never skips one.
The Doctrine provider lets go of each batch before it reads the next, so a large set
stays within memory. Every entity the loop loaded or persisted since its first batch is
detached at that point, along with its unflushed changes. What the EntityManager
managed before the loop began stays managed, such as the security user or the entity a
resource action runs on, and keeps its unflushed field changes. One of those that points
at a detached row, or holds an unflushed collection change, is reloaded from the
database instead. Flush a batch's changes before the loop asks for the next one, as the
example does, and don't keep entities from one batch to use in a later one.
The Doctrine extensions see these queries as QueryPurpose::ActionCollection, with the
request and the action's ActionDescriptor on the context. A scope that hides rows from
GET /{type} hides them from the action too.
Authorization¶
Actions are authorized by two reused layers — you write no special wiring for either:
- The request-wide serving gate. The
ServingEventfires insideServer::dispatch()for every operation, actions included, so any global authorization you already have applies automatically. - A per-action
securityexpression. Declare a Symfony Security expression on the attribute and the bundle evaluates it after entity resolution and before the handler, denying with a JSON:API403(or401when unauthenticated):
#[AsJsonApiAction(
type: 'articles',
path: 'publish',
security: "is_granted('PUBLISH', subject)",
)]
The subject variable is the resolved entity for a resource-scope action and
null for a collection-scope action — so is_granted('PUBLISH', subject)
delegates straight to an ordinary Symfony
Voter, exactly as
securityUpdate does for CRUD. The expression rides a
BeforeActionEvent, so it is evaluated per action (not per type) and needs no
resource-level registration.
A
securityexpression needssymfony/security-core,symfony/expression-languageand a configured firewall, the same as declarative authorization. Without them the container build fails and names the action.
For authorization an expression can't capture — a multi-entity rule, a
data-dependent check — subscribe to the BeforeActionEvent directly and throw a
JsonApiExceptionInterface (see lifecycle hooks).
Exposing an action as a resource link (asLink)¶
Set asLink: true and the action's URL is published as a links member on every
rendered resource of its mount type — keyed by the action's path — so a client
discovers the action straight from the resource it acts on, with no out-of-band
knowledge of the URL structure:
#[AsJsonApiAction(
type: 'articles',
path: 'publish',
security: "is_granted('PUBLISH', subject)",
asLink: true,
)]
// GET /articles/42
{
"data": {
"type": "articles",
"id": "42",
"attributes": { "...": "..." },
"links": {
"self": {
"href": "https://example.com/articles/42",
"describedby": "/docs.json#/paths/~1articles~1%7Bid%7D/get"
},
"publish": {
"href": "https://example.com/articles/42/-actions/publish",
"describedby": "/docs.json#/paths/~1articles~1%7Bid%7D~1-actions~1publish/post"
}
}
}
}
The link is security-aware. When the action declares a security expression,
its link is rendered only when the current requester would pass that same gate —
evaluated exactly as the BeforeActionEvent gate evaluates it at invocation — so a
client never sees a link to an action it cannot invoke (the publish link above is
absent for a user who lacks PUBLISH on article 42). An action with no security
always renders its link.
When the server enforces OAuth scopes, the link also needs the request's
grant to cover every scope the action requires, checked for the method the link names.
A token missing one of them doesn't see the link, just as invoking the action would get
a 403. A request with no grant isn't checked for scopes, and without a configured
grant provider nothing changes. The link is added without the resource's own
getLinks() having to know about it, and an author-supplied link of the same name
always wins.
The link's describedby names the action's operation in the served OpenAPI document,
using its first declared method, and the document lists the action under its name in
the type's resource links (see links and describedby).
The link's href sits on the same base as the resource's self link. That's the
server's base_uri when one is configured, or the request host plus the prefix the
routes are imported under when it's empty (see base_uri).
The contribution applies to every rendered resource of the type, primary or
included — so GET /comments/1?include=article carries the publish link on the
included articles member too.
asLinkis resource scope only: a collection-scope action has no resource to hang a link on, soasLink: trueon aActionScope::Collectionaction is a build-time error. The security-aware visibility uses the same authorization checker as thesecuritygate, and the scope check reads the same scope table as invocation, so link visibility and invocation always agree. An action with asecurityexpression and no firewall fails the build.
Showing an action link only in some states¶
asLink renders the link whenever the action's security and scopes pass. A link that belongs
only to some states, such as completing an upload only while the file is pending,
shouldn't move that state into security. The invocation gate would then answer an
out-of-state call with a plain 403 instead of the handler's own error. Declare the link
on the resource instead, with core's ActionLink, next to its
declared links:
use haddowg\JsonApi\Request\JsonApiRequestInterface;
use haddowg\JsonApi\Resource\Link\ActionLink;
final class AlbumResource extends AbstractResource
{
public function links(): array
{
return [
ActionLink::for('download')
->when(static fn(Album $album, JsonApiRequestInterface $request): bool => $album->status === AlbumStatus::Released)
->describedAs('A short-lived link to the album as CSV, present while the album is released.'),
];
}
}
ActionLink::for() names a resource-scope action of the resource's own type. The bundle
still builds the href, the method and the describedby from the action, on the server's
link base. It checks the action's security and scopes first, then calls when() with
the rendered object and the request, and renders the link only when all of them pass.
when() is optional.
Declaring an ActionLink implies the link, so the action needs no asLink: true. When it
has one anyway, the ActionLink's condition and description apply. describedAs()
replaces the generic description of the link in <Type>ResourceLinks; the rest of the
schema is unchanged and the condition isn't described.
A resource served on several servers may name an action only some of them expose. A
server without the action neither renders the link nor lists it in its document. These
fail the build at cache:warmup, naming the resource class:
- an
ActionLinkfor a path that no server serving the type has a resource-scope action for, which is usually a typo; - a declared link named like an
ActionLink's path; - two
ActionLinks for one path.
Lifecycle events¶
BeforeActionEvent and AfterActionEvent are public lifecycle
events, symmetric with the CRUD hooks. BeforeActionEvent
fires after entity resolution and before the handler (it carries the type, the
action name, the subject, and any security expression); AfterActionEvent fires
after the handler returns. Subscribe to them for cross-cutting concerns — an audit
log, a custom authorization rule, a metric. For a writing action both run inside its
transaction.
Transactions¶
An action called with POST, PATCH, PUT or DELETE runs in one transaction on a
persister, when that persister implements
TransactionalDataPersisterInterface.
The transaction opens before BeforeActionEvent and commits after AfterActionEvent, so
it covers the gate, the handler and everything after it that can still throw before the
response value object is returned. If any of it throws, everything written through that
connection is rolled back: a flush() in the handler, a write through a persister, a
change a subscriber made. A GET action runs without one. So does an action inside an
Atomic Operations batch, where the batch owns the transaction.
The persister is the mount type's, for collection and resource actions alike. When the
mount type has none, as a read-only type may not, the inputType's persister is used, and
with neither the action runs without a transaction. On Doctrine every entity-mapped type shares one EntityManager, so whichever
type's persister it is, the transaction covers every entity the handler writes.
Unlike a CRUD write, whose after hooks run once the write has committed,
AfterActionEvent runs inside the action's transaction, so a subscriber that throws there
undoes the action. The after-commit callbacks run once
it commits, and rendering the response comes after them.
A rollback can't take back what left the database. A message dispatched to a queue, an
email sent or an HTTP call made during the action has already happened when a later step
throws, and a worker may pick up a dispatched message before the transaction commits.
Register that work with $context->afterCommit() so it
runs once the action has committed, or send messages through a transport that writes to
the same connection, such as Symfony Messenger's Doctrine transport, so the rollback
discards them.
A collection action that works through many rows, like the
archive example above, holds one transaction for all of
them, along with the row locks it takes. Flushing each batch, as the example does, keeps
memory down but commits nothing until the action returns.
Running code after the commit¶
$context->afterCommit($callback) runs the callback once the action's transaction has
committed, which is after AfterActionEvent and before the response is rendered. If the
action rolls back, the callback never runs. Here an action creates a run and queues it
for a worker, which must not pick it up before the run is in the database:
use Doctrine\ORM\EntityManagerInterface;
use haddowg\JsonApi\OpenApi\Metadata\Accepted;
use haddowg\JsonApi\Response\AcceptedResponse;
use haddowg\JsonApiBundle\Action\ActionContext;
use haddowg\JsonApiBundle\Action\ActionHandlerInterface;
use haddowg\JsonApiBundle\Attribute\AsJsonApiAction;
use Symfony\Component\Messenger\MessageBusInterface;
#[AsJsonApiAction(type: 'imports', path: 'retry', responds: [new Accepted('importRuns')])]
final readonly class RetryImport implements ActionHandlerInterface
{
public function __construct(
private EntityManagerInterface $entityManager,
private MessageBusInterface $bus,
) {}
public function handle(ActionContext $context): AcceptedResponse
{
$import = $context->entity();
\assert($import instanceof Import);
$run = new ImportRun($import);
$this->entityManager->persist($run);
$this->entityManager->flush();
$context->afterCommit(fn () => $this->bus->dispatch(new ProcessImportRun($run->id)));
return $context->accepted('https://example.test/importRuns/' . $run->id);
}
}
A GET action, or one with no transactional persister, runs its callbacks once the
handler returns without throwing. Callbacks run in the order they were registered, and one
that throws is logged at error level while the rest still run and the response goes out as
normal. The context delegates to the
AfterCommit service, which a
BeforeActionEvent subscriber or anything else the handler calls can inject to register
callbacks of its own.
Recording a rejection¶
Since 2.17 everything an action writes before it throws is rolled back, and so is what a
BeforeActionEvent subscriber wrote. An action that records a failure and then throws
loses the record. Take an action that completes an upload: it marks the file failed when
the upload doesn't check out, flushes, then throws to answer 422. Before 2.17 the mark
stayed in the database. Now the throw rolls it back, and the file looks as though nothing
happened.
Return the error instead of throwing it. A response value object returned from
handle() commits the transaction, so the mark is kept and the client still gets the
error document. The commit also runs the callbacks the action
registered, so one that should only follow a success
has to be registered on the success path:
public function handle(ActionContext $context): NoContentResponse|ErrorResponse
{
$file = $context->entity();
\assert($file instanceof File);
try {
$this->uploads->complete($file);
} catch (UploadRejected $rejected) { // your own JsonApiExceptionInterface
$file->status = FileStatus::Failed;
$this->entityManager->flush();
return ErrorResponse::fromException($rejected);
}
return $context->noContent();
}
Throw only when nothing the action wrote should survive.
On Doctrine a rollback keeps managed what the EntityManager managed before the
transaction began, such as the security user and the entity a resource action runs on,
and reloads one the action changed. Everything else the action loaded or wrote is
detached. See what a rollback leaves managed.
Error responses¶
Every error path renders as a JSON:API error document through the route-scoped
ExceptionListener:
| Situation | Status |
|---|---|
| unknown action name | 404 |
| entity not found (resource scope) | 404 |
| method not allowed for the action | 405 (Symfony routing) |
security expression denies (authenticated) |
403 |
security expression denies (unauthenticated) |
401 |
| serving gate denies | 403 |
a Document-mode body that fails validation |
422 (see validation) |
You can also return an ErrorResponse from handle() for a domain failure the
handler detects itself — it renders with the error's own status.