OpenAPI generation¶
The library can project a server's worth of JSON:API metadata into an OpenAPI
3.1 document — every resource type, its CRUD, relationship, related and custom-action
endpoints, their parameters, request bodies and responses, plus the reusable component
schemas they $ref. The projection is a pure, framework-agnostic part of core:
give it a description of your server (a metadata contract) and it returns an immutable
OpenAPI value-object tree. A framework integration (the Symfony bundle) supplies that
description from its compiled registry, serves the document at an endpoint, and offers a
Swagger/Redoc UI — but the semantics (how a JSON:API type becomes an OpenAPI schema,
how an ?include becomes a parameter) live here, and are fully testable with in-core
fixtures and no framework.
This page is the reference for that projection: the model that builds the document, the
contract you implement to feed it, the field-level authoring surface that shapes the
schemas (describedAs() / example()), the per-code error catalogue, and the vendor
extensions it emits (x-generator, x-enum-*, x-profile, x-safety, x-sort-families, x-sort-descriptions, x-filter-list, x-filter-families). For serving the document,
the config, and the UI, see the Symfony bundle's OpenAPI docs.
The projection model¶
The projection is a small pipeline of pure classes in
haddowg\JsonApi\OpenApi, composed from the leaf up:
-
Schema— an immutable JSON Schema 2020-12 node, the dialect an OpenAPI 3.1 Schema Object speaks. Built fluently from typed withers (Schema::ofType('string') ->withEnum([…]),Schema::ref('#/components/schemas/…'),Schema::never()for the booleanfalseschema), it knows nothing about resources or fields. Vendor extensions (x-…) are first-class, so the projector can attachx-enum-varnamesand friends. The rest of the VO model (OpenApi,Components,PathItem,Operation,Parameter,RequestBody,Response,Tag,SecurityScheme, …) mirrors the OAS 3.1 object set the same way. -
SchemaProjector— maps a field and its declared constraints to aSchema. A structural constraint self-describes its keyword viaProvidesJsonSchema, so the projector shares one constraint→keyword source of truth with the body-validationSchemaCompiler(rather than mirroring it) — but emits a standalone, OpenAPI-shaped schema on top:description/examples, full nullable handling, enum var-names, and the complete attributes / resource-object shapes. A constraint that has no faithful JSON Schema 2020-12 keyword (aWhenwith an opaque condition,CompareField, a date/time bound fromAfter/Before/Between) is never emitted as a wrong keyword; instead a human-readable note is appended to the schemadescription. The same rule governs a date/time field's ownformatkeyword. This lossy-by-design degradation keeps the document honest. -
OperationProjector— projects one type's HTTP surface intoPathItems: the resource-levelGET/POSTon/{uriType}andGET/PATCH/DELETEon/{uriType}/{id}(honouring the per-type operation allow-list), each relation's exposed related and relationship endpoints, and its custom actions under the-actionssegment. Each operation enumerates its concrete query parameters (filter[…],sort,include,fields[…],page[…],withCount,relatedQuery), its request body, its declared success responses (see Response declarations) and a$refper standard error status, and carries its tags and per-operation security. -
ErrorCatalogProjector— groups the server's error codes into one named shape per status,sourcemember andmetadeclaration, each code aconstbranch of its shape, and theanyOfthat offers the shapes fromErrorDocument.errors.items. See The error-code catalogue. -
ErrorResponseProjector— projects thecomponents.responsesentry every operation's error$refs resolve to, one per advertised status, each pointing at the narrowest error document the catalogue supports, and names the error document an operation raising scoped codes answers with instead. See The shared error responses and Scoping a code. -
OpenApiProjector— the top-level entry point. It consumes aServerMetadataInterfaceand returns oneOpenApidocument: the skeleton (openapi/info/servers/tags/ security schemes), the full component set (per-type attributes, resource object, resource identifier, create/update request schemas, per-relationship relationship objects, and the single / collection / relationship / related document envelopes, and a type's own links component when it has named links), the shared components (JsonApi,Meta,LinkObject,RenderedLink,Links, the per-context links components,Error,ErrorDocumentand its per-status narrowings), the per-code error variants, the shared error responses, the named enum components, the optional Atomic Operations extension components + path, and — via theOperationProjector— thepaths.
Component names follow stable PascalCase conventions (blog-post → BlogPost, so
BlogPostResource, BlogPostCreateRequest, BlogPostAuthorRelationship, …), shared
between the schema and path projections so every $ref resolves. The document is
projected once per server: a multi-server API produces one document per server, each
built from that server's registered types.
Which types a document describes¶
A server's document describes the types registered on that server, and a resource object
is the shape claim that only a registration can back. So a relation that exposes its
related endpoint must point at a type this server registers. GET /favorites/{id}/user
returns a users resource object as primary data, and with users unregistered here
there is no field inventory to describe one.
The projector refuses that configuration rather than publishing a guess:
haddowg\JsonApi\OpenApi\RelatedTypeNotRegistered
Relation "user" on type "favorites" exposes its related endpoint to type "users",
which is not registered on server "Music Catalog API". …
Three ways out, all of them honest:
- register the type on this server — it then projects from its own fields;
- point the relation at a type that is registered — a reduced second type
(
public-profilesbeside a fullusers) where the real one belongs elsewhere; - call
->withoutRelatedEndpoint()— linkage-only, which needs no shape at all.
That last case is fully supported and unchanged. A related type reached only as linkage
gets a <RelatedType>ResourceIdentifier and no resource object, registered or not: an
identifier is {type, id} and asserts nothing about the resource behind it.
Two servers describing the same JSON:API type differently is a different thing
entirely, and stays supported — a v2 server serving a reshaped users beside v1 is the
versioning pattern, and each document states a shape its own server honours.
ProjectedTypes is the accessor for the described set:
use haddowg\JsonApi\OpenApi\ProjectedTypes;
ProjectedTypes::registered($server); // ['favorites'] — projected from their own fields
ProjectedTypes::relatedOnly($server); // [] — non-empty means project() refuses
ProjectedTypes::forServer($server); // ['favorites']
A framework integration emits a second artifact from the same metadata — the per-type JSON
Schema bundle served at /schemas.json — and keys it from forServer(), so the two
artifacts describe one agreed type set. relatedOnly() is the diagnostic: read it to fail
a build before the export runs.
What the schemas capture¶
The projection is faithful to the runtime the server actually serves, not a rough sketch:
- Context-correct attributes. A field's visibility and its
requiredset differ by representation, so the read, create and update shapes are distinct components (<Type>Attributes,<Type>CreateAttributes,<Type>UpdateAttributes). A read-only field isreadOnly: true; a create-required one appears in the create shape'srequiredbut not the update shape's (an absent update member means "no change"). When a create must send an attribute, the create request and the atomicaddalso require the resource object'sattributesmember. The create/update components are emitted only when the type's operation allow-list exposes that write, so a read-only type dangles no write components. A type a custom action takes as its JSON:API request document is the exception: the action reads it in a create context, so the type gets<Type>CreateAttributesand<Type>CreateRequestwhether or not it exposes create. - Closed objects. Every attributes component and every nested object a field declares
(
Map,Obj, eachOneOfbranch, a structured list's element) carriesadditionalProperties: false, so a member the type does not declare is rejected rather than silently dropped. A nested object aserializeUsing()hook renders stays open on a read, since that hook's return value goes out as it is. AnextractUsing()orcomputedUsing()hook only supplies the value, which then renders through the declared shape, so the read schema is the one the field has with no hook: closed, with an undeclared key dropped from the response. AfillUsing()/deserializeUsing()hook only changes how a write is stored, so the write schema keeps the declared shape, open members and counts, and the server validates the value against it. A standalone serializer with no field inventory keeps an open attributes object. - Open objects. An
ObjdeclaringadditionalProperties()projects that field's schema as itsadditionalProperties, built exactly as the field would project as a child, beside its declaredproperties, with itsminProperties()/maxProperties()asminProperties/maxProperties. The members follow a child's representation rules: a read-only member field closes the object on a write, a write-only one on a read.SchemaCompilerkeeps read-only members as accepted ones, as it keeps a read-only child. A document holding an open object declares theOPEN_OBJECTScontract tier in itsx-generatorstamp. - Unions. A
Unionprojects one schema whosetypelists its members' JSON types, with each member's type-scoped keywords beside it, or aoneOfof the members' schemas once a member carriesenum,const, a$refor another keyword not scoped to its type. A nullable union addsnullto thetypelist, or anullbranch to theoneOf. A document holding a union declares theUNIONScontract tier in itsx-generatorstamp. - Named shapes. An
Obj,OneOf,Union,MaporArrayListdeclared withcomponent()projects its shape once as#/components/schemas/<Name>, and each field using it is a$refthere. The response shape takes the bare name. A create or update shape that differs from it, through a read-only or write-only member, a member required only on create, a context-scoped constraint or an update that merges, is<Name>Createor<Name>Update, the convention<Type>Attributesfollows; one that doesn't shares the bare name. Each use keeps its description, deprecation, example and the non-empty keyword of itsrequired()beside the$ref, and a use that admitsnullis theanyOfof the$refand{"type": "null"}, so the component itself never admitsnull. Each use also carries the component'stype, withnulladded when it admitsnull, exactly as the inline shape would (see typed references). Two fields claiming one name with different shapes, or a name the document already generates, fail the projection. A document holding a named shape declares theNAMED_COMPONENTScontract tier in itsx-generatorstamp. - Read-only children. A nested object's child that is read-only for a write is left
out of that write's shape, as a read-only attribute is, in a
Map, anObj, eachOneOfbranch and a structured list's element. A child read-only only by awhen:predicate stays. The request validatorSchemaCompilerbuilds from the same projection but keeps such a child as an optional member, because hydration ignores it rather than rejecting it, so a client echoing a fetched value back still validates. - Id policy. A create request
$refs the create attributes and shapesidaccording to the type's client-id policy: forbidden (afalseschema) when the server assigns it, permitted when a client id is allowed, required when it is mandatory — so a client generated from the spec can never send anidthe runtime would reject. - Relationships. Each declared relation gets a relationship-object component with its
linkage
data(a single nullable identifier for a to-one, an array for a to-many; a polymorphic relation's identifier is aoneOfof its members with atypediscriminator, even when it has only one, see polymorphic relations). A write request lists only the relations settable in that write: a create leaves out a relation that isreadOnly()orreadOnlyOnCreate(), and an update one whose replacement is refused. A relation read-only only by awhen:predicate stays listed, as such an attribute does. The request example follows the same rule. A write request marks a write-only relation's propertywriteOnly: true, so a generator can keep it on its input types and off its read types. A to-many relation'sminItems()/maxItems()bound the linkage array of every write that sets the whole membership: the create and update requests, the atomicaddandupdateresource objects, and thePATCHthat replaces the relationship. Each takes the bounds declared for its context, beside the shared relationship object in anallOf, since that object is the read shape too. ThePOSTandDELETEthat add and remove members carry a delta, so they take none. A request example whose one member falls outside the bounds is left out. A relation required on create is listed in the create request's and the atomicadd'srelationships.required, andrelationshipsis then required of the resource object too. A required to-many takesminItems: 1in each write it is required in, as a required list attribute does, and a required to-one refusesnullthere unless it is alsonullable(). Where the write references the shared relationship object, the narrowing sits beside the reference in anallOf, with the reference first. Endpoints are emitted per relation, gated by its endpoint-exposure and mutation flags — and a mutating verb on/{type}/{id}/relationships/{rel}additionally needs the parent type's allow-list to exposeUpdate, since that is what it is. A read-only type's relation flags never open one. A relation's paths use its URI field name, the segment its links and routes use, sowithUriFieldName('by')documents/{type}/{id}/by. - Linkage a parent always renders. A relationship object may carry only its
links: a lazy to-many that isn't loaded or included renders nodata. A to-many's<Type><Rel>Relationshiplistsdatainrequiredwhen a parent's document renders the linkage every time it renders the relationship, so a generated client can type those members as present. That holds for a relation declaredwithData()and for aMorphToManyidentified byidentifiedBy()oridentifiedByRows(), when the adapter declares throughDeclaresRelationDataWithholdingthat no caller can be refused the relation's data, since a refused relationship keeps itslinksand dropsdata. It holds too for a to-many declaredwithoutLinks(), which never defers its linkage and is left out whole when refused. AqueriedBy()relation never rendersdataon a parent, and a to-one is left as it is. A sparse fieldset or ahidden(when:)predicate drops the whole member, which the requirement doesn't cover. The projector reads these facts from the relation's definition among the type's fields, so a relation with no definition requires nothing. The object is shared with the write bodies, where JSON:API requiresdataanyway. A document with such an object declares theRENDERED_LINKAGEcontract tier in itsx-generatorstamp. - Pivot data, per direction. A
belongsToManyrelation's linkage identifiers type theirmeta.pivotwith one of two components.<Type><Rel>Pivotis what a response renders: every pivot field except a write-only one, eachrequiredunless its read visibility is request-conditional, andnulladmitted unless the value is guaranteed, as for an attribute.<Type><Rel>WritePivotis what a request may send: only the fields a write can set, with the ones every attach must supply inrequired. The response linkage reaches the first through<Type><Rel>Relationshipand<Type><Rel>RelationshipDocument; the create, update and atomic bodies reach the second through<Type><Rel>WriteRelationship, and the relationshipPATCH/POST/DELETEbodies through<Type><Rel>RelationshipRequest. Both are closed withadditionalProperties: false, unless anAdditionalPropertiesentry among the pivot fields opens them, to any value or to the schema of itsof()field. A host rendersmeta.pivoton every member of the response linkage,{}when the request hides every pivot field, so each response identifier listsmetainrequiredand itsmetalistspivot. A request identifier may leave both out. - Declared identifier meta. A relation whose
identifierMeta()declares its members (fields:) gets a<Type><Rel>IdentifierMetacomponent, projected under the read rules<Type><Rel>Pivotfollows, and each response linkage identifier'smetareferences it. The object is closed unless anAdditionalPropertiesentry opens it. With a pivot too,pivotis one of its required properties, referencing<Type><Rel>Pivot. A polymorphic relation narrows its whole identifier union the same way. Requests never carry these members: they are read-only. A relation that declares none keeps an openmeta. - Links, per context. Each place a link renders has one shared component listing the
members the server can put there:
ResourceLinks,DocumentLinks,CollectionLinks,RelationshipLinks,RelationshipDocumentLinksandRelatedDocumentLinks. A type whose resources carry declared links or action links gets its own<Type>ResourceLinks, extendingResourceLinkswith them. See links anddescribedby. - A typed
included. A compound document'sincludedis an array whose items are aoneOfover the<Type>Resourceof every type its?includepaths reach, with atypediscriminator mapping each type to its component. The reach is the one the operation'sincludeenum andfields[<type>]parameters use: every type a listed path ends at, walked through the relation graph and through each member of a polymorphic segment, leaving out a type the server does not register. A related endpoint'sincludedis rooted at the related type. A document whose paths reach nothing has noincludedmember. - Atomic operations by kind. With the Atomic Operations
extension on,
AtomicOperationis aoneOfover one component per kind:AtomicAddOperation,AtomicUpdateOperationandAtomicRemoveOperationfor a resource, andAtomicRelationshipAddOperation,AtomicRelationshipUpdateOperationandAtomicRelationshipRemoveOperationfor a relationship. Each pins itsopas aconst, and a relationship kind needs a target that names the relationship, arefwithrelationshipor anhrefending inrelationships/<name>, which a resource kind refuses, so a valid operation matches exactly one kind. An add or update carries aoneOfover<Type>AtomicAddor<Type>AtomicUpdate, discriminated bytype. A relationship kind referencesAtomicIdentifier, theoneOfover each<Type>AtomicIdentifierdiscriminated bytype, orAtomicIdentifiers, its array: the update takes an identifier,nullor the array, and the add and remove take the array. Each<Type>AtomicIdentifiertakes anidor alid. A type the server gains adds a branch toAtomicIdentifierand leaves the operations unchanged, and the union keeps itsoneOfand discriminator when the relations link to a single type. The relationships inside an add or update carry the same identifiers, so they can link a resource an earlier operation created. AnAtomicResult'sdatais theanyOfof the returned resource, discriminated over<Type>Resource, and the returned linkage, discriminated over<Type>ResourceIdentifier, since a resource with no attributes is also an identifier. A relation that types its identifiers'meta, with pivot fields or declared identifier meta, adds its own branch instead: the linkage its relationship endpoint returns, so a pivot relation's members requiremeta.pivotthere too. A result does not name the operation that produced it, so each such relation is one more branch of theanyOf, emitted when one of its relationship operations can run. A type that only those relations link to is left out of the shared identifier union. - Pagination, filters, sorts, includes. A collection
GETadvertises itspage[…]parameters (per the resolved paginator kind), its declaredfilter[…]value schemas, itssortkeys (and the patterns of its sort families), andinclude— the last only when the type actually exposes an includable path, so?includeis never advertised where the runtime would reject it. A to-many relation that declares a default read order gives thesortparameter of its relationship and related endpoints that order as the schema'sdefault, such as["position", "-title"]. Metadata reports it throughDeclaresRelationDefaultSort. Everysortparameter carries anexample, the sort example, and tables its described keys. A filter's declared default is itsfilter[<key>]schema'sdefault. ?include/fields[…]on writes. These two shape the rendered document, not the query that selects it, so they belong to every operation that answers with a resource document — aPOSTcreate and aPATCHupdate as much as aGET, with the identical allowed-value enums, because the legal paths and members are a property of the type. A write that returns no such document takes neither: a204create or update, a delete (204or a meta-only200), and a relationship-endpoint mutation, whose echoed document is linkage and carries noincludedhowever the request is spelled. A custom action follows its declared body: one answering with a named type's document advertises that type's pair, even when it is mounted on another.- Filter values that carry a type. A
filter[<key>]gets its container shape from the filter kind — a set is an array, a range amin/maxobject, a presence-only filter a plain string whose description ends "Applied when present; value ignored." and whose example istrue— and its value schema from the filter's declared value constraints. A filter that declared none falls back to the JSON type of the field it targets, matching the filter's column against the type's field inventory: aWhereover anIntegerdocuments as{"type": "integer"}where it used to document as{}. Only the type carries over — not the field'sformat,enumor length, which describe a document member rather than a comparison operand. Where the column resolves to no single scalar field — a relationship path, a group spanning several columns, a computed value, a composite — the value isstring, which is what a query parameter is on the wire regardless. - Dates and times that mean it.
format: date-time,dateandtimeare RFC 3339 productions, so aDateTime/Date/Timefield gets one only when its configured serialization format really writes that shape. A field that writes anything else is documented as a plainstringand its shape is given by example in thedescription, so a generated client never coerces on a keyword the server does not honour. Note thatTime'sH:i:sdefault carries no offset and so is not an RFC 3339full-time. - Constraints, per representation. Every built-in constraint with a JSON Schema
keyword projects it:
minimum/maximum/exclusiveMinimum/exclusiveMaximum/multipleOf,minLength/maxLength/pattern,minItems/maxItems/uniqueItems,minProperties/maxProperties,enum,not, and theemail/uri/uuid/ipv4/ipv6formats. Which schema carries a keyword follows the context it is enforced in. The create shape takes the constraints that apply on create, and the update shape those that apply on update. The read shape takes a constraint only when every write that can set the field enforces it, so a create-onlymaxLength(280)on a field an update can also write narrows the create shape and nothing else. A field only a create can write (readOnlyOnUpdate()) keeps its create-only bounds on read.nullgoes the other way: the read shape admits it when any write that can set the field does. A filter value takes every constraint the filter declares, whatever its context, because the filter validator runs them all. nullon read only when it can happen. A response attribute admitsnullunless the server guarantees a value, because an optional member a create left out renders asnull. A value is guaranteed when every create had to supply it (required()orrequiredOnCreate()on a field a create can write, and no write declaresnullable()), when the closure producing it declares a non-null return type, or when the field declaresguaranteed(). A read-only field and anon()value admitnulluntil asserted, and a field no write can set admits it whenever it declaresnullable(), guaranteed or not. A nullable enum addsnullto itsenumlist, or unions its$refwith{"type": "null"}and addsnullto thetypebeside it; a nullableOneOfgains anullbranch. Any other keyword that applies whatever the type and thatnullcould fail, aShapeoneOfwhose members carry no type, anallOf, anotother thannotIn()'s or aconst, moves into ananyOfbeside{"type": "null"}, adiscriminatormoving with itsoneOf, the way the compiled validation schema admits it.ObjandMapchildren, list elements' members andOneOfvariants' members follow the same rule, each written only by the writes that can set the value around it, and the resourceidis never null. So a client can trust a read type withoutnull: that member always carries a value.- Presence is a separate promise. The read shape's
requiredlists every attribute a response withoutfields[<type>]always carries,nullor not. Ahidden(when:)orwriteOnly(when:)member and asparseByDefault()one are left out, since a response can omit them. A sparse fieldset can omit any member, so a client that sends one narrows the type itself. The rule recurses intoMap,ObjandOneOfvalues: a nested object lists every child it renders, leaving out a write-only child (absent from the readpropertiestoo) and ahidden(when:)/writeOnly(when:)one, and a discriminatedOneOfbranch also requires its discriminator. AnextractUsing()orcomputedUsing()value renders through those children like a stored one, so the same rule holds for it. A nested object whoseserializeUsing()hook builds the value lists none, and aOneOfwith such a hook stops requiring its discriminator, since the hook decides its shape. Itspropertiesare still projected from the declared children, but the hook's return value goes out as it is, so keep it to the declared shape or the response won't match the documented one. A nullable nested object can still benull; when it is present, its required children are there. required()means non-empty too. ARequiredfield must be present on create and may never be empty, so a required string carriesminLength: 1, a required listminItems: 1and a requiredArrayHash/Map/ObjminProperties: 1, in each shape theRequiredapplies to (a larger declared minimum is kept). A required number or boolean gains nothing.- Conditional rules stay out of the keywords. A constraint inside
when()holds only for the requests its condition admits, so none of its keywords project. The schema gets a note in itsdescriptioninstead. A conditionalnullable()does widen the type to admitnull, since some requests may send it. AnIpthat accepts either family has noformat, becauseipv4alone would reject its IPv6 addresses. AnanyOffromatLeastOneOf()keeps every alternative whatever its context, since dropping one would reject values the server accepts. - Repeated constraints all hold. Every
each()that applies to a write adds to the list'sitems, whether declared directly or insidesequentially(): theirin()values intersect, the first backed enum among them owns the reference, and their other keywords merge. A secondnotIn()adds its values to the first one'snot, and a secondatLeastOneOf()orShapejoins anallOfbeside the first one's combinator. A bound declared twice keeps the stricter one, sominLength(5)->minLength(2)documentsminLength: 5, and the same goes formin(),max(), the exclusive bounds and the length, item and property counts. Two integermultipleOf()values become their least common multiple; any other pair, and a secondpattern()orformat, joins theallOfbeside the first. A write narrows only its own schema, so anonUpdate()maxLength()tightens updates and leaves reads and creates alone. The compiled validation schema follows the same rules. A value holding such a condition in itsallOf, two ofoneOf,anyOfandallOf, or an enum reference sharing itsallOfwith another condition raises the document'sx-generatorstamp, since a generator reading only the first condition accepts values the server refuses. So does a nullable value whoseoneOf,notorconstmoves beside anullbranch.
Nested fieldsets¶
A fields[<type>] parameter's items are the enum of the type's members. When the type has
an attribute declaring a nested fieldset, the items become
an anyOf of that enum and one string pattern per path a member may select:
<attribute>.<key> for each such attribute, <attribute>.<key>.<key> for each object
inside it that declares a nested fieldset too, at any depth, and <attribute>.* and
<attribute>.*.<key> for a list whose element declares them, and for a OneOf, wherever
it sits, the paths of every variant that declares them:
"items": {
"anyOf": [
{ "type": "string", "enum": ["name", "address", "totals", "lines"] },
{ "type": "string", "pattern": "^address\\.(?:[a-z]+)$" },
{ "type": "string", "pattern": "^address\\.geo\\.(?:lat|lng)$" },
{ "type": "string", "pattern": "^totals\\.[^.,*]+$" },
{ "type": "string", "pattern": "^lines\\.\\*$" },
{ "type": "string", "pattern": "^lines\\.\\*\\.(?:sku|quantity|price)$" },
{ "type": "string", "pattern": "^lines\\.\\*\\.price\\.(?:amount|currency)$" }
]
}
Each pattern wraps the declared key pattern of its last object. A nested object reached
through a declared child names that child, so geo appears literally, and one reached
through the members of an open object repeats the open object's key pattern. A list's own
pattern ends in a literal \.\*, as a key pattern does for an object, and selects every
item whole, the same as listing the list; its element's paths follow that segment. A child the parent's
pattern doesn't match, or one that never renders, adds no pattern, nor does a list whose
element declares no nested fieldset. An object declaring only a predicate can't say which
keys it takes, so its pattern admits any key up to the next ., comma or *, and the
server still rejects one the predicate refuses. The parameter's description names the
attributes and the lists and the Nested Fieldsets profile,
which the server applies to a narrowed response, and mentions nested keys and nested
lists when the type has any. The JsonApi component
lists the profile with the others when the server registers it. The attribute's own schema
is unchanged. A document with such a parameter declares the NESTED_FIELDSETS contract tier
in its x-generator stamp.
Polymorphic relations with one type¶
A MorphTo or MorphToMany is projected as a union of its member types even when it
declares only one. MorphTo::make('subject', ['people']) gets the same shape a
MorphTo over two types gets, with one member, where a BelongsTo to people gets a
plain $ref:
- its linkage identifier is
{"oneOf": [{"$ref": "#/components/schemas/PeopleResourceIdentifier"}], "discriminator": {"propertyName": "type", "mapping": {"people": "#/components/schemas/PeopleResourceIdentifier"}}}, in the relationship object, the relationship document and the write bodies; - the
dataof its related document or related collection is the sameoneOfover the member resources, its discriminator mapping each type to its<Type>Resource; - its related and relationship endpoints take no
filter,sortorpageparameters from the related type. Its related?withCountoffers every relation that any of its related types counts, since each member renders its own total (counting on a mixed-type response). A relation's own filters and sorts, and thefields[<type>]parameters, are unchanged.
A MorphToMany declared with identifiedByRows() or identifiedBy()
is the one exception, projected the same whichever it uses: its relationship endpoint pages its stored pairs, so it takes the
same page and withCount parameters as its related endpoint. With
pivot fields on its link rows, both its
endpoints also take the filter[<key>] and sort parameters of the relation's own
filters and sorts, which metadata reports as the pivot ones, and its linkage identifiers
type meta.pivot with the <Type><Rel>Pivot and <Type><Rel>WritePivot components a
BelongsToMany gets, joined to the member union by an allOf. A document holding such a
relation declares the IDENTIFIED_PIVOTS contract tier. Metadata says the relation
is identified through DeclaresIdentifiedMembers; metadata that doesn't implement it
projects the endpoint with no parameters.
A relation declared with queriedBy()
projects the same endpoint, its filter[<key>] and sort parameters being every filter and
sort the relation declares, which metadata reports from filters() and sorts(). Its
relationship object in a parent's document carries no example and says that it renders no
data, and a parent's example document shows its links only. Its relationship and related reads carry
x-mcp: {"parentLinkage": false}. Metadata says so
through DeclaresQueriedMembers.
So a generated client already types the relation as polymorphic, and adding a second type
later adds a member rather than changing every input that carries the relation. The
projector learns that a relation is polymorphic from DeclaresPolymorphicRelation on its
metadata; metadata that doesn't implement it decides by the
number of types, as before.
The error-code catalogue¶
Every typed exception core raises carries a stable code, a
fixed HTTP status, a default title and, usually, a known source member. The projection
groups the codes into shapes: the codes at one status that fill the same source
member and declare the same meta share one schema component, and each code is a const
branch of that component's code. A generated client still offers a typed exception per
code, and a new code usually adds one branch rather than a component:
components:
schemas:
Error400Parameter:
title: A 400 error caused by a query parameter
description: A `400` error. Its `code` is one of the branches below, … `source.parameter` names the query parameter at fault.
allOf:
- $ref: '#/components/schemas/Error'
- type: object
properties:
code:
anyOf:
- type: string
const: FIELDSET_MEMBER_UNRECOGNIZED
title: Fieldset member is unrecognized
description: A `fields[TYPE]` parameter names a member that type does not have. Request only the attributes and relationships the type declares.
- type: string
const: QUERY_PARAM_UNRECOGNIZED
title: Query parameter is unrecognized
description: …
- …
status: { type: string, const: '400' }
source: { type: object, required: [parameter] }
required: [code, status, source]
A shape narrows the shared Error rather than restating it, so the member vocabulary
lives in one place. code and status are pinned, the code to one of its branches and the
status to a const: they are the machine and HTTP contract and no
message resolver can change
them. title stays a plain string, because a resolver replaces it per locale; core's
default is the title annotation on the code's branch. source names the member every code
in the shape always fills, so a client can read source.parameter without a null check on
the codes that guarantee it. The code is an anyOf even when the shape holds one code, so
adding a code is always one more branch.
A shape is named for its status, then its source member, then, when it declares meta or
only some operations offer it, its first code: Error400Parameter, Error406Header,
Error404ResourceNotFound, Error403InsufficientScope, Error400ParameterCursorMalformed.
Each branch's description says what its code means and what a client should do about it,
which a generator can carry onto the typed exception it emits. Every code core ships has a
description; your own codes get one from the
descriptor, and a code
without one projects its branch without it. A code's example detail, source and meta
are in its entry of the error responses' examples, not on the schema.
Meta. A code whose descriptor declares its meta
gets a closed meta object built from those members, with the same field builders and the
same projection an attribute uses. meta is required when a member is declared required()
and optional otherwise. INSUFFICIENT_SCOPE shows both kinds:
Error403InsufficientScope:
title: Insufficient scope
allOf:
- $ref: '#/components/schemas/Error'
- type: object
properties:
code: { anyOf: [ { type: string, const: INSUFFICIENT_SCOPE, title: Insufficient scope, description: … } ] }
status: { type: string, const: '403' }
meta:
type: object
properties:
requiredScopes: { type: array, items: { type: string }, description: Every scope the request needs. }
missingScopes: { type: array, items: { type: string }, description: The required scopes the access token does not grant. }
include: { type: string, description: … }
required: [requiredScopes, missingScopes]
additionalProperties: false
required: [code, status, meta]
What a shape does not carry is the error's interpolation context. The
{placeholder} tokens core fills into title and detail are resolved before the
response leaves, so the context itself never reaches a client. Describing its shape in a
document a client reads would describe something it can never receive. Those tokens are a
PHP-side API and live on the
descriptor, where whoever
writes a replacement template is already working.
ErrorDocument.errors.items then offers the catalogue:
items:
anyOf:
- $ref: '#/components/schemas/Error' # the open branch
- $ref: '#/components/schemas/Error400Parameter'
- …
The first branch is the generic Error, and it is load-bearing. Your application
throws error codes this projection has never heard of, and a closed oneOf would make
those documents fail your own published schema. The anyOf is a catalogue, not a
constraint: it constrains nothing, and that is the point. A generator reads the named
shapes for the codes it can type and falls back to a status-based exception, raw code
intact, for anything else.
The catalogue is registration-aware, like the rest of the document: a code that depends
on a capability your server does not offer is left out entirely. The atomic and local-id
codes need the Atomic Operations extension; CURSOR_MALFORMED /
CURSOR_STALE need a cursor-paginated collection; PAGINATION_KIND_UNKNOWN needs a
MultiPaginator menu; RELATIONSHIP_COUNT_NOT_ALLOWED needs the Countable profile;
the client-id codes need a type that permits one; and the whole request-document family
(bad JSON, missing data, an unacceptable type, …) needs a server that accepts a
request body somewhere — a CRUD write, a mutable relationship endpoint, an action taking a
document, or the atomic batch.
Past that gate, each of core's codes is offered only on the operations whose runtime can
raise it, the way a scoped code is.
What a type, relation or action declares narrows that further, and a code no operation can
raise is left out, such as FILTER_VALUE_INVALID on a server that declares no filter:
| Codes | Offered on |
|---|---|
QUERY_PARAM_UNRECOGNIZED, QUERY_PARAM_MALFORMED, MEDIA_TYPE_UNACCEPTABLE, MEDIA_TYPE_UNSUPPORTED, METHOD_NOT_ALLOWED, APPLICATION_ERROR and NO_RESOURCE_REGISTERED |
every operation |
ACCESS_DENIED, AUTHENTICATION_REQUIRED |
the operations the adapter says its security layer can refuse, and the batch when it can be refused or runs a write that can; every operation when it does not say |
FIELDSET_MEMBER_UNRECOGNIZED |
every operation, on a strict server with a type declaring its fields |
RESPONSE_BODY_INVALID_JSON, RESPONSE_BODY_INVALID_JSON_API |
every operation, on a server that validates its responses |
SORTING_UNSUPPORTED |
a collection read, or a to-many's related or relationship read, whose sort vocabulary is empty |
SORTING_UNRECOGNIZED |
a collection read, or a to-many's related or relationship read, that declares a sort |
FILTERING_UNRECOGNIZED |
a collection read, a related or relationship read, and a collection action that takes filters |
FILTER_VALUE_INVALID |
those of the reads and actions above that declare a filter |
| the four above, with the Relationship Queries profile | also every operation documenting relatedQuery, by the vocabulary of the relations it addresses: SORTING_UNSUPPORTED where an addressed to-many sorts by nothing, SORTING_UNRECOGNIZED where one sorts by something, FILTERING_UNRECOGNIZED always, and FILTER_VALUE_INVALID where an addressed relation declares a filter |
INCLUSION_UNRECOGNIZED |
a collection or single read, a create, an update, a related or relationship read, a relationship mutation echoing its linkage, an action answering with a resource, and the atomic batch |
INCLUSION_UNSUPPORTED |
only the operations whose type declares that its handler refuses include |
INCLUSION_NOT_ALLOWED |
the same operations as INCLUSION_UNRECOGNIZED, where the document's root has an allow-list or excluded paths, or the include tree reaches a relation that cannot be included or is gated by cannotBeIncluded(when:) |
INCLUSION_DEPTH_EXCEEDED |
the same operations, where the root's maximum include depth, its own or else the server's, is set |
RELATIONSHIP_COUNT_NOT_ALLOWED |
every operation rendering a document: the reads, a create or update answering with its resource, a relationship mutation echoing its linkage, an action answering with a resource, and the atomic batch |
CURSOR_MALFORMED, CURSOR_STALE |
a collection read, or a to-many's related or relationship read, whose page pages by cursor, bare or as a menu arm |
PAGINATION_KIND_UNKNOWN |
the reads whose page is a MultiPaginator menu |
INSUFFICIENT_SCOPE |
an operation needing scopes of its own, a read, create, update or related read with a path to include, and the batch when it or a write it runs needs scopes |
RESOURCE_NOT_FOUND |
every operation addressing a resource, a create of a type with a relation it may set whose linkage can name a missing resource, and an action on a resource or taking a document; never a collection read |
RELATIONSHIP_NOT_EXISTS |
the relationship mutations, and the related and relationship reads of a relation that a hidden(when:) or writeOnly(when:) predicate can hide, or, on the relationship read, that renders only when fields[<type>] names it |
REQUEST_BODY_INVALID_JSON |
a create, an update, a relationship mutation, an action taking a document, and the atomic batch |
REQUEST_BODY_INVALID_JSON_API |
the same on a server validating request documents; otherwise only a create or update, and the batch, on a server checking a resource object's members |
REQUIRED_TOP_LEVEL_MEMBERS_MISSING, TOP_LEVEL_MEMBERS_INCOMPATIBLE, TOP_LEVEL_MEMBER_NOT_ALLOWED, LOCAL_ID_NOT_SUPPORTED |
the same, except the atomic batch |
DATA_MEMBER_MISSING, RESOURCE_TYPE_MISSING, RESOURCE_ID_INVALID, ATTRIBUTE_MEMBER_UNRECOGNIZED |
a create, an update, and an action taking a document |
RESOURCE_TYPE_UNACCEPTABLE |
the same, and a relationship mutation |
the RESOURCE_IDENTIFIER_* codes |
a relationship mutation, and a create, update or document action whose type declares a relation |
RELATIONSHIP_TYPE_INAPPROPRIATE |
a relationship mutation, and a write of a type with no field inventory whose hydrator checks cardinality |
ATTRIBUTE_VALUE_INVALID |
a create, an update, an action taking a document, and a mutation of a relation with pivot fields |
ATTRIBUTE_WRITE_PROHIBITED |
a create, an update, and an action taking a document, of a type declaring an attribute that is read-only for that write, unconditionally or by a readOnly(when:) predicate |
RELATED_ATTRIBUTE_OWNER_MISSING |
the same, of a type with an attribute flattened on() a relation |
RESOURCE_ID_MISSING |
an update |
RESOURCE_ID_CONFLICT |
an update, but not inside the atomic batch |
CLIENT_GENERATED_ID_NOT_SUPPORTED |
the create of a type that refuses a client id, and an action whose document input is such a type |
CLIENT_GENERATED_ID_REQUIRED |
the create of a type that requires a client id, and such an action |
CLIENT_GENERATED_ID_ALREADY_EXISTS |
the create of a type that permits a client id and whose data layer detects a taken one, and such an action |
RESOURCE_ID_UNDECODABLE |
the create of a type that permits a client id and encodes its ids, and such an action |
FULL_REPLACEMENT_PROHIBITED |
a relationship replacement the relation does not always allow or whose data layer can refuse to detach a member, and the update of a type with such a data-layer refusal |
ADDITION_PROHIBITED |
a relationship addition the relation does not always allow |
REMOVAL_PROHIBITED |
a relationship removal, or the replacement of a to-one, which null clears, that the relation does not always allow or whose data layer can refuse, and the update of a type with a to-one the data layer can refuse to clear |
MEMBERSHIP_CHANGE_PROHIBITED |
the relationship replacement of a relation declared cannotChangeMembership(), and the update of its type |
| the atomic and local-id codes | the atomic batch |
The batch offers a code when it can perform a write that does, since a batch entry runs that
write through the same handler, unless the batch skips that check: its document has no
top-level data, its entries may carry a lid, and nothing checks an entry's id against
its ref. It also offers ADDITION_PROHIBITED when a relation refuses additions outright,
since a batch entry can still target one. A code the batch raises itself, such as a
malformed body, is always offered there.
A delete, a single read, a write or a relationship mutation never reads sort or filter,
so those codes stay off them, and a cursor-paged collection leaves your deletes and
single-resource reads untouched.
Some of these facts core reads from your definitions, through the fields a type reports: a
readOnly(when:), hidden(when:) or writeOnly(when:) predicate, a relation's
cannotReplace(when:), cannotAdd(when:), cannotRemove(when:) or
cannotBeIncluded(when:), and whether the Id field has an encoder. The rest only an
adapter knows, and it says so through an opt-in interface on its metadata:
| Interface | On | Decides |
|---|---|---|
DeclaresOperationSecurity |
the server | ACCESS_DENIED and AUTHENTICATION_REQUIRED, per operation |
DeclaresStrictQueryParameters |
the server | FIELDSET_MEMBER_UNRECOGNIZED |
DeclaresDocumentValidation |
the server | REQUEST_BODY_INVALID_JSON_API and the RESPONSE_BODY_INVALID_* codes |
DeclaresMaxIncludeDepth |
the server | INCLUSION_DEPTH_EXCEEDED, for a root with no depth of its own |
DeclaresIncludeSafeguards |
a type | INCLUSION_NOT_ALLOWED and INCLUSION_DEPTH_EXCEEDED where it is the root |
DeclaresInclusionUnsupported |
a type | INCLUSION_UNSUPPORTED |
DeclaresClientIdCollisions |
a type | CLIENT_GENERATED_ID_ALREADY_EXISTS |
DeclaresHydratorCardinality |
a type with no field inventory | RELATIONSHIP_TYPE_INAPPROPRIATE on its writes |
DeclaresDetachmentRefusal |
a relation | FULL_REPLACEMENT_PROHIBITED and REMOVAL_PROHIBITED from the data layer |
DeclaresLinkageResolution |
a relation | RESOURCE_NOT_FOUND on a create |
Where neither tells, the code is offered, because a missing code hurts a client more than a
spare one: metadata implementing none of these documents what it did before, except
INCLUSION_UNSUPPORTED, which nothing raises unless a type declares it.
Each rule's codes form shapes of their own, so Error400ParameterCursorMalformed keeps
its name when another collection starts paging by cursor, and never takes in a code of
another rule that happens to reach the same operations. A status every operation shares
no code at still gets its ErrorDocument<status>, offering only the generic Error, for the
operations outside every scope at that status.
Scoping a code to the operations that raise it¶
Most codes can arrive on any operation, but an application's own codes are often endpoint
specific: a lock on an update, a payment check on one action. An error names the operations
it can arrive on with a scope on its descriptor:
use haddowg\JsonApi\Exception\ErrorScope;
new ErrorDescriptor(
code: 'ARTICLE_LOCKED',
status: 409,
title: 'Article locked',
scope: ErrorScope::on('articles', 'update', 'delete'),
);
ErrorScope::on() names operations of one type in the grammar operation examples and
scopes are keyed by (update, fetchRelated.author, action.publish.post), or every
operation of the type when it names none. ErrorScope::kinds() covers operations of a kind
on every type, for an error that is not one type's, and and() combines scopes. The Atomic
Operations endpoint offers a code whose scope names OperationKind::Atomic, and one whose
scope covers a create, update, delete or relationship write, since a batch entry runs that
write through the same handler. A code scoped to reads stays off the batch. For an
error you do not own, catalogue it through a ScopedErrorSource, whose scope replaces the
descriptor's, and for one of core's codes the operations its rule reaches:
A scoped code is catalogued like any other, in a shape of its own scope named after its first
code (Error409ArticleLocked), and only the operations it is declared for offer it. Each of
them answers the code's status with an error document of its own, offering the codes every
operation raises at that status plus its scoped ones, and gains that status if it did not
advertise it already. The rest keep the shared response. A name that is not an operation
name fails when the scope is built, and a scope naming a type the server does not register
covers nothing on it.
paths:
/articles/{id}:
patch:
responses:
'409':
description: Conflict — the request conflicts with the resource state (e.g. a type or id mismatch).
content:
application/vnd.api+json:
schema: { $ref: '#/components/schemas/ArticlesUpdate409' }
examples:
RESOURCE_TYPE_UNACCEPTABLE: { $ref: '#/components/examples/RESOURCE_TYPE_UNACCEPTABLE' }
ARTICLE_LOCKED: { $ref: '#/components/examples/ARTICLE_LOCKED' }
components:
schemas:
ArticlesUpdate409:
type: object
properties:
errors:
type: array
minItems: 1
items:
anyOf:
- { $ref: '#/components/schemas/Error' }
- { $ref: '#/components/schemas/Error409PointerResourceIdConflict' }
- { $ref: '#/components/schemas/Error409ArticleLocked' }
links: { $ref: '#/components/schemas/Links' }
meta: { $ref: '#/components/schemas/Meta' }
jsonapi: { $ref: '#/components/schemas/JsonApi' }
required: [errors]
The document is named for the operation and the status, never for the codes it offers, so a scoped code joining or leaving an operation changes what its document offers and leaves its name, and the type a generated client imports for it, alone. The name is the type's PascalCase base followed by the operation:
| Operation | Error document at 409 |
|---|---|
update of campaign-template-bindings |
CampaignTemplateBindingsUpdate409 |
fetchCollection, fetchOne, create, delete of articles |
ArticlesFetchCollection409, ArticlesFetchOne409, ArticlesCreate409, ArticlesDelete409 |
fetchRelated.author, updateRelationship.author of articles |
ArticlesAuthorFetchRelated409, ArticlesAuthorUpdateRelationship409 |
fetchRelationship.tags, addRelationship.tags, removeRelationship.tags of articles |
ArticlesTagsFetchRelationship409, ArticlesTagsAddRelationship409, ArticlesTagsRemoveRelationship409 |
the publish action of articles |
ArticlesPublishAction409 |
the POST of an export action answering GET and POST |
ArticlesExportActionPost409 |
| the Atomic Operations endpoint | AtomicOperations409 |
An action takes its method in the name only when it answers to several, as its operationId
does. A relation is named by its member name, as in its operationId. Two operations whose
names come out the same, or a name another component already holds, fail the projection
with an exception naming both, as any other clashing generated name does. Rename the type,
relation or action.
An operation's own document references the shared shapes, Error and the Links, Meta
and JsonApi members, and copies none of them. It carries no description: the explanation
of why the list stays open lives once, on the shared ErrorDocument<status>, and applies to
it unchanged. Its response sits inline in the operation, so there is one set of
per-operation names, the documents, and no response component beside each.
Each code's example is one components.examples entry, keyed by the code, which every
response offering the code references, so an operation's own response adds a reference per
code rather than a copy.
The shared error responses¶
An operation does not describe its error bodies. Unless it raises a scoped code at that
status, it $refs one of the shared responses under components.responses, named for the
HTTP status:
paths:
/articles/{id}:
get:
responses:
'200': { … }
'406': { $ref: '#/components/responses/NotAcceptable' }
components:
responses:
NotAcceptable:
description: Not Acceptable — the `Accept` header could not be satisfied.
content:
application/vnd.api+json:
schema: { $ref: '#/components/schemas/ErrorDocument406' }
One response component per status your server advertises — nothing more, in keeping with
the rest of the document. Each is named for its status's reason phrase (UnprocessableEntity,
PaymentRequired, TooManyRequests, …); a status without one is named Status<code>. An endpoint that phrases a status its own way keeps its wording
on the $ref as an OAS 3.1 Reference Object description, which overrides the
component's; the Atomic Operations batch does this for the six it
describes in terms of an operation within the batch rather than the request as a whole.
Each response carries the narrowest error document its status supports. Every
catalogued shape pins its status to a const, so ErrorDocument406 is the error document
whose errors.items.anyOf offers only the shapes whose codes can arrive with a 406 on any
operation — and the open generic Error still leads it. Since nearly every operation offers
400 and 404 codes of its own, those statuses usually answer with an operation's own
document, and a status no operation answers from a shared response has no component. A status the catalogue claims no
code for keeps the generic ErrorDocument, such as a status whose codes your feature set
gated out. 401 and 403 narrow like the rest: core catalogues AUTHENTICATION_REQUIRED
and ACCESS_DENIED for the adapters to render when the framework's security layer refuses a
request, so ErrorDocument401 offers the one and ErrorDocument403 offers the other. The
write-side 403 codes are the writes' own.
Two things follow, and the second is easy to miss. The anyOf is still a catalogue and
still not a constraint — your own 422 code validates against ErrorDocument422 for the
same reason it validates against ErrorDocument. And a document's status is the status
class its errors share: a response that collects a 422 and a 409 goes out as a 400
(errors and exceptions), so a 400
body can carry an error object whose own status member reads "422". The generic branch
absorbs that and validation passes. Read the per-status list as the codes that status
usually carries, not the codes it can only carry.
Adding your own codes to the catalogue. Implement DescribedErrorInterface on your
exception and build its errors through the descriptor:
use haddowg\JsonApi\Exception\AbstractJsonApiException;
use haddowg\JsonApi\Exception\DescribedErrorInterface;
use haddowg\JsonApi\Exception\ErrorContextType;
use haddowg\JsonApi\Exception\ErrorDescriptor;
use haddowg\JsonApi\Exception\ErrorSourceShape;
use haddowg\JsonApi\Schema\Error\ErrorSource;
final class SeatsSoldOut extends AbstractJsonApiException implements DescribedErrorInterface
{
public function __construct(public readonly string $performance)
{
parent::__construct("No seats remain for '$performance'.", self::describe()->status);
}
public static function describe(): ErrorDescriptor
{
return new ErrorDescriptor(
code: 'SEATS_SOLD_OUT',
status: 409,
title: 'Seats are sold out',
context: ['performance' => ErrorContextType::Str],
source: ErrorSourceShape::Pointer,
);
}
public function getErrors(): array
{
return [self::describe()->toError(
detail: "No seats remain for '{performance}'.",
context: ['performance' => $this->performance],
source: ErrorSource::fromPointer('/data/relationships/performance'),
)];
}
}
Then point the server at it. The catalogue is assembled from
sources: core's own
always, plus whatever the server's metadata contributes through ContributesErrorCodes.
Contribution is per server, so SEATS_SOLD_OUT is documented on the servers that can
raise it and nowhere else, and two classes claiming one code are refused rather than
silently merged. The Symfony and Laravel integrations wire a source from their own
discovery, so in those apps the exception above is catalogued by writing it.
Links and describedby¶
The server renders the links it builds as link objects, and the links components describe exactly that. There is one per context, shared by every type and relation:
| Component | Used by | Members |
|---|---|---|
ResourceLinks |
each <Type>Resource without named links |
self |
DocumentLinks |
each <Type>Document |
self, describedby |
CollectionLinks |
each <Type>Collection |
self, describedby, first, prev, next, last |
RelationshipLinks |
each <Type><Rel>Relationship |
self, related, first, prev, next, last |
RelationshipDocumentLinks |
each <Type><Rel>RelationshipDocument |
self, related, first, prev, next, last, describedby |
RelatedDocumentLinks |
each <Type><Rel>RelatedDocument and <Type><Rel>RelatedCollection |
self, describedby, first, prev, next, last |
Each member points at RenderedLink, the object form the server renders (href, plus
describedby and meta when present), and none is required. describedby is listed only
when the metadata names the document's URL. A member is listed when some response in that
context can render it, so a to-one relationship's links admit pagination members it never
renders, and a relationship object whose relationship endpoint isn't exposed admits a
self it never renders; each component's description says when each member is present.
A component is emitted only when something references it, so a server without relations
has no RelationshipLinks. Error documents keep the generic Links.
"CollectionLinks": {
"type": "object",
"description": "The top-level `links` of a document whose primary data is a collection. The pages are present when the collection is paginated.",
"properties": {
"self": { "$ref": "#/components/schemas/RenderedLink", "description": "The URL that produced the document." },
"describedby": { "$ref": "#/components/schemas/RenderedLink", "description": "The OpenAPI operation that describes the document." },
"first": { "$ref": "#/components/schemas/RenderedLink", "description": "The `first` page of the collection, when there is one." },
"prev": { "…": "…" },
"next": { "…": "…" },
"last": { "…": "…" }
},
"additionalProperties": { "$ref": "#/components/schemas/LinkObject" }
}
additionalProperties stays the open LinkObject (a string, a link object or null),
because a getLinks() override can add any link in any shape. RenderedLink's description
says once that a response's href is absolute to the request host unless the server pins
its links to a configured base URI.
The link schemas carry no examples. The operation examples show
every document whole, links included: each link built from the document's first server
URL plus its path, with the type's Id example in place of {id}, and the pagination
links of page two under the paginator's configured keys. That is where a type's own URLs
appear. The describedby in an example is present only when the metadata names the
document's URL and the document carries the operation; it is built from the same path
templates the projector keys paths by, so the two can't drift.
LinkObject keeps an example of its own: the first registered type's resource URL with its
example id (else 1), plus a describedby pointing at that type's fetch-one operation when
the server renders link objects and names its document URL. The generic Links that error
documents use keeps a one-link example, and the free-form Meta component an empty {},
because a sampler would otherwise fill those open objects with invented members.
A type whose resources carry declared links or
action links gets its own <Type>ResourceLinks: an
allOf of the shared ResourceLinks and an object holding one property per named link,
none of them required, since a link whose href resolves to null is left out. Its
<Type>Resource points there instead of at ResourceLinks. Each named link still
satisfies ResourceLinks' additionalProperties, since every link shape is a
LinkObject. A link with meta members or a static member, one of rel, title, type,
hreflang and describedby, gets its own object schema: href, each static member as a
const, and a meta object whose properties are the declared members, each projected the
way an attribute is on a read, with its type, constraints, description and example. meta
lists as required every member a request cannot hide, and the link lists meta when
there is one. A link with neither takes the open LinkObject union, as an author-supplied
link does:
"FilesResourceLinks": {
"description": "The `links` of a resource object of type `files`.",
"allOf": [
{ "$ref": "#/components/schemas/ResourceLinks" },
{
"type": "object",
"properties": {
"upload": {
"type": "object",
"description": "Where to PUT the file's bytes.",
"properties": {
"href": { "type": "string", "format": "uri-reference" },
"meta": {
"type": "object",
"properties": {
"method": { "type": "string", "enum": ["PUT"], "examples": ["PUT"] },
"headers": { "type": "object", "additionalProperties": {}, "examples": [{ "Content-Type": "image/png" }] },
"expiresAt": { "type": "string", "format": "date-time", "examples": ["2026-10-26T12:00:00+00:00"] }
},
"required": ["method", "headers", "expiresAt"]
}
},
"required": ["href", "meta"]
},
"complete": {
"$ref": "#/components/schemas/RenderedLink",
"description": "Present while the file is PENDING_UPLOAD."
}
}
}
]
}
A declared link may not share its name with an action's link, the one
DeclaresActionLink names. The projection fails rather than
describing one of them wrongly.
A type whose resource declares action links reports them
through the opt-in DeclaresActionLinks type metadata. Each names a resource-scope action
whose link the type's <Type>ResourceLinks then lists as a RenderedLink, whether or not the action's own
metadata names a link, and its describedAs() replaces the generic action-link
description. An action link naming no resource-scope action of the type on the document's
server is left out of it.
LinkObject itself allows every JSON:API 1.1 member: href, rel, describedby (a
URI-reference or a link object), title, type, hreflang (a string or a list of
strings) and meta. A server that opts out
to strings gets no RenderedLink; its members point at LinkObject, which then carries the
note about absolute hrefs, and the links in its operation examples are plain strings.
A $ref with a type or an example is wrapped in allOf¶
Wherever a schema $refs a component and also carries type, examples or a default,
the document writes the $ref as the single entry of an allOf, with the other keywords
beside it: {"type": "string", "description": …, "allOf": [{"$ref": …}], "examples": […]}.
OAS 3.1 allows siblings next to a $ref, but tools that read OAS 3.0 semantics, ReDoc's
example sampler and oasdiff among them, ignore them, so they would never see the type or
the example. Every typed reference below is written this way, as is any other $ref with
an example or a default. A $ref with no such sibling is written plainly. A code generator
should read a single-entry allOf holding only a $ref as that $ref.
A reference carries its component's type¶
A field whose value is a component, a backed enum
or a named shape, carries that component's JSON
type beside its $ref, the type the field would carry inline. So moving a field between
an inline enum and an enum component, or between an inline shape and component(), leaves
its type where a diff tool or a generator reads it, and only the allOf wrapper differs:
- a string-backed enum is
{"type": "string", "allOf": [{"$ref": "#/components/schemas/Status"}]}, an int-backed oneinteger; - a named object or map is
object, a named listarray, and a named union the list of its members' types, such as["string", "number", "boolean"]; - a use that admits
nullkeeps itsanyOfof the$refand{"type": "null"}and addsnullto the type beside it,{"type": ["string", "null"], "anyOf": [{"$ref": …}, {"type": "null"}]}. The$refinside theanyOfstays bare.
The same holds wherever such a reference sits: an attribute, a nested child, a list's items
and each() items, a union member declared with enum(), a pivot or identifier meta
field, a declared link's meta, a filter[<key>] value or list item, and an action's
raw request or response body declared with a DescribesRawBody class
(raw action responses), which takes the top-level type of its
jsonSchema(). The type restates the component's, so nothing
validates differently, and a reference gains no minLength from required() that the
component does not have.
A reference whose component has no single type carries none, as the inline form has none:
a named OneOf, whose variants sit in a oneOf, and a named Union that projects a
oneOf because a member carries an enum or another keyword not scoped to its type. A
reference to a raw body schema with no top-level type carries none either. The $refs
core uses for its own document structure, the resource objects, documents, identifiers,
relationships, links, meta, errors and responses, never carry a type.
Operation examples¶
Every operation's request body and success responses carry a whole worked example on
their application/vnd.api+json media type, and each shared error response carries named
examples, one per code. The projector builds them from the examples you already declare:
the example() on each field, and the exampleDetail, exampleSource and meta members'
example() on each error descriptor. They follow the fields as they change and nobody
maintains a second copy. A code generator or an MCP tool
description can quote one as is.
The examples show what the server sends and accepts:
- A create or update request carries the members that write can set. A read-only field is
left out and a write-only one is in. A create carries
idonly when the type's id policy allows or requires a client id; an update always carries it. Each relationship the write can set is there too. - A response resource carries what a read renders without a sparse fieldset: no write-only
or sparse-by-default member. Its
idis theIdfield's example. Itslinks, and each relationship'sselfandrelated, are the URLs the server builds under the document's first server URL, in the server's link form, with theirdescribedbywhen the server describes its links. - A nested
ObjorMapwith no example of its own is built from its children's examples, and aOneOffrom its first variant. That holds for a nullable or computed one too, since acomputedUsing()orextractUsing()value still renders through the children; aserializeUsing()hook shapes the value itself, so that field needs its own example. A structuredArrayListshows one element built the same way from itsObjorOneOf. A scalarArrayListor anArrayHashhas no children and needs its own example. A declarednullexample staysnull. - Linkage is built from the related type's
Idexample. Where the related type gives none, because the server does not register it or itsIddeclares no example, the relation's ownexampleId()is used. A polymorphic relation shows its first related type. A relation to an unregistered type that declares noexampleId()shows its links and nodatain a read, and is left out of a write; its relationship endpoints report the relation as missing an example. - A collection holds one resource and shows page two of a larger set: the
self,first,prevandnextlinks its paginator renders, and itsmeta.page. A collection whose paginator always counts, which type or relation metadata reports throughDeclaresAlwaysCounted, showslast,meta.totalandmeta.page.total, as every request gets them. A menu counts when its default strategy does, which is what itswantsCount()reports, and a cursor paginator never counts every request. Otherwise a countable collection on a server that registers the Countable profile shows what awithCount=_self_request gets, the parameter and the profile included. On a cursor page that ismeta.totalalone, with nolastand nometa.page.total. Any other collection shows the count-free page. An unpaginated collection carriesmeta.total, which the server always renders for one. - A resource's declared links are in its
links, each built from itshrefexample and its meta members' examples. A declared link is part of what a read renders by default, the way an attribute is, so a link with nohrefexample, or a rendered meta member with no example, is a miss like any other: the operation gets no example and theMissingExamplenameslinks.<name>orlinks.<name>.meta.<member>. - A relationship endpoint carries the linkage document, and a relationship mutation the linkage it writes.
- A custom action's response is built from the type its
ActionResourceorActionCreatednames, and its request body from its input type's create request document when the input is a resource document. ARawResultkeeps its ownexample. - An error response carries one named example per code it offers, keyed by the code and
referencing the code's entry in
components.examples, summarised by its title. Each is a document holding that code's one error, with itsstatus,code,title,exampleDetail,sourceand declaredmeta. A viewer shows the first entry by default, so the map leads with the code a reader most likely meets on the operations sharing the response:QUERY_PARAM_MALFORMED(elseREQUEST_BODY_INVALID_JSON_API) for a400,ACCESS_DENIEDfor a403,RESOURCE_NOT_FOUNDfor a404,RESOURCE_TYPE_UNACCEPTABLEfor a409andATTRIBUTE_VALUE_INVALIDfor a422. The rest follow in catalogue order. A code whose example needs a value nothing declares, such as asourcewith noexampleSourceor a required meta member with noexample(), is left out of the map and reported.
Nothing is invented. When any value an operation's examples need has no declared example, that operation gets none, and the projector says which field was missing:
$projection = (new OpenApiProjector())->projectWithDiagnostics($metadata);
$projection->document; // the OpenApi document
$projection->missingExamples; // list<MissingExample>
Each MissingExample names the operation (its operationId, or the response component
for an error response), the type and the field, such as address.street or
tags.pivot.position, and message() reads as a sentence. An export command can print
them as warnings, or fail on any under a strict flag. project() returns the document
alone.
To replace or switch off an operation's example, type metadata implements
DeclaresOperationExamples and returns a map keyed by operation name: fetchCollection,
fetchOne, create, update, delete, and for a relation fetchRelated.<relation>,
fetchRelationship.<relation>, updateRelationship.<relation>,
addRelationship.<relation> and removeRelationship.<relation>. A false or null value
switches that operation's example off. An OperationExample replaces the parts it names
and leaves the rest generated. Only the parts left generated need declared examples, so a
MissingExample is never reported for a part the override replaces or removes, and an
operation whose override covers every part reports nothing:
use haddowg\JsonApi\OpenApi\Metadata\OperationExample;
public function operationExamples(): array
{
return [
'delete' => new OperationExample(responses: [200 => ['meta' => ['deleted' => true]]]),
'update' => false,
];
}
request takes the request document, or false for none. responses maps a success
status to its document, or to false. A name the type does not expose, or a status the
operation does not answer with a JSON:API document, fails the projection. These names are
the ones OperationKey::fromName() parses, so an integration that checks its own override
keys at boot can call it, or OperationKey::tryFromName() for null instead of a
\InvalidArgumentException. The key it returns carries the OperationKind, the relation
name and the HTTP method. Action metadata
implements DeclaresActionExample instead, whose example() returns one
OperationExample, false, or null to keep the generated one. Server metadata that
implements DeclaresExampleGeneration and returns false from generatesExamples()
switches generation off for the whole document.
Operation ids¶
Every operation carries an operationId built from the type name, and from the relation or
action name where there is one:
| Operation | operationId |
|---|---|
| fetch collection, fetch one, create, update, delete | fetchCollection.<type>, fetchOne.<type>, create.<type>, update.<type>, delete.<type> |
| related read | fetchRelated.<type>.<relation> |
| relationship read, replace, add, remove | fetchRelationship.<type>.<relation>, updateRelationship.…, addRelationship.…, removeRelationship.… |
| custom action | action.<type>.<path>, or action.<type>.<path>.<method> when the action answers to more than one method |
| Atomic Operations | atomic.operations |
A singleton type keeps these ids on its /{uriType} paths.
So the ids stay unique, even for a consumer that flattens them into names by dropping
case and punctuation, ActionDeclarations rejects with a \LogicException:
- one action path declared at both the resource and the collection scope, which would give both the same id;
- an action path that flattens to one of the words above (
ActionDeclarations::RESERVED_NAMES), sofetch-oneandDeleteare refused. A relation's name is not reserved, so anowneraction can sit beside anownerrelation; - two actions whose ids differ only in case or punctuation, such as
export-allandexportAll.
The projector checks every type it projects. A framework integration should also call
ActionDeclarations::validate($type, $actions) when it registers a type's
actions, so the mistake fails at boot rather than when the document is first generated.
The metadata contract¶
Core owns the JSON:API→OAS semantics, but most of the data — the API title and base
URLs, server assignment, tag definitions, security schemes, and the type/relation/action
inventory — is app- and framework-side. So the projector reads its input through a small
family of read-only interfaces in haddowg\JsonApi\OpenApi\Metadata. A framework
integration implements these from its compiled registry; core projects purely against
them.
| Interface | Describes |
|---|---|
ServerMetadataInterface |
one server: info (title / version / description / contact / license), servers (base URLs), the JSON:API version, tag definitions, security schemes + document-level default security, external docs, the type list, and the optional Atomic Operations endpoint |
TypeMetadataInterface |
one type: type / uriType, the field inventory (may be absent for a standalone serializer), relations, the operation allow-list (+ which operations are secured / public), the id policy (allowsClientId / requiresClientId / idPattern), the page value schema (pageSchema) + countability, filters, sorts, actions, tags, description (+ per-operation description overrides), includable paths, and per-operation response declarations (responsesFor) |
RelationMetadataInterface |
one relation: name, related type(s), cardinality, endpoint exposure + mutation flags, per-relation security, the page value schema (pageSchema), filters/sorts (for a queryable to-many), pivot fields, and description |
ActionMetadataInterface |
one custom action: path, methods, scope, input mode + type, its responds response set, whether it is secured, tags, summary, description |
The pageSchema() accessors carry the resolved paginator's self-described page[…]
object schema (a oneOf menu for a MultiPaginator), or null when the collection is
unpaginated — so the projector emits the whole page family as one deepObject
parameter without a central paginator switch. Discriminator enums (OperationType,
ActionScope, ActionInputMode) round out the contract. The accessors that return
OAS value objects (servers(), tags(), securitySchemes()) hand the projector
ready-made VOs — that data is config-shaped, with no JSON:API semantics to interpret —
while type / relation / action data, which does carry semantics the projector must
interpret, flows through the interface family above.
One optional contract sits beside the family: ContributesErrorCodes extends
ServerMetadataInterface with errorSources(): iterable, and the projector checks for it
when it assembles that server's error catalogue. Metadata
that does not implement it publishes core's codes and nothing else.
DeclaresMethodNotAllowed is another. Its rendersMethodNotAllowed(): bool says whether the
adapter answers a method a path does not accept with a JSON:API error, which adds
METHOD_NOT_ALLOWED to the catalogue. No operation lists a 405 response, since an
operation is one method on one path.
A second sits beside TypeMetadataInterface: DeclaresOperationExtensions adds
extensions(): array and operationExtensions(OperationType): array, the vendor
extensions for a type's operations. DeclaresNamedOperationExtensions adds
namedOperationExtensions(): array, extensions for single operations keyed by operation
name. See
your own extensions.
A third sits beside RelationMetadataInterface: DeclaresWriteOnlyRelation adds
isWriteOnly(): bool. A relation that reports true is projected the way a
write-only attribute is. It stays in the create and update
request schemas, where its property carries writeOnly: true, and keeps its relationship PATCH/POST/DELETE, each documented as a
204. It is left out of the read resource schema, the fields[type] and ?withCount
enums, and it has no related endpoint and no relationship GET. Report true only for an
unconditional writeOnly(); a relation write-only by predicate stays in the superset, as
an attribute does. Metadata that doesn't implement the interface projects every relation
as readable.
A fourth sits beside it: DeclaresRelationUriFieldName adds uriFieldName(): string, the
segment the relation's related and relationship endpoints are served under. Return the
core relation's uriFieldName(), which is the name unless withUriFieldName() set one.
Metadata that doesn't implement it keys every relation's paths by its name.
Another sits beside RelationMetadataInterface: DeclaresIdentifierMeta adds
identifierMetaFields(): list<FieldInterface>, the members a relation's identifier meta
resolver produces. Return the core relation's identifierMetaFields(). Metadata that
doesn't implement it leaves each linkage identifier's meta open except for a pivot.
DeclaresRelationDataWithholding sits beside ServerMetadataInterface. Its
canWithholdRelationData(TypeMetadataInterface, RelationMetadataInterface): bool says
whether the adapter's RelationAuthorizerInterface can refuse some caller the relation's
data on a parent's document. Answer false only when no caller can be refused it, such as
a relation with no read permission of its own whose related types gate no collection read.
Metadata that doesn't implement it lets a relationship object that renders links require
no data. See linkage a parent always renders.
Another sits beside RelationMetadataInterface: DeclaresPolymorphicRelation adds
isPolymorphic(): bool. Return true when the core relation is a
PolymorphicRelationInterface, which MorphTo and MorphToMany are. Metadata that
doesn't implement it is polymorphic only when it lists more than one type. See
polymorphic relations.
A fifth sits beside TypeMetadataInterface: DeclaresSingularName adds
singularName(): ?string, the noun the generated prose
uses for one resource of the type. Mirror the resource's getSingularName(). Metadata that
doesn't implement it, or returns null, gets the inflected singular of the type name.
Three more shape the operation examples: DeclaresOperationExamples
beside TypeMetadataInterface, DeclaresActionExample beside ActionMetadataInterface, and
DeclaresExampleGeneration beside ServerMetadataInterface. Metadata that implements none
of them gets every example the projector can build.
Two more feed the examples facts the rest of the contract does not carry.
DeclaresAlwaysCounted adds alwaysCounts(): bool to type or relation metadata: return the
collection paginator's wantsCount(). DeclaresRelationExampleId extends
RelationMetadataInterface with exampleId(): ?string: return the core relation's
exampleId().
Two more shape the sort example. DeclaresDefaultSort extends
TypeMetadataInterface with defaultSort(): list<SortDirective>: return the resource's
defaultSort(). DeclaresSortExample extends it with sortExample(): ?list<string>: return
the resource's sortExample(). Metadata that implements neither shows the first exact sort
as the example.
DeclaresDroppedFilterDefaults extends RelationMetadataInterface with
dropsAllFilterDefaults(): bool and droppedFilterDefaults(): list<string>: return the core
relation's, from DropsFilterDefaultsInterface. The projector leaves a dropped default off
the relation's related and relationship endpoints. Metadata that doesn't implement it shows
every related default there.
Four more describe links. DeclaresLinkObjects extends ServerMetadataInterface with
rendersLinkObjects(): bool (mirror Server::withLinkObjects()) and
documentUrl(): ?string, the URI-reference the document is served at, which every
describedby points into. Metadata that doesn't implement it projects link objects without
describedby, which is what a server renders by default. DeclaresActionLink extends
ActionMetadataInterface with linkName(): ?string: a resource-scope action that returns a
name is listed under it in its type's <Type>ResourceLinks, described by its first declared
method. DeclaresResourceLinks extends TypeMetadataInterface with
declaredLinks(): list<DeclaredLink>: return the resource's allLinks(). Metadata that
doesn't implement it projects no declared links. DeclaresActionLinks extends
TypeMetadataInterface with actionLinks(): list<ActionLink>: return the resource's
allActionLinks(). Metadata that doesn't implement it projects only the action links
DeclaresActionLink names.
DeclaresRelatedOnly extends TypeMetadataInterface with isRelatedOnly(): bool. Return
true for a type the server marks related-only. Its
resource objects then $ref a <Type>ResourceLinks of their own that lists the type's
declared links and no self, and its examples show no self. The metadata of such a type
must expose no operations, no actions and no relationship or related endpoint, and the
projector refuses it with a \LogicException otherwise. It still gets the create
components when an action takes it as its request document. A document with a related-only
type declares the RELATED_ONLY contract tier in its
x-generator stamp. Metadata that doesn't implement
it projects every type with a self.
DeclaresSingleton extends TypeMetadataInterface with isSingleton(): bool. Return
true for a singleton type. Its fetch and update are
projected at /{uriType}, its relationship and related endpoints at
/{uriType}/relationships/{rel} and /{uriType}/{rel}, and its actions at
/{uriType}/-actions/{name}, none of them with an {id} path parameter. Its operation ids
stay fetchOne.<type>, update.<type> and so on, so operation scopes, operationExtensions
and x-mcp keyed by operation name, error documents (InboxesUpdate409), examples and
describedby all follow it to those paths. Its <Type>Resource component carries
x-singleton. The metadata of a singleton must expose no
FetchCollection, Create or Delete and no collection-scope action, and the projector
refuses it with a Resource\SingletonMisdeclared otherwise. A document with a singleton
declares the SINGLETONS contract tier in its
x-generator stamp. Metadata that doesn't implement
it projects every type at /{uriType}/{id}.
DeclaresDocumentMeta extends TypeMetadataInterface with
documentMeta(OperationType $operation, ?string $relation = null): iterable, the members of
the top-level meta of the document that operation answers with. Delegate to the type's own
documentMeta(). Each operation returning members,
and each related endpoint serving the type, answers with a
typed-meta document. A document with one declares the
TYPED_DOCUMENT_META contract tier in its
x-generator stamp. Metadata that doesn't implement
it keeps the shared documents.
Two more sit beside ActionMetadataInterface. DeclaresActionSafety adds readOnly(),
destructive() and idempotent(), each ?bool, which project as
x-safety. DeclaresActionExtensions adds extensions(): array,
the action's own vendor extensions. Action metadata that implements neither projects as
before.
DeclaresActionFilters extends ActionMetadataInterface with filters(): bool|array,
the filters a collection action takes from its type:
true for all of them, a list of filter keys, or false for none.
Three more carry deprecation. DeclaresDeprecation extends
TypeMetadataInterface with isDeprecated(): bool, sunset(): ?\DateTimeInterface and
deprecatedOperations(): list<string>; fill it from the declaration behind the type's
Deprecation and Sunset response headers. DeclaresActionDeprecation extends
ActionMetadataInterface with isDeprecated(): bool. DeclaresDeprecatedRelation extends
RelationMetadataInterface with isDeprecated(): bool: return the relation field's
isDeprecated(). Metadata that implements none of them projects no deprecation markers.
A standalone serializer with no declared field inventory is tolerated
(hasFields() is false, fields() is empty): it projects to a permissive
resource-object schema and no attribute components, exactly mirroring the runtime's
"serializer but no fields" case. Where it can be created, or an action takes it as its
request document, its <Type>CreateRequest is still a request document: data with the
type const, the id its client-id policy allows and an open attributes object. Where it
can be updated, its <Type>UpdateRequest is the same document with a required id.
Response declarations¶
By default every operation advertises the single success response it has always emitted — a
create 201 (with Location and the created document), an update 200, a delete 204, a
fetch 200, a collection 200. A type may override the success set an operation
advertises, and a custom action declares its own, through a small family of immutable
response objects in haddowg\JsonApi\OpenApi\Metadata. This is how a spec-valid 204, an
asynchronous 202, or a 303 completion enters the contract.
The response objects¶
Each object names one HTTP status an operation may return; a declaration is a list of them (a set). They are typed per operation so an illegal combination is unrepresentable:
| Object | Status | Body / headers | Valid on |
|---|---|---|---|
new Created() |
201 |
created resource document + Location |
create |
new Ok() |
200 |
resource / collection document | update, fetch-one, fetch-collection |
new NoContent() |
204 |
no body | create, update, delete, actions |
new Accepted(string $jobType) |
202 |
the job type's document + Content-Location + Retry-After |
create, update, actions |
new SeeOther(?string $description, ?string $mediaType) |
303 |
Location only, no body; on an action with a mediaType also a 200 location document |
fetch-one, actions |
new MetaResult(array $meta = []) |
200 |
a meta-only document | delete, actions |
new ActionResource(string $type, array $meta = []) |
200 |
the named type's document | actions |
new ActionCreated(string $type, array $meta = []) |
201 |
the named type's document + optional Location |
actions |
new RawResult(string $mediaType, …) |
200 by default |
a body that is not JSON:API, beside the JSON:API one | actions |
Each implements a per-operation marker interface — CreateResponse, UpdateResponse,
DeleteResponse, FetchOneResponse, FetchCollectionResponse for CRUD, and
ActionResponse for custom actions — so a value only type-checks where it is spec-valid
(new SeeOther() is a FetchOneResponse, never a CreateResponse). The helpers
OperationResponses (defaultFor() / validate()) and ActionResponses (validate())
supply the default set and reject a malformed one: empty, a duplicate status, more than one
job-bearing 202, or a status outside the operation's spec-valid range.
The metadata contract carries the resolved sets:
TypeMetadataInterface::responsesFor(OperationType) returns a type's success set for a
CRUD/read operation (its declared override, else OperationResponses::defaultFor()), and
ActionMetadataInterface::responds() returns an action's. The OperationProjector emits
one Response per element, keyed by status — and the unoverridden default reproduces the
exact response the document has always carried, so an existing contract is byte-for-byte
unchanged.
Raw action responses¶
An action that answers with something other than a JSON:API document, such as a CSV
export, a PDF or an image, declares a RawResult per media type. Several sit beside the
action's JSON:API response at the same status, and the request's Accept header picks
between them:
use haddowg\JsonApi\OpenApi\Metadata\{MetaResult, RawResult};
$responds = [
new MetaResult(),
new RawResult('text/csv', schema: ['type' => 'string'], headers: [
'Content-Disposition' => 'Names the downloaded file.',
], example: "id,title\n1,Hello\n"),
new RawResult('application/pdf', binary: true),
new RawResult('application/json', schema: ChartSummary::class),
];
schema is an inline JSON Schema array, or the class name of a DescribesRawBody, whose
static jsonSchema() the projector emits once as #/components/schemas/<ShortClassName>
and $refs from each use, with the schema's top-level type beside the $ref. A class whose short name another component already holds is
refused. binary: true projects {type: string, format: binary}. headers maps a header
name to its description, or to a Header object, and joins the response's headers.
example becomes the media type's example. Each media type lands under the status's
content, next to application/vnd.api+json when the action declares a JSON:API response
there too. ActionResponses::validate() allows any number of raw results per status, one
per media type; the media type must be concrete, never JSON:API, and the status a 2xx
with a body.
At runtime the integration picks the media type with
Negotiation\AcceptNegotiator::negotiate($accept, ActionResponses::mediaTypes($responds)).
Each media type takes the q of the most specific Accept range that matches it, the
highest wins, and a tie goes to JSON:API, so a client that accepts JSON:API as readily as
anything else gets it. Nothing acceptable is a 406 MediaTypeUnacceptable, and every
error renders as a JSON:API document whatever was negotiated. A handler answers a raw pick
with a RawResponse.
A document whose actions declare no RawResult is byte-for-byte unchanged.
Actions that create a resource¶
An action that creates the resource it answers with, such as
POST /orders/{id}/-actions/duplicate, declares new ActionCreated('orders'). The
projection documents a 201 whose body is the named type's document, with an optional
Location header, and offers the type's include and fields[<type>] parameters, as an
ActionResource does. It can sit beside a 200 ActionResource for an action that
sometimes creates and sometimes returns an existing resource.
The handler returns a DataResponse as usual. Server::dispatch() renders it as 201
when the action declares an ActionCreated and no ActionResource
(ActionResponses::dataStatus()), so the declared status and the sent one cannot drift.
When the action declares both, the response stays 200 unless the handler calls
withStatus(201), and a status the handler set always wins. Setting the Location header
is the handler's choice, with withHeader('Location', …).
Actions that answer with a URL¶
An action that hands out a URL, such as a short-lived download link, declares SeeOther
with a mediaType, the media type the URL serves. A download whose type varies or isn't
known in advance declares application/octet-stream. description replaces the generated wording. The
mediaType is the opt-in: a bare new SeeOther(), or one with only a description, stays
the plain 303 it always was, at runtime and in the projection.
use haddowg\JsonApi\OpenApi\Metadata\SeeOther;
$responds = [new SeeOther('A short-lived link to the export.', 'text/csv')];
The handler returns SeeOtherResponse::to($url, $expiresAt) (see
location responses), and the request's Accept decides
the shape. A request that names application/vnd.api+json, with nothing else it lists
weighing more, gets a 200 location document. Any other request gets the 303: no
Accept, */*, a browser's navigation, a link click or curl. The document exists
because a browser cannot read a 303's Location from fetch(), which with
redirect: 'manual' returns an opaque response:
{
"links": {
"self": { "href": "https://api.example.com/files/1/-actions/download" },
"location": {
"href": "https://storage.example.com/1.csv?signature=abc",
"type": "text/csv",
"meta": { "expiresAt": "2026-10-27T12:00:00+00:00" }
}
},
"meta": { "expiresAt": "2026-10-27T12:00:00+00:00" },
"jsonapi": { "version": "1.1" }
}
self is the action's own URL. location.type is the declared media type unless the
handler sets its own with withType(), and location.meta appears when the URL expires.
An action declaring application/octet-stream may set any type, such as application/pdf
for one file and image/png for the next. Any other declaration fixes the type: the handler
may add or change parameters, such as text/csv; charset=utf-8, but Server::dispatch()
throws a LogicException naming the declared type when the handler sends a different one,
because the published document allows only that type. JSON:API needs a
meta, data or errors member at the top level, so the top-level meta.expiresAt is
always there, null for a URL that does not expire. The expiry is written in the
server's output timezone, as a DateTime attribute is. Both shapes send
Cache-Control: no-store and Vary: Accept unless the handler set its own. Errors stay
JSON:API documents.
The projection documents both responses. The 200 references a shared
LocationDocument component, whose links.location is a LocationLink with href,
type and meta.expiresAt, narrowed in an allOf so type is a const of the declared
media type. For application/octet-stream the narrowing leaves type any string, with
the declared type as its example, and the document declares the VARYING_LOCATION_TYPE
contract tier in its x-generator stamp. The
303 documents Location as a uri-reference, and both document Cache-Control. When the action also declares a 200 JSON:API body, such as an
ActionResource, the 200 is a oneOf of that document and the location document. The
operation's example is the location document with a fixed example URL and expiry, typed
with the declared media type.
An integration negotiates such an action with
AcceptNegotiator::negotiateAction($accept, $responds), which returns null instead of
throwing a 406 when no declared media type is acceptable, because the action can still
answer with its 303. An action with a bare SeeOther keeps the 406, since it may
answer with a JSON:API body instead. It passes the declared responses to CustomActionOperation
(responds:), so Server::dispatch() can type the location link from the declared
media type. SeeOther on a fetch-one is unchanged: always the bare 303.
Accepted request bodies¶
An action's input mode projects one request body: none, its JSON:API document, or an
open application/octet-stream body for raw input. The document is its input type's
<Type>CreateRequest, since the action parses, validates and hydrates the body as a
create: data with the type const, an id only as the type's client-id policy allows,
the create attributes and the relationships a create may set. The request example is
that create document, with no links. An action that takes several media
types, or a raw body with a known shape, also implements DeclaresAcceptedBodies on its
metadata, and each AcceptedBody becomes one requestBody.content entry:
use haddowg\JsonApi\OpenApi\Metadata\AcceptedBody;
public function accepts(): array
{
return [
new AcceptedBody('text/csv', schema: ['type' => 'string']),
new AcceptedBody('image/*', binary: true),
new AcceptedBody('multipart/form-data'),
new AcceptedBody('application/json', schema: ImportRows::class),
];
}
The media type may end in a wildcard, such as image/*, and parameters are dropped from
the key. A JSON:API entry, application/vnd.api+json by default or any entry declared with
document: true, carries the action's request document. binary: true gives a binary
string, schema takes an inline array or a DescribesRawBody class emitted as a component
the way a raw response's is. An entry with none of them takes a default from its media
type: a string for text/*, any JSON value ({}) for application/json and any +json
type, an open object for multipart/form-data and application/x-www-form-urlencoded,
and a binary string for anything else, such as image/* or application/pdf. A wildcard
follows its family, so text/* is a string. The body is required only when the
action's input mode is Document, and the operation lists the 415 a Content-Type it
does not accept gets.
An action that returns no accepted bodies, or whose metadata does not implement the interface, projects as before.
Filters on a collection action¶
A collection-scope action, such as POST /articles/-actions/archive, often works on the
same rows a collection fetch would list. Its metadata can implement DeclaresActionFilters
to take the mount type's declared filters, so a client narrows the rows with the
filter[<key>] parameters it already uses on GET /articles. filters() returns true
for every filter the type declares, a list of filter keys for some of them, or false for
none:
The action's operation lists one filter[<key>] parameter per filter it takes, in the order
the type declares them, built the same way the collection fetch builds them. A Range keeps
its deepObject style, a set filter its delimited array, and a declared example, description
or deprecation comes along unchanged. The operation already lists the 400 an invalid
filter value gets.
Only a collection-scope action may take filters, and every key in the list must be one the
type declares. ActionDeclarations::validate() rejects either mistake with a
\LogicException naming the action and the type, and the projector runs the same check.
ActionDeclarations::filters() resolves the filters an action takes from its type's
metadata. An adapter parses, validates and applies exactly that list, the way it does for
the collection fetch, and rejects any other filter[<key>] with the same 400.
Such an action also needs the type's fetchCollection scopes beside its own. The
scope table adds them, so the operation's security, the enforcer and the
operation catalogue all list the same union.
A document with at least one action taking a filter declares the ACTION_FILTERS contract
tier in its x-generator stamp. Action metadata that
does not implement the interface, or returns false, projects as before.
The asynchronous-write lifecycle¶
Together the objects reflect the JSON:API asynchronous processing recommendation in the generated document:
- A write accepted for background processing advertises
new Accepted('jobs')— a202whose body is thejobstype's document, plus aContent-Locationheader (the job URL to poll) and aRetry-Afterhint. Register the job type so the body references itsJobsDocumentcomponent; for a type the server doesn't describe, the projector inlines an open document whosedata.typeis the job type instead of naming a component it never defines. AnActionResourceorActionCreatedbody type works the same way. - The client polls the job resource; completion is a
303 See Otherto the produced resource. Model it either as a fetch-one on the job type declaring[new Ok(), new SeeOther()](the spec-canonical shape:200with the job's status while it runs,303when done) or as a custom action declaring[new Accepted('jobs'), new SeeOther()].
Because the 303 is a runtime decision, a fetch-one that may redirect implements the
read seam haddowg\JsonApi\Resource\ResolvesCompletionRedirect:
completionLocation(object $entity): ?string returns the produced resource's URL when the
work is complete (the handler then renders a 303) or null for the normal 200. The
declaration documents the 303; the seam performs it.
Authoring them¶
Core defines and projects these objects; the framework integrations let you declare them on a resource or action — see the response-declaration sections of the Symfony bundle and Laravel package documentation.
Authoring the schemas: describedAs() and example()¶
Two field builder methods shape a field's projected schema. They are render-neutral (the runtime ignores them) — they exist purely so the generated document reads well:
use haddowg\JsonApi\Resource\Field\Str;
use haddowg\JsonApi\Resource\Field\Integer;
public function fields(): array
{
return [
Id::make(),
Str::make('title')
->describedAs('The human-readable track title.')
->example('Paranoid Android'),
Integer::make('duration')
->describedAs('The track length, in seconds.')
->example(383),
];
}
describedAs(string)sets the schemadescription. (The setter is named to match the filters'describedAs(); the read-back getter isgetDescription().)example(mixed)sets the schema'sexamplesto a list holding the value, the OAS 3.1 keyword; the singular Schema Objectexampleis deprecated there. A declarednullis honoured and is distinct from "no example".
Filters take both too. A filter's describedAs() overrides the generated default every
convenience filter ships with, and its example() becomes the filter[<key>] parameter's
own example. That puts it on the Parameter Object rather than the value schema, because
OAS 3.1 deprecates the Schema Object's example. Give it the
parameter's whole value, in the shape the schema describes:
Where::make('name')->describedAs('Match the artist name.')->example('Radiohead'),
WhereIn::make('genre')->example(['rock', 'jazz']),
Range::make('rating')->example(['min' => 3, 'max' => 5]),
The projector emits the example as declared and does not check it against the schema. A
filter without one is unchanged, and a custom filter opts in by implementing
ExemplifiedFilter. Neither the description nor the example is copied into the parameter's
schema. Some filters are documented by rule rather than as declared:
- A presence filter ends its description with
"Applied when present; value ignored." and always has the example
true.WhereNull,WhereNotNull,WhereHasandWhereDoesntHavetakedescribedAs()too. - A list filter's example and default are shown
as the same members on
filter[<key>]andfilter[<key>][], split or joined on the delimiter to fit each schema. - A
WhereSet's example and default are lists of booleans, shown as[true, false]on both of its array parameters whichever form you declared them in. - A
WhereMorphis adeepObjectwhosetypeis an enum of its relation's types and whoseidis a comma-separated string or an array of ids. Give its example as an object:WhereMorph::make('subject')->example(['type' => 'rfps', 'id' => ['812']]). - A filter family's description and
example go in its
x-filter-familiesentry and on the sharedfilterparameter. - A group is one parameter, so a child declaring its own description or example fails when the group is built.
Sorts take describedAs() as well, and a sortable field's
sort carries the field's description.
Relations take describedAs() as well, and their relationship object's
schema is exemplified from exampleId() or the
related type's id; a relation builder refuses example(). A pivot relation's example member
also carries its meta.pivot, and any declared identifier meta, built from each field's
example as the operation examples build them, so it has no example when one of those
fields has none. Beyond fields, every documentable element
gets a generated default description the author may override declaratively: a type's
resource object via its description(), and each CRUD / related / relationship operation
via a per-operation description override — the projector emits the author's value when
present, a short generated sentence otherwise, never a blank. Because a request-time,
per-caller condition cannot be baked into a cached schema, a conditionally hidden or
prohibited field/verb is documented as the superset — the union of what any caller
may see or do (see the request-aware predicates note).
How generated prose names a type¶
A generated summary or description that means one resource names it in the singular, with
its article: GET /advertisers/{id} reads "Fetch an advertiser", and its related endpoint
"Fetch the related agencies of an advertiser". A collection keeps the plural: "List
advertisers". Wording that names the type itself, such as "a resource object of type
advertisers", keeps the type name as declared.
The type name renders as lower-case words, split at -, _ and camelCase boundaries, so
export-jobs and exportJobs both read "export jobs" and "an export job". An all-caps
word keeps its case. The singular inflects the last word with doctrine/inflector, which
handles the common irregulars (people reads "person").
The article is "an" before a vowel letter and "a" otherwise, with three exceptions: a word
that starts with a consonant sound takes "a" ("a user", "a unique code", "a one-off
charge"), a silent h takes "an" ("an hour"), and an all-caps acronym follows the spoken
name of its first letter ("an SDK release", "a URL alias").
When the inflection is wrong or reads badly, override getSingularName() on the resource:
final class MediaResource extends AbstractResource
{
protected static string $type = 'media';
public function getSingularName(): ?string
{
return 'media item';
}
}
Return the noun as words, without an article; the projector picks "a" or "an" from it. The
framework integration reads it through DeclaresSingularName.
Generated parameter descriptions also leave out what the parameter's schema already says.
The allowed sort tokens, include paths, fields[TYPE] members and withCount tokens
are each the items enum, so the prose explains the encoding (a comma-separated list, -
for descending, the profile that must be negotiated, where a count lands) and stops there.
A backed enum's value → description table stays, because it carries what each value
means, which an enum cannot.
Deprecation¶
A type, a single operation, an action, a field, a relation, a filter and a sort can each be marked deprecated. Every marker is documentation only. The server keeps serving whatever is marked exactly as before; the document just tells clients to move off it.
A type whose metadata implements DeclaresDeprecation and reports isDeprecated()
marks every operation the document emits for it deprecated: true: its CRUD operations,
its related and relationship endpoints and its custom actions. A declared sunset() adds a
sentence naming the date to the end of each of those operations' descriptions, after any
description an author declared:
"/articles": {
"get": {
"description": "…\n\nThis operation may stop responding on or after 2027-06-30, its sunset date.",
"deprecated": true
}
}
A sunset is a date rather than a flag, so it marks nothing deprecated on its own.
Single operations are listed by name in deprecatedOperations(), in the grammar
operation examples and scopes are keyed by: fetchCollection,
fetchOne, create, update, delete, or fetchRelated, fetchRelationship,
updateRelationship, addRelationship or removeRelationship with a dot and the relation
name. A name the type does not expose fails the projection with an
\InvalidArgumentException. OperationKey::tryFromName() checks a name earlier. An
action is not named there; its metadata implements DeclaresActionDeprecation
instead.
A field declared deprecated() carries
deprecated: true on its property in the read, create and update attribute schemas, at
whatever depth it sits. A relation carries it on its property under relationships in
the read resource and the write requests, beside the $ref:
"relationships": {
"type": "object",
"properties": {
"author": { "$ref": "#/components/schemas/ArticlesAuthorRelationship", "deprecated": true }
}
}
A filter marks its filter[<key>] parameter deprecated: true. A sort cannot be
marked inside the sort enum, so its key is listed under
x-deprecated-sorts, and a deprecated sort family's
entry in x-sort-families carries deprecated: true.
A document that carries any of these markers declares the DEPRECATION contract tier in
its x-generator stamp, so an older generator is
warned that it may drop them. A document with none of them, including one whose only
declaration is a sunset, keeps the lower stamp.
Vendor extensions¶
The projection emits a few OpenAPI vendor extensions (x-… keywords) to carry
information the base OAS vocabulary cannot.
The generator contract: x-generator¶
Every projected document stamps its info with one integer:
contract is the version of the emitted structure, for the code generators that read
the document (json-api-client-codegen
and @haddowg/json-api-codegen). It is not the
package version and moves only when the structure does. A generator declares the range it
understands: it errors on a document below that range and warns on one above it,
since a newer server describes capabilities the generator would otherwise silently leave
out. A document with no x-generator predates the field and reads as contract 1. What
each release added is in the changelog.
Diffing documents across releases¶
A $ref that carries an example or default is written as a single-entry allOf
holding the $ref, with the example beside it. That means the same schema, but
oasdiff breaking compares the allOf wrapper with a bare $ref and reports false
"required property removed" findings against a document from an older release. Pass
--flatten-allof so oasdiff merges each allOf before comparing. A field moving between an
inline enum or shape and a component then compares as the same type, since the
reference carries it:
Singleton types: x-singleton¶
A singleton type has no collection or create endpoint for a
generator to find it from, and its fetch and update paths carry no {id}. Its
<Type>Resource component names its path instead:
"InboxesResource": {
"type": "object",
"x-singleton": "/inbox",
"properties": { "type": { "const": "inboxes" }, "id": { "type": "string" } }
}
The value is the path key of its fetchOne.<type> and update.<type> operations. Its
related, relationship and action paths are that path followed by /{rel},
/relationships/{rel} and /-actions/{name}. A generator calls them without an id, while
the resource object it reads back still carries one.
Typed document meta: x-document-meta¶
An operation whose document declares its top-level meta
answers with a document component of its own. It is an allOf of the shared document and an
object narrowing meta to the declared members, marked x-document-meta: true:
"InboxItemsMarkAsReadActionDocument": {
"allOf": [
{ "$ref": "#/components/schemas/InboxesDocument" },
{
"type": "object",
"required": ["meta"],
"properties": {
"meta": {
"type": "object",
"additionalProperties": false,
"required": ["marked"],
"properties": { "marked": { "type": "integer", "description": "How many items this call marked read." } }
}
}
}
],
"x-document-meta": true
}
The first allOf entry is the shared document: <Type>Collection for a collection fetch,
<Type>Document for a fetch, create, update or document action, the relation's
RelatedCollection or RelatedDocument for a related endpoint, and MetaDocument for a
meta-only result. The second carries meta, closed with additionalProperties: false and
required when any member is. A collection's meta also lists page and total, which core
writes there.
The component is named for the operation, as its error documents are, followed by
Document: InboxItemsFetchCollectionDocument, InboxItemsFetchOneDocument,
BoardsNotesFetchRelatedDocument, InboxItemsDeleteDocument. An action's is
<Type><Path>ActionDocument for its 200 and <Type><Path>ActionCreatedDocument for its
201, one per action whatever methods it answers to. An operation that declares nothing
keeps the shared component, so its document does not change. A name another component
already holds throws.
A relationship write declaring its meta-only document
answers 200 with <Type><Rel><Kind>Document, such as PlaylistsTracksAddRelationshipDocument,
narrowing MetaDocument, in place of its linkage. A 202 whose job document declares its
meta answers <Type><Operation>AcceptedDocument, such as ImportsCreateAcceptedDocument, or
<Type><Path>ActionAcceptedDocument for an action, narrowing the job type's <Job>Document.
An AdditionalProperties entry in any of these declarations opens meta, to any value or to
its of() field's schema.
Typed request meta: x-request-meta¶
A write whose request declares its top-level meta
takes a request document of its own, named for the operation and followed by
RequestDocument: ImportsCreateRequestDocument, ImportsUpdateRequestDocument,
ImportsDeleteRequestDocument, PlaylistsTracksAddRelationshipRequestDocument, and
<Type><Path>ActionRequestDocument for an action, with the method too,
<Type><Path>ActionPostRequestDocument, for an action mounted on several methods. It is an
allOf of the shared request document and an object narrowing meta to the declared object,
marked x-request-meta: true:
"ImportsCreateRequestDocument": {
"allOf": [
{ "$ref": "#/components/schemas/ImportsCreateRequest" },
{
"type": "object",
"properties": {
"meta": {
"type": "object",
"properties": { "idempotencyKey": { "type": "string", "minLength": 1 } },
"required": ["idempotencyKey"],
"additionalProperties": false
}
},
"required": ["meta"]
}
],
"x-request-meta": true
}
The shared request document is <Type>CreateRequest or <Type>UpdateRequest, the relation's
RelationshipRequest for a pivot-backed relation or its RelationshipDocument otherwise, and
for an action the request document its input mode takes. A write with no shared document, a
delete or an action taking no input, takes a meta-only object instead, with meta and
jsonapi; a delete declaring request meta takes a request body, and advertises 415 and
422. meta is required when a member is. The shared <Type>CreateRequest keeps its
open top-level meta, so an action taking the type's document is unaffected by its create's
declaration.
Typed resource meta: x-resource-meta¶
A type declaring its resource objects' meta gets one
object per direction, each marked x-resource-meta: true. <Type>ResourceMeta is what a
response renders, and <Type>Resource references it in place of the shared Meta.
<Type>CreateResourceMeta and <Type>UpdateResourceMeta are what a write may send, and the
data of <Type>CreateRequest and <Type>UpdateRequest references them. The atomic
<Type>AtomicAdd and <Type>AtomicUpdate carry the atomic declaration inline. Each is closed
unless an AdditionalProperties entry opens it. A type some pivot-backed relation points at
lists an optional, open pivot in <Type>ResourceMeta, which its related endpoint renders
beside the declared members. A type declaring nothing keeps the shared
Meta.
An adapter's standalone per-type JSON Schema, one self-contained resource object per type,
builds on StandaloneResourceObject::project()
and types the same objects inline: meta as <Type>ResourceMeta, and under
relationships.<name>.data each identifier's meta as <Type><Rel>IdentifierMeta, or as a
pivot of <Type><Rel>Pivot alone. A pivot relation's identifiers require meta and its
pivot, as in the document. A type or relation declaring none keeps an open object.
A request's top-level meta and a write's data.meta belong to request documents, which
that export does not describe.
Atomic operations of a declaring type¶
When a type declares the meta of an atomic operation, that operation takes a kind of its
own beside the shared ones in the AtomicOperation union, marked x-request-meta: true. An
add or update is <Type>AtomicAddOperation or <Type>AtomicUpdateOperation, its data
the type's resource object, and the shared kind's data union leaves the type out. A remove
is <Type>AtomicRemoveOperation and a relationship operation
<Type><Rel>AtomicRelationshipAddOperation and its update and remove siblings. These name
their target by a ref whose type, and relationship, are const, and the shared kind
refuses such a ref with a not. A declaring operation addressed by href matches the
shared kind, so its meta is typed only when addressed by ref. The batch's own top-level
meta stays open, and so does each AtomicResult's.
Backed enums: x-enum-varnames / x-enum-descriptions¶
When a field constrains its value to a PHP backed enum (via In with an enum
class-string, e.g. the enum() field builder), the projected enum schema is hoisted
into a reusable named component (#/components/schemas/<Enum>) and $ref'd — so the
same enum shared by several fields is one component, not a repeated inline list. A
filter declared with enum() references the same component
from its filter[<key>] value, or from each item of a list filter's value. Each reference
carries the enum's backing type, string or integer, beside the $ref, with null
added for a nullable field, so a field reads the same type inline and hoisted
(typed references). The component lists every
case of the enum, whichever use the projector reaches first. A use that allows only some
cases, in() over a subset or an In scoped to one write with onCreate() or onUpdate(),
references the same component and narrows it with an enum of its values, in the order it
declares them, beside the $ref. OAS 3.1 reads the two as an intersection:
"status": { "type": "string", "enum": ["processing", "applied"], "allOf": [{ "$ref": "#/components/schemas/Status" }] }
A use listing every case, in any order, is the bare typed reference. A nullable use keeps its
enum on the $ref inside the anyOf. When a field declares two In constraints, say an
in() and one scoped to a write, that write's enum lists the values both allow, in the
order of the first one listing only some of them. Declaring them the other way round gives
the same schema, hoisted or inline, and the compiled validation schema allows the same values.
The same holds when the two don't share an enum: two enums, or an enum and plain values,
reference the component of the first enum declared, which is the one a write hydrates to,
narrowed to the values both allow. An In inside sequentially() takes the place of the
sequentially(), for the component and for hydration alike. A field declaring
enum(Status::class) and then enum(Visibility::class) references Status with an enum
of the values the two have in common.
Every other keyword the field's constraints set, such as a length, a pattern, a format or
a numeric bound, sits beside the $ref the same way, whether it was declared before or after
the in() or enum(), and the component holds only the enum. A narrowed reference raises
the document's x-generator stamp, since a generator reading only
the $ref would accept values the server refuses. That component carries:
x-enum-varnames— the enum case names, aligned to theenumvalues, so a code generator can emit a typed enum with meaningful member names rather than raw values.x-enum-descriptions— present when the enum implementsDescribedEnum: a per-case description list (and a markdownvalue → descriptiontable folded into the schemadescription), so each case documents its meaning.
An EnumDescriptionMode controls whether the projector emits the markdown table, the
structured x-enum-* extensions, or both (the default).
Profile-gated parameters: x-profile¶
Some query parameters are recognised by the runtime only when a JSON:API
profile is negotiated. The withCount parameter is the built-in case:
it is honoured only under the Countable profile. Rather than
advertise such a parameter unconditionally (which would mislead a client that has not
negotiated the profile), the projector marks it with x-profile: <profile-URI> —
naming the profile whose negotiation activates it. A tool that understands the extension
can surface the parameter conditionally; a tool that does not simply ignores an unknown
x- keyword. The parameter's description also states the profile requirement in prose,
so the constraint is never hidden behind the extension alone.
The description also says where each requested total lands. On an endpoint that accepts
_self_ it reads "Request withCount=_self_ to receive the collection total in the
top-level meta.total (also in meta.page.total when the collection is paginated)". On
one that accepts relation tokens it names the first, e.g. "Request a relation name, e.g.
withCount=comments, to receive that relation's total on each resource in
relationships.comments.meta.total".
withCount appears on every operation that renders resources and has something to count.
A collection read and a to-many's related read take _self_ when the collection is
countable, plus the countable relations of the type they render. A to-many's relationship
read takes _self_ alone. An operation rendering one resource takes that resource's
countable relations and never _self_, since there is no collection to total: a fetch-one,
a create or update answering with the resource, a to-one related read, and an action
answering with a resource. A to-one relationship read renders an identifier and takes none.
relatedQuery, under the Relationship Queries profile,
is marked the same way. It appears on every operation that renders resources of one type
with a relation it can address: a collection or single read, a create or update answering
with its resource, a related read over one type, and an action answering with a resource.
Its addressable relations are the type's relations over one type that a read renders, so
a polymorphic relation and a write-only one are left out, and a type with no other
relation takes no relatedQuery. A polymorphic related read renders several types and
takes none either. Delete, relationship reads and mutations, and actions answering
without a resource never take it.
Each type has one parameter component, #/components/parameters/<Type>RelatedQuery,
which every operation rendering that type references. Its deepObject schema is closed
and keyed by the addressable relations' names. A to-many's entry takes a sort, a string
whose pattern admits a comma-separated list of its related endpoint's sort keys, each
optionally prefixed with -, and defaults to that endpoint's declared order. A to-one's
takes no sort. Each entry's filter is a closed object whose members are the values its
related endpoint's filter[<key>] parameters take, with that endpoint's filter families
under patternProperties. An entry leaves out a sort or filter its relation has no
vocabulary for. The rQ shorthand is not documented.
RELATIONSHIP_COUNT_NOT_ALLOWED is offered on exactly those operations.
Sort families: x-sort-families¶
A sort family accepts keys that
can't be listed, so its keys can't join the sort enum. When an endpoint's sort
vocabulary has a family, the sort array's items become an anyOf: the enum of
fixed keys and their - forms, then one string pattern per family. The pattern
is ^-?, the escaped prefix, a dot and the family's suffix pattern. The array
schema also lists each family under x-sort-families, so a generator can offer a
typed helper rather than parse the pattern back:
"schema": {
"type": "array",
"items": {
"anyOf": [
{ "type": "string", "enum": ["title", "-title"] },
{ "type": "string", "pattern": "^-?value\\.(?:[a-z_]+)$" }
]
},
"x-sort-families": [
{ "prefix": "value", "suffixPattern": "[a-z_]+" }
]
}
An endpoint with no family keeps the plain enum, and a document whose endpoints
declare none carries no x-sort-families and keeps the lower contract stamp.
A deprecated family's entry adds "deprecated": true beside
its prefix and suffixPattern, and a described one its
"description". Both sit in the family's own entry so a prefix is never mistaken for an
exact key.
Sort descriptions: x-sort-descriptions¶
A described sort is documented the way a described enum value
is, as the projector's EnumDescriptionMode says. With Both, the default, the sort
parameter's description gains a markdown table of every key, families as
<prefix>.<suffix>, and the array schema maps each described exact key to its description
under x-sort-descriptions. Extensions emits only the map and Description only the
table:
{
"name": "sort",
"in": "query",
"description": "A comma-separated list of sort fields. Prefix a field with `-` for descending order.\n\n| Sort | Description |\n| --- | --- |\n| `title` | Alphabetical by title. |\n| `budget` | |",
"schema": {
"type": "array",
"items": { "type": "string", "enum": ["title", "-title", "budget", "-budget"] },
"x-sort-descriptions": { "title": "Alphabetical by title." }
},
"style": "form",
"explode": false,
"example": ["title"]
}
The map holds exact keys without the -, and only the described ones. A family's
description is in its x-sort-families entry. A sort parameter with no described key
carries neither.
List filters: x-filter-list¶
A filter declared with acceptsList() takes
its list as filter[<key>][]=a&filter[<key>][]=b. OAS has no way to say that a
parameter's name gains a [] suffix per member, so the array form is its own parameter,
named filter[<key>][], an array of the value schema with style: form and
explode: true, which is exactly the repeated pair a client sends. It carries
x-filter-list, naming the filter's key and whether the delimited form is accepted too:
{
"name": "filter[columns][]",
"in": "query",
"schema": { "type": "array", "items": { "type": "string" } },
"style": "form",
"explode": true,
"x-filter-list": { "key": "columns", "delimited": false }
}
A delimited list keeps its filter[<key>] parameter beside this one, shaped as before:
an array with the OAS style its delimiter spells and explode: false. An array-only list
has no filter[<key>] parameter, since a single string is refused. A generator should
read the two parameters as one filter keyed by the x-filter-list key and send the array
form, which works whether or not the list is delimited. A set filter without
acceptsList() documents only its delimited parameter.
WhereThroughIn always takes a
list, so it documents both parameters the same way with no acceptsList() call. When its
path ends on a relationship, the items take the related id's type or format.
Filter families: x-filter-families¶
A filter family accepts keys that
can't be listed, so it can't have a filter[<key>] parameter of its own. The families an
endpoint accepts share one filter parameter in deepObject style, whose object schema
holds one patternProperties entry per family: the escaped prefix, a dot and the family's
suffix pattern, matched to a string, or to a list of strings for a family that takes a
list. The object is left open, because the exact filters travel in their own parameters.
The schema lists each family under x-filter-families with its prefix, suffixPattern,
whether it takes a list and, for a list, whether it is delimited:
"schema": {
"type": "object",
"patternProperties": {
"^value\\.(?:.+)$": {
"anyOf": [
{ "type": "string" },
{ "type": "array", "items": { "type": "string" } }
]
}
},
"x-filter-families": [
{ "prefix": "value", "suffixPattern": ".+", "list": true, "delimited": true }
]
}
OAS does not define how deepObject carries an array, so x-filter-families is what a
generator should read: a list family takes filter[<prefix>.<suffix>][] once per member,
and a delimited one a single comma-separated string as well. A deprecated family's entry
adds "deprecated": true.
A described or exemplified family's
entry carries its description and its example, one full key and the value sent with it.
The parameter's description gains one line per described family, and its example holds
every family's example together:
"x-filter-families": [
{
"prefix": "value", "suffixPattern": "[a-z_]+", "list": false,
"description": "Matches a placeholder value.",
"example": { "value.cap": "10" }
}
]
An endpoint with no family has no filter parameter.
Deprecated sorts: x-deprecated-sorts¶
The sort array schema lists the exact keys declared deprecated
under x-deprecated-sorts, without the -. Each key stays in the items enum in both
directions, because a deprecated sort still works:
"schema": {
"type": "array",
"items": { "type": "string", "enum": ["name", "-name", "rank", "-rank"] },
"x-deprecated-sorts": ["name"]
}
A sort parameter with no deprecated key carries no x-deprecated-sorts, and a deprecated
family is flagged in x-sort-families rather than listed here.
Action safety: x-safety¶
A custom action's method doesn't say whether it changes anything. A search sent as POST
reads like a write. Action metadata that implements DeclaresActionSafety declares it
instead, through three methods that each return ?bool: readOnly(), destructive() and
idempotent(). The projector stamps the declared flags on the action's operation, one
object per operation, and leaves out any flag that returns null:
"/files/{id}/-actions/purge": {
"post": {
"operationId": "action.files.purge",
"x-safety": { "destructive": true, "idempotent": true }
}
}
An action that declares none of the three gets no x-safety, and CRUD operations never
get one. An action declared both read-only and destructive fails with a \LogicException.
Pagination strategy: x-paginator¶
Every key a paginator reads can be renamed (PagePaginator::make()->withPageKey('p')), and
so can its kind(). Key names alone therefore can't tell a client which strategy a
collection uses. Each built-in paginator stamps its page schema with the strategy and the
key that fills each of its roles:
"schema": {
"type": "object",
"properties": { "p": { "type": "integer" }, "size": { "type": "integer" } },
"x-paginator": { "strategy": "page", "keys": { "number": "p", "size": "size" } }
}
strategy |
keys roles |
|---|---|
page |
number, size |
offset |
offset, limit |
cursor |
after, before, size |
fixed |
number |
A MultiPaginator menu stamps its oneOf with
{"strategy": "multi", "default": "<kind>"}, where default is the kind the server
picks when a request names none. Each arm carries its child's own x-paginator beside the
kind const that selects it. A custom paginator that stamps nothing is left to whatever a
generator infers from its key names.
Each built-in member also carries the paginator's default and, for the page size, its cap
as maximum. See In OpenAPI on the pagination page.
Queried linkage for MCP servers: x-mcp¶
A queriedBy() relation renders its
linkage only on its own endpoints, never as data in a parent's document. Its relationship
read, GET /{type}/{id}/relationships/{rel}, and its related read, GET /{type}/{id}/{rel},
each say so to an MCP server built from the document:
json-api-mcp reads it to point the parent read
tool's slot for the relation at whichever of the two reads the relation exposes, rather
than at a data member that never arrives. No other operation carries it, and a relation
without queriedBy() never does.
An x-mcp your adapter declares for either read, keyed fetchRelationship.<rel> or
fetchRelated.<rel> among the operation extensions, merges with it:
- an object keeps its members and gains
parentLinkage: false, unless it setsparentLinkageitself, which wins; false, which leaves the operation out of the tools, and any other value that isn't an object stay as declared.
Your own extensions on operations, paths, parameters and responses¶
Operation, PathItem, Parameter and Response each carry a map of vendor extensions,
emitted after their standard members. withExtension() sets one, withExtensions()
merges several, and extension() reads one back. A name without the prefix gets it, the
way Schema::withExtension() does it, so withExtension('feature', 'agency') emits
x-feature: agency. A map passed to a constructor's extensions: argument must already
use x- keys. The x-oai- and x-oas- prefixes are reserved by the OpenAPI Initiative,
and both forms throw an \InvalidArgumentException for them.
extensions() returns the whole map, keyed x-…. Info and Schema have it too.
A document decorator can tag a feature-gated operation directly:
$item = $document->paths->items['/agencies'];
$item = $item->withOperation('get', $item->operations['get']->withExtension('feature', 'agency'));
$document = $document->withPaths($document->paths->with('/agencies', $item));
To declare them on the type instead, have its metadata implement
DeclaresOperationExtensions. The projector stamps extensions() on every operation it
emits for the type: the CRUD operations, its related and relationship endpoints, and its
custom actions. It then merges operationExtensions($operation) over that for each CRUD
operation, so the operation's value wins on a shared key. Metadata that doesn't implement
the interface projects as before. A framework integration builds the two maps from its
own resource configuration.
To target one operation that is not CRUD, such as a single related endpoint, implement
DeclaresNamedOperationExtensions as well or instead. Its namedOperationExtensions()
returns a map keyed by operation name, the same names
operationExamples() and operationScopes() use: fetchCollection,
fetchOne, create, update, delete, or fetchRelated, fetchRelationship,
updateRelationship, addRelationship or removeRelationship followed by a dot and the
relation name.
public function namedOperationExtensions(): array
{
return [
'fetchRelated.agencies' => ['feature' => 'agency'],
'fetchRelationship.agencies' => ['feature' => 'agency'],
];
}
The projector layers the sets for each operation in this order, a later one winning on a
shared key: the type-wide extensions(), then operationExtensions() for a CRUD
operation, then the set named for the operation. Every layer is normalised to x- keys
before the merge, so feature and x-feature are the same key. A name the type does not
expose fails the projection with an \InvalidArgumentException. Actions have no name in
this map, since they declare their own as below. OperationKey::tryFromName() parses a
name, so an integration can check its configuration before it projects.
An action declares its own with action metadata that implements DeclaresActionExtensions,
whose extensions() returns the map. It lands on that action's operation only, merged over
the type-wide set, so the action's value wins on a shared key. A link to an
Arazzo workflow is the usual case:
public function extensions(): array
{
return ['workflows' => ['source' => 'workflows.arazzo.yaml', 'workflowId' => 'purgeFile']];
}
A declared x-safety wins over an extension of the same name.
Changing one member without losing the rest¶
Change a generated value object through its withers rather than rebuilding it with
new. Every member of Operation, PathItem, Response and Parameter has a
with<Member>() wither (withDescription(), withResponses(), withParameters(),
withDeprecated() and so on), and each returns a copy with every other member intact,
extensions included. A new Operation(...) copies only the arguments you pass, so it drops
whatever an earlier decorator set.
The collection members also take one item at a time:
| Value object | Single-item wither | Replaces |
|---|---|---|
Operation |
withResponse($status, $response) |
the response for that status |
Operation, PathItem |
withParameter($parameter) |
the parameter with the same name and in, in place (a Reference is appended) |
PathItem |
withOperation($method, $operation) |
the operation for that method |
Response, RequestBody |
withMediaType($mediaType, $media) |
that media type's body |
Response |
withHeader($name, $header) |
that header |
Components |
withSchema(), withResponse(), withParameter(), withRequestBody(), withHeader(), withSecurityScheme() |
the component with that name |
OpenApi |
withPath($path, $item) |
that path |
A decorator that documents rate limiting on an operation another decorator already tagged:
$item = $document->paths->items['/agencies'];
$operation = $item->operations['get']
->withResponse('429', Reference::to('responses', 'TooManyRequests'))
->withDescription('Limited to 60 requests a minute.');
$document = $document
->withPath('/agencies', $item->withOperation('get', $operation))
->withComponents($document->components->withResponse('TooManyRequests', new Response('Too Many Requests')));
x-feature survives both steps. Info, MediaType, RequestBody, Tag, Server and
the OpenApi document carry withers for the members a decorator usually changes.
Serving a decorated document (for adapter authors)¶
An adapter that lets applications change the served document per request (a servers
entry per host, operations hidden for one tenant) builds on four classes in
haddowg\JsonApi\OpenApi\Serve. They take strings and stdClass trees and know nothing
about HTTP messages, so the decorator interfaces, the controller and the cache location
stay in the adapter. Using them keeps every adapter pruning and tagging the same way.
At warm-up, wrap the built document in a ServeArtifact and encode it beside the JSON:
$artifact = ServeArtifact::of($document);
$codec = new ServeArtifactCodec(['acme/json-api-adapter']);
file_put_contents("$dir/default.json", $json = $document->toJsonString(true));
file_put_contents("$dir/default.hash", EntityTag::hash($json));
file_put_contents("$dir/default.serve", $codec->encode($artifact));
On a request, decode it, run the decorators, then prune:
$artifact = $codec->decode($bytes) ?? ServeArtifact::of($factory->build());
$document = $artifact->document;
foreach ($decorators as $decorator) {
$document = $decorator->decorate($document, $request);
}
$body = json_encode($artifact->prune($document), JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
decode() returns null when the bytes are unreadable or were written by another
installed version of this package or of a package named in the codec's first argument,
so stale artifacts left behind by a deploy fall back to a fresh build. Decoding allows
only the OpenAPI value objects, stdClass and enums. If an example(), a default or an
extension value holds another object, encode() throws UnserializableValue unless its
class is passed in the second argument, allowedClasses. It's a LogicException whose
$class names the rejected class, so an adapter can report it without parsing the message.
prune() drops what the decorators orphaned: path items with no operations left, tags no
remaining operation uses, and components the undecorated paths reached that nothing
reaches now, following $refs and discriminator mappings. A component the undecorated
document never referenced, or one a decorator added, is kept along with everything it
references. Security schemes are never pruned. A relationship whose related type lost
its endpoints keeps its schema, since the parent still renders that linkage.
EntityTag builds the ETag:
EntityTag::hash($bytes)for the stored artifact when no decorator runs, or for the final body.EntityTag::keyed($artifactHash, $keys)when every decorator can give a cache key for the request.$keyslists[decorator class, key]pairs in the order the decorators run, and the tag can be checked before anything is decoded. If any decorator has no key, fall back to the body hash, because a partial key would let two different bodies share a tag.EntityTag::matches($etag, $ifNoneMatch)compares against the rawIf-None-Matchheader value. It matches weakly, so aW/tag from a compressing CDN still matches, and*matches anything.
Related pages¶
- Fields / field types — the builder surface
describedAs()/example()extend, and how each field type projects. - Constraints — the validation vocabulary the
SchemaProjectormaps to JSON Schema keywords (and the lossy-degradation cases). - Filters — a filter's value schema, its generated description, the
Range/DateRangedeepObjectparameter, andDescribesQueryParameterfor a custom filter's own structured parameter shape. - Profiles / Countable profile — the profile
mechanism behind the
x-profileextension. - Atomic Operations — the extension whose request/result
components and
POSTpath the projector adds when it is enabled. - The Symfony bundle's OpenAPI docs — serving the document, configuration, the UI, and decorating the generated document.