OpenAPI Plugin
The OpenAPI Specification Plugin (OAS) builds on top of the JsonApi4j plugin system to provide automatic, always-in-sync API documentation. It observes registered resources, relationships, and operations and translates them into an OpenAPI-compliant model. Because the specification is derived directly from the same metadata used at runtime, it accurately reflects the actual behavior of your JSON:API endpoints without requiring manual maintenance.
To enable the plugin, add the following dependency:
<dependency>
<groupId>pro.api4</groupId>
<artifactId>jsonapi4j-oas-plugin</artifactId>
<version>${jsonapi4j.version}</version>
</dependency>
If you’re using Spring Boot or Quarkus, the plugin is auto-configured with default values.
Accessing the Specification
JsonApi4j generates an io.swagger.v3.oas.models.OpenAPI model and exposes it through a dedicated endpoint.
By default, the specification is available at /jsonapi/oas. It supports an optional format query parameter (json or yaml) — defaulting to json if not provided.
The document the sample app produces is published as a live OpenAPI example — regenerated on every build and asserted by the test suite, so it is what the plugin emits today rather than what it emitted once.
Out of the box, JsonApi4j generates all schemas and operations automatically. JSON:API parameters, request/response schemas, and error models are all included.
Enriching the Specification
To add metadata beyond what the framework generates automatically (e.g., info, securitySchemes), you have two options:
Via configuration properties — set OpenAPI metadata in application.yaml / application.properties. See the Spring Boot sample config or Quarkus sample config for reference.
Via annotations — place these on your domain and operation classes for fine-grained control:
| Annotation | Placement | Purpose |
|---|---|---|
@OasResourceInfo |
On Resource class |
Declares the attributes class, the singular resource name, and how the resource’s identifier is described and exemplified |
@OasRelationshipInfo |
On ToOneRelationship or ToManyRelationship class |
Declares the resource types the relationship links to, and the type of the meta its resource linkage carries |
@OasOperationInfo |
On operation class or individual operation methods | Overrides the generated operation summary, description and request body type, and declares sortable fields, filters, pagination styles, application-specific parameters and OAuth2 security requirements |
Example:
@JsonApiResource(resourceType = "users")
@OasResourceInfo(
resourceNameSingle = "user",
attributes = UserAttributes.class,
resourceIdDescription = "User unique identifier",
resourceIdExample = "3"
)
public class UserResource implements Resource<UserDbEntity> {
// ...
}
resourceIdDescription and resourceIdExample are declared once and reach every place that resource’s identifier
appears — the {id} path parameter of each operation acting on one instance, and the id member of the resource
schema. They belong to the resource rather than to an operation because every operation asks for the same
identifier; declaring them per operation is what lets one endpoint carry an example and the next one not. Request
bodies keep their own id wording, which says whether the id must match the path or may be omitted, since that is
about the operation.
@JsonApiResourceOperation(resource = UserResource.class)
public class UserOperations implements ResourceOperations<UserDbEntity> {
@OasOperationInfo(summary = "List all users", description = "Returns a paginated list of users")
@Override
public PaginationAwareResponse<UserDbEntity> readPage(JsonApiRequest request) {
// ...
}
}
Using springdoc Instead of the Built-in Endpoint
If your Spring Boot app already serves an OpenAPI document through springdoc, feed it the JsonApi4j customizers
rather than running both endpoints. springdoc’s OpenApiCustomizer declares the same customise(OpenAPI) method
the framework’s customizers do, so one bean is the whole integration:
@Bean
public OpenApiCustomizer jsonApi4jOpenApiCustomizer(JsonApi4j jsonApi4j) {
return openApi -> OasDocument.customizers(jsonApi4j).forEach(customizer -> customizer.customise(openApi));
}
OasDocument.customizers(...) returns them in the order they must be applied, so the document springdoc publishes
matches the one the built-in endpoint would. Everything each customizer needs — the registries, the root
configuration, the OAS configuration — comes off the JsonApi4j bean.
To build a document without springdoc, OasDocument.generate(jsonApi4j) returns a finished OpenAPI.
See the Spring Boot sample app for the complete configuration.
Request Bodies
Every write operation gets a request body derived from what JSON:API prescribes for it — nothing to declare:
| Operation | Request body schema |
|---|---|
POST /{type} |
<Type>CreateRequestDoc — id optional, so the client may generate it |
PATCH /{type}/{id} |
<Type>UpdateRequestDoc — id required |
PATCH /{type}/{id}/relationships/{name} (to-one) |
ToOneRelationshipRequestDoc — linkage, nullable to clear |
POST/PATCH/DELETE /{type}/{id}/relationships/{name} (to-many) |
ToManyRelationshipsRequestDoc — array of linkage |
DELETE /{type}/{id} |
none |
<Type> is the resource type capitalized, so users yields UsersCreateRequestDoc. The relationship bodies carry no
<Type> prefix because they are pure resource linkage — {"data": {"id": …, "type": …}} — which looks the same
whatever resource it points at, so one schema serves them all. The exception is a relationship declaring
@OasRelationshipInfo(resourceLinkageMetaType = …): its linkage carries a typed meta, which makes the body specific
to that relationship, so it gets <Type><Relationship>ToOneRelationshipRequestDoc /
<Type><Relationship>ToManyRelationshipsRequestDoc instead. The same typed identifier is reused in responses, so a
client sees one shape for the linkage whichever direction it travels.
Every resource schema pins its type to the single value JSON:API allows for it — UsersResource.type is
enum: ["users"], not an open string. That is the same rule the framework enforces at runtime by answering a
mismatched request body with a 409, so the document and the server now say the same thing. It also makes included
resolvable: the union of resource schemas a document may carry declares a discriminator on type, mapping each
resource type to the schema describing it, so a generated client deserializes each member into its concrete class
instead of handing the caller a union to switch on.
These are separate from the response documents on purpose: a request carries no links or included, and id is
optional on create but mandatory on update. To document a body the framework cannot derive, set
@OasOperationInfo(payloadType = YourPayload.class) — the declared type replaces the derived one and its schema is
registered automatically.
Required Attributes Are a Create-Only Promise
@Schema(requiredMode = REQUIRED) on an attribute says what a create must carry, and that is the one place it is
published — <Type>CreateAttributes. The other two forms require nothing:
| Schema | Referenced by | required |
|---|---|---|
<Type>CreateAttributes |
POST /{type} |
as the resource declared it |
<Type>UpdateAttributes |
PATCH /{type}/{id} |
nothing — PATCH is a partial update, so a client sends only what it is changing |
<Type>Attributes |
every response | nothing — see below |
That is not a weakening — it is the only honest reading. A response cannot promise an attribute is present:
- an attribute with no value is not serialized at all — true of every application, with no plugins involved;
- sparse fieldsets let a client ask for a subset (
?fields[users]=fullName); - access control withholds what the caller may not see.
Each of those produces a response that a required list copied from the attributes class would reject. A generated
client would model the attribute as non-nullable and fail to read a response the server is entitled to send, and a
strict response validator would reject it — which is exactly what used to happen. The same reasoning is what separates
create from update: requiring an attribute on PATCH would reject a partial update the framework accepts.
Each reason is described by whoever owns it, so a document never mentions a plugin the application does not run. The
framework’s own pass states the first line only; the sparse fieldsets customizer adds “A client can narrow what is
returned with fields[users]“, and access control adds what it withholds. Turn both plugins off and the attributes
schema says just the one sentence.
Each form is published only for the operation that uses it: a read-only resource gets none of the write forms, and a
resource with only an update gets only <Type>UpdateAttributes. On a read-only resource the annotation therefore
publishes nothing at all.
One thing required is not: enforced. The framework does not reject a create for a missing attribute on the strength
of requiredMode — that is what validateCreate is for. So the annotation is a claim about your own operation, and it
is worth keeping the two in step: the sample app declares fullName and email required and its validateCreate
checks both. A required the validator does not enforce is a document that promises something the server does not do.
Where the Access Control plugin guards an individual attribute, the response schema also says so on that attribute —
“Absent from the response unless the caller qualifies — requires the scopes users.sensitive.read” — using the
requirement’s own description() where one was given. Absence alone tells a client nothing; naming the requirement
turns it into something they can act on.
Operation Ids
Every operation gets an operationId, derived from what it does and what it acts on:
get-all-users create-single-user
get-single-user update-single-user
get-user-relatives-relationship delete-user-relatives-relationship
Client generators name their methods after it, so it is part of your published contract — treat a rename as a breaking change.
Your resourceType stays exactly as you declared it, plural as JSON:API asks: it is what paths, tags, schema names
and the type member are built from, and get-all-users uses it as-is. A singular form appears only where the plural
would read wrong — in the ids of operations acting on one resource (get-single-user) and in the generated summaries
and descriptions (“Retrieves user details by resource id.”). The plugin guesses it from the resource type
(countries → country, addresses → address, status → status, left alone when unrecognised). Set
@OasResourceInfo(resourceNameSingle = …) on the resource whenever that guess reads wrong. There is no override for
the plural — that is the resource type itself.
Query Parameters
The framework parses sort, page[…] and fields[…] for every request, but only the operation can act on them —
so the document publishes what the operation declares, never what the request layer merely accepts.
| Parameter | Published when |
|---|---|
include |
the resource has relationships with a read operation |
fields[TYPE] |
the sparse fieldsets plugin is enabled and the operation returns resources |
page[cursor] |
the operation is paginated — the default |
page[limit], page[offset] |
@OasOperationInfo(pagination = {CURSOR, LIMIT_OFFSET}) |
sort |
@OasOperationInfo(sortableFields = {"fullName", "email"}) |
filter[…] |
@OasOperationInfo(filters = {@Filter(name = "region")}) |
@OasOperationInfo(
sortableFields = {"fullName", "email"},
pagination = {PaginationStyle.CURSOR, PaginationStyle.LIMIT_OFFSET},
filters = {
@Filter(name = "id", example = "3"),
@Filter(name = "region", description = "Filter by region", example = "Asia")
}
)
public PaginationAwareResponse<UserDbEntity> readPage(JsonApiRequest request) { … }
sortableFields becomes the parameter’s allowed values in both directions — fullName, -fullName, email,
-email. Pagination defaults to cursor alone, so an operation that does not read page[limit] never advertises it.
A filter is declared by its dimension, not by its parameter name: the framework spells it filter[id], makes it
optional and multi-valued as JSON:API defines filters, and bounds it with validation.maxElementsInFilterParam.
Every multi-valued parameter is published as style: form, explode: false, so a generated client sends
?include=citizenships,placeOfBirth — the form JSON:API asks for. Saying nothing would not be neutral: OpenAPI’s
default for a query parameter is a repeated key (?include=a&include=b). The request layer accepts either form, so
this is about what the document promises rather than what the server takes.
Application-specific Parameters
@OasOperationInfo(parameters = …) documents parameters the framework cannot derive — the application’s own query
parameters, which reach an operation through JsonApiRequest#getCustomQueryParams().
@OasOperationInfo(
parameters = @Parameter(name = "tenant", description = "Tenant the request is scoped to", required = false)
)
Naming a parameter the framework already generates — id, include, sort, page[…], fields[…], filter[…] —
contributes a description and example to it and nothing else, so the generated schema keeps the constraints it took
from the running configuration. For the id, prefer @OasResourceInfo: it reaches every operation at once.
One