Sparse fieldsets and compound documents¶
Two query parameters shape what a response carries: fields[TYPE] narrows which
members of a resource render, and include pulls related resources into the
same document. This page covers both — how the engine applies them, how to exempt
a member from narrowing, how default includes work, and how to read the parsed
values off an operation.
If you are new here, start with the getting started tour; this page assumes you already have a resource rendering.
Sparse fieldsets: fields[TYPE]¶
A fields[type]=a,b parameter restricts the type resource to the named members
— both attributes and relationships. Anything not listed is dropped. The engine
applies this efficiently: it only invokes the member callables that survive the
filter, so a narrowed payload does no work computing values you discarded.
The id is always present. It is structural identity, not an attribute member,
so it is exempt from narrowing.
Worked example: narrowing an album¶
AlbumResource declares
title, releasedAt, releaseInfo, explicit, the date fields, and the
artist / tracks relationships. Ask for just the title:
Only title survives in attributes; the id and type remain because they are
structural. A fieldset can name a relationship too — fields[albums]=title,artist
keeps the title attribute and the artist relationship and drops everything else,
including tracks. See
SparseFieldsetsAndIncludesTest
for the assertions that pin this behaviour.
Nested fieldsets¶
An attribute declared with nestedFieldset(), an Obj
or a Map, also accepts <attribute>.<key> members, each selecting one key of its
object:
{
"data": [{
"type": "people",
"id": "1",
"attributes": { "name": "Ada Lovelace", "address": { "postcode": "SW1A 1AA" } }
}],
"jsonapi": { "version": "1.1", "profile": ["https://haddowg.github.io/json-api/profiles/nested-fieldsets/"] }
}
A key whose own object declares nestedFieldset() takes a longer path, one key per
level. fields[people]=address.geo.lat renders address holding only geo, and geo
holding only lat.
A list whose element declares nestedFieldset() takes * for every item.
fields[orders]=lines.*.sku renders lines with every item kept, in order, each holding
only sku:
The rules:
- Listing the attribute itself and a key of it,
fields[people]=address,address.postcode, renders the whole attribute. The same holds at each level, soaddress.geo,address.geo.latrenders all ofgeo, and*counts as a level:lines,lines.*.skuandlines.*,lines.*.skuboth render every item whole. - A
OneOf, as an attribute, a child or a list's items, renders its discriminator and the selected keys its own variant accepts. A key is accepted when one variant accepts it. lines.*on its own is read aslines: it selects the whole list and narrows nothing, so it doesn't bring the profile. The same goes inside a path, whereshipping.parcels.*selectsparcelswhole.- A list keeps its length and order. An item without a selected member renders without
it, as
{}when nothing selected is left, and an empty list renders[]. - A path selects nothing else of the objects it passes through:
address.geo.latleaves out the street, the postcode andgeo.lng. - A request without
fields[people]renders every resource as before. - A key the declaration rejects, a dotted member on an attribute that declares no
nested fieldset, a dotted member on a relationship, an empty key, a path continuing
past a key whose object declares no nested fieldset,
*on anything but a list whose element declares a nested fieldset, and an index such aslines.0are unknown fieldset members: a400FieldsetMemberUnrecognizedunder strict query-parameter validation. Without strict validation an unknown nested fieldset member is dropped: it selects nothing, and its attribute renders only iffields[TYPE]also lists it whole. - The nested fieldsets apply to the type wherever it renders: primary data,
included, related endpoints, a write answering with the resource and atomic results. - Request bodies are unchanged; a nested fieldset shapes only what renders.
- Whether a response carries the profile is decided from the request, not from what renders. A request narrowing an attribute the server accepts gets the profile even when its collection is empty or holds no resource of that type.
JSON:API 1.1 says a fields[TYPE] member is a field name, so a response that narrows an
attribute this way applies the
Nested Fieldsets profile, which a client never has to ask
for. When the request narrows an attribute of a type the server serializes, and the server
registers Schema\Profile\NestedFieldsetsProfile, the response's Content-Type carries
profile="https://haddowg.github.io/json-api/profiles/nested-fieldsets/" and its
jsonapi.profile lists the URI. A request narrowing nothing gets an unchanged response. A
server that doesn't register the profile still narrows, without advertising it.
A type rendered by a serializer override is narrowed the same way, against the fields its Resource class declares.
Resource\NestedFieldsets holds the parsing and acceptance rules the resource, the server
and the responses share, for an adapter that needs the same answers.
Exempting a member: notSparseField()¶
Sometimes a member must always render — say a checksum or a status flag a client
relies on. Call notSparseField() on the field and it is serialized regardless of
any fields[type] parameter:
isSparseField() on the field reports whether it participates; a field that opts
out is excluded from the narrowing pass entirely. A relation declared
notSparseField() keeps its relationship object the same way. A field that is hidden or
write-only for the request still never renders.
An empty fields[type]=, listing nothing, renders no fields of the type, and that includes
notSparseField() members: a client asking for no fields gets none. An empty member
anywhere in the list counts as the same empty selection, so fields[type]=title, with its
trailing comma renders no fields either. This is the one member-level
override — every other field follows the fieldset. See
fields for the rest of the shared field surface.
Compound documents: include¶
include builds a compound document: the requested related resources are fetched
and placed in a top-level included array alongside the primary data. Paths are
comma-separated and may be nested with a dot — ?include=artist,tracks.playlists
includes each album's artist, its tracks, and each track's playlists.
Worked example: an album with its artist and tracks¶
{
"data": {
"type": "albums",
"id": "1",
"relationships": {
"artist": { "data": { "type": "artists", "id": "1" } },
"tracks": { "data": [ { "type": "tracks", "id": "1" }, ... ] }
}
},
"included": [
{ "type": "artists", "id": "1", "attributes": { ... } },
{ "type": "tracks", "id": "1", "attributes": { ... } },
...
]
}
The data member carries linkage (the {type, id} identifiers); the full related
resources live in included. Fieldsets compose with includes — adding
fields[artists]=name narrows the included artist's attributes to name,
exactly as it would the primary resource.
Deduplication; primary takes precedence¶
included never carries the same {type, id} pair twice. Fetch a collection of
albums that share an artist with ?include=artist, and that artist appears once.
A resource that is part of the primary data is also never duplicated into
included — the primary representation wins.
Default-included relationships¶
A resource can include a relationship by default, applied only when the request
sends no include. There is no fluent "include by default" field method; this
lever lives on the serializer contract. Override
getDefaultIncludedRelationships() and return the relationship names:
// AlbumResource
public function getDefaultIncludedRelationships(mixed $object): array
{
return ['artist'];
}
With that override, GET /albums/1 (no ?include) emits the artist in
included. The moment a request sends any include, the default is suppressed
— GET /albums/1?include=tracks includes the tracks and not the artist. The
signature is getDefaultIncludedRelationships(mixed $object): array; it is passed
the domain object so the set can vary per record.
How a relation participates in included¶
A relationship's linkage policy interacts with includes. An owner-side to-one
(BelongsTo/MorphTo) renders its linkage (data) on every response. A lazy
relation — the default for a to-many and HasOne, as tracks is on AlbumResource —
emits linkage only when the related data is already loaded, to avoid forcing a fetch.
When that relation is explicitly included, the include wins: the resources are
fetched and both the linkage and the included entries appear. See
relations for the full linkage and links policy.
An included to-many is paginated like its related endpoint: the linkage and
included hold the first page of its members, and the relationship object's
links carry first, next and the rest of its pages. A relation declared
withoutPagination() includes its whole set. See
pagination.
A relation declared with a foreign key
includes the related rows whose foreign key holds the parent's id, read for the whole
page of parents at once.
Constraining includes: the safeguards¶
By default every declared relationship is includable at every path, and nested
?include chains are unbounded. Three composable safeguards let you constrain that
— and guarantee a compound document always terminates (a mutual default-include
cycle would otherwise recurse forever).
Per-relation opt-out: cannotBeIncluded()¶
Mark a relation non-includable on the field. A ?include naming it (at any path)
is rejected with 400 InclusionNotAllowed, and it is dropped from the
default-include cascade. Its linkage and its self / related links are
unaffected — only the compound expansion is suppressed.
cannotBeIncluded() also takes a (mixed $model, JsonApiRequestInterface $request): bool
closure, which prohibits the include only for the resources and requests it returns
true for. It runs at render time, once per resource carrying the relation, and an
include it prohibits is the same 400. See relations.
Maximum include depth¶
Depth is the number of relationship hops from the primary resource:
?include=artist is depth 1, ?include=tracks.playlists is depth 2,
?include=tracks.playlists.owner is depth 3. A cap of N allows depth ≤ N and
rejects deeper requests with 400 InclusionDepthExceeded.
Set a server-wide default (core is unopinionated: unset, or any value <= 0, means
unlimited):
A resource overrides the default for itself by implementing
IncludeControlsInterface::maxIncludeDepth() (an AbstractResource subclass just
overrides the method — it already implements the interface):
// AlbumResource — cap includes rooted at an album at 2, beating the server default
public function maxIncludeDepth(): ?int
{
return 2;
}
Resolution is resource override ?? server default, with <= 0 normalised to
unlimited. Beyond the cap the compound expansion is silently dropped from the
default cascade (the linkage identifier is still emitted), so the cascade always
terminates; an over-deep requested path is the up-front 400.
Allowed include paths (root-scoped whitelist)¶
cannotBeIncluded() is all-or-nothing for a relation at its own resource. To allow
a relation directly yet forbid it as a nested path from a parent, declare the full
dotted paths permitted when this resource is the request's primary/root type, via
IncludeControlsInterface::getAllowedIncludePaths():
// UserResource — posts (and posts.author) are includable, but posts.comments is not
public function getAllowedIncludePaths(): ?array
{
return ['posts.author'];
}
GET /users/1?include=posts.comments is now 400 InclusionNotAllowed even though
comments is includable when a post is the root
(GET /posts/1?include=comments still succeeds). Listing a deep path implies its
ancestors — ['posts.author'] permits posts and posts.author without
enumerating every prefix, but not the sibling posts.comments. null (the default)
is unrestricted (today's behaviour); an empty list [] permits no includes at all.
Excluded include paths (root-scoped)¶
When most paths are fine and only a few should be refused, list those instead via
IncludeControlsInterface::getExcludedIncludePaths():
// UserResource — everything stays includable except posts.comments and what lies below it
public function getExcludedIncludePaths(): array
{
return ['posts.comments'];
}
GET /users/1?include=posts.comments and ?include=posts.comments.author are both
400 InclusionNotAllowed, while posts itself is still includable. Unlike the allow
list, an excluded path refuses everything below it. Like the allow list, it is
evaluated against the root resource only, takes plain dotted paths with no
wildcards, and checks requested paths only: a relation the resource includes by
default still renders. Use cannotBeIncluded() to stop that. The default []
excludes nothing.
The safeguards compose: a path is permitted only if every hop's relation is includable, it is within the effective max depth, it is in the root's allowed paths when one is set, and it is not at or below one of the root's excluded paths. Declaring both lists lets you allow a deep tree and carve a branch out of it.
Reading the parsed query¶
Inside a handler, the parsed query parameters hang off the operation as a plain value object:
$query = $operation->queryParameters();
$query->fields; // array<string, list<string>> — keyed by type
$query->includes; // list<string> — the requested include paths
QueryParameters is a readonly value object — the public properties are the
accessors, there are no getters. fields is keyed by resource type to its
requested member names; includes is the flat list of include paths (a nested
tracks.playlists arrives as the single string tracks.playlists). The
in-memory handler
reads these off the operation when it builds a response. Malformed values are
tolerated and skipped during parsing — well-formedness of the request itself is
the negotiation layer's job, not this projection's.
An unknown fields[type] member is not tolerated while
strict query-parameter validation
is on, as it is by default. Before the handler runs, Server checks every member
of every fields[type] against that type's declared field names and rejects one
that names no declared field with a 400 FieldsetMemberUnrecognized. The check
covers the types of included resources too, and counts hidden and write-only fields
as declared, so it gives nothing away about them. An <attribute>.<key> member is
known when the attribute declares a nested fieldset
that accept the key, and an <attribute>.*.<key> member when the list's element does. It skips a type the server doesn't
register and a serializer that doesn't declare its field names. With strict
validation off, an unknown member is ignored.
The fields and include families themselves are always recognized, so they never
trip the family-level check: an unrecognized query-parameter family (a misspelled
?inclde=..., an unregistered custom parameter) is a 400 QueryParamUnrecognized.
An include path naming an unknown relationship is its own
400 InclusionUnrecognized, covered in Spec errors below.
Include paths are checked before any data¶
Server checks every include path against the primary type's declared
relationships before the handler runs, on both dispatch() and handle(), so
GET /albums?include=bogus is a 400 even when there are no albums. This check
runs whether or not strict query parameters are on. The primary type is the
target's type, or the relation's related type on a related endpoint
(/albums/1/artist?include=...).
On a relationship endpoint the paths start at the parent, as in the spec's own
/articles/1/relationships/comments?include=comments.author. The parent's allowed
and excluded include paths and its maximum include depth apply, and a path is
checked whole, so ?include=bogus or ?include=author.bogus is a 400 there
even though it never reaches the requested relationship. The relationship reads
and the relationship mutations that answer with the linkage are checked the same
way, before the parent loads. A mutation of a
write-only relation answers 204 with no
document, so, like a delete, it ignores include. The linkage document itself
carries no included member, whatever paths are valid.
A nested path walks the related types through
the registry, and a segment after a polymorphic relation is accepted when any of
its declared types has it. The checks run in the order rendering applies them:
the root's allowed include paths, then its excluded include paths, then the maximum include depth, then unknown and
cannotBeIncluded() segments, so each request gets the error it got before.
Rendering keeps its own per-resource check. It covers what can't be known without
an object: a cannotBeIncluded() or hidden() predicate, a serializer that is
not an AbstractResource, and each member of a polymorphic relation, which must
itself have the next segment. Custom actions and atomic operations are not checked
up front.
Spec errors¶
| Exception | Status | When |
|---|---|---|
InclusionUnrecognized |
400 |
An include path names a relationship the endpoint does not recognize. The error's source is the include parameter and lists the offending paths. |
InclusionNotAllowed |
400 |
An include path names a relationship marked cannotBeIncluded(), a path outside the root resource's getAllowedIncludePaths() whitelist, or a path at or below one of its getExcludedIncludePaths(). Lists the offending paths. |
InclusionDepthExceeded |
400 |
An include path is deeper than the effective maximum include depth. Lists the offending paths and the cap. |
InclusionUnsupported |
400 |
The endpoint does not support inclusion at all. |
FieldsetMemberUnrecognized |
400 |
Under strict query-parameter validation, a fields[type] member names no declared field of that type, or an <attribute>.<key> member names a key the attribute doesn't let a request select. Its source.parameter is fields. |
The Inclusion… errors render as JSON:API errors with source.parameter set to include. See
errors and exceptions for the propagation model and the
full exception catalogue.
Next / see also¶
- fields — the shared field surface, including
notSparseField(). - relations — linkage policy and
withData(). - pagination — windowing the primary collection and related to-many collections.
- errors and exceptions —
InclusionUnrecognized/InclusionNotAllowed/InclusionDepthExceeded/InclusionUnsupportedand the rest of the catalogue.