Reusing OpenAPI components: Within a file, across files, and where to stop
The fastest way to make an OpenAPI document unmaintainable is to copy and paste. The same error object written out in forty responses, the same limit parameter in twenty operations: sooner or later one copy changes and the others do not, and the document no longer describes one API but several slightly different ones. components and $ref exist to prevent that. This post shows what can be reused, how references work within a file and across files, and where reuse stops being a good idea.
What components can hold
| Section | Holds | Referenced from |
|---|---|---|
schemas | Data shapes: Order, Error | Request and response bodies, other schemas |
parameters | Path, query, header and cookie parameters | Operations and paths |
responses | Whole responses, such as a shared 404 | The responses of an operation |
requestBodies | Whole request bodies | Operations |
headers | Response headers, such as rate limit headers | Responses |
examples | Named examples | Media types and parameters |
securitySchemes | How a caller authenticates | security |
Nothing in components has any effect until something refers to it.
Reuse in practice
Define the pieces once:
components:
parameters:
Limit:
name: limit
in: query
description: How many items to return
schema:
type: integer
minimum: 1
maximum: 100
default: 20
schemas:
Error:
type: object
required: [code, message]
properties:
code:
type: string
message:
type: string
responses:
NotFound:
description: The resource does not exist
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
Unauthorized:
description: The credential is missing or invalid
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
and refer to them wherever they apply:
paths:
/orders:
get:
parameters:
- $ref: "#/components/parameters/Limit"
responses:
"200":
description: A page of orders
"401":
$ref: "#/components/responses/Unauthorized"
/orders/{orderId}:
get:
responses:
"200":
description: The order
"401":
$ref: "#/components/responses/Unauthorized"
"404":
$ref: "#/components/responses/NotFound"
The gain is larger than fewer lines. Every list endpoint now pages the same way, and every 401 has the same body, which is what a client developer hopes for and rarely gets.
References across files
A $ref is an address, and the address can be another file:
# openapi/orders.yaml
components:
schemas:
Order:
$ref: "../schemas/order.yaml"
responses:
NotFound:
$ref: "../shared/responses.yaml#/NotFound"
This is how an organization shares one error model, one pagination scheme and one set of security schemes between several APIs: the shared pieces live in their own files, and each API refers to them.
Two practical points:
- Tools must be able to follow the references. In APIGit, the editor's preview and the Governance view follow references to other files of the repository, including changes you have not committed yet, and a published document resolves them for its readers.
- Some consumers want one file. A gateway import or a code generator often cannot follow file references. Bundle before handing the document over:
apigit bundle openapi/orders.yaml -o dist/orders.yaml
The command writes one file with every external reference resolved. Published documents on APIGit offer the bundled file for download as well, one per spec.
Where reuse goes wrong
Sharing a schema between request and response. A User used for both POST /users and GET /users/{id} ends up with id and createdAt in the request, where the client cannot set them. Either mark such properties readOnly: true, or keep a UserInput and a User.
One schema for things that only look alike. A billing address and a shipping address have the same fields today. If they are different concepts, a shared Address couples two parts of the API that will want to change separately.
Components nobody can find. Response1, Model_2, inline_object. Name components for what they are (Order, NotFound, Limit), in one consistent style.
Splitting too far. A property that is used once does not need its own component, and a schema that is spread over six files is harder to review than one that is a little long. Extract something when it is used the second time.
Changing a shared component casually. A change to Error is a change to every operation that uses it. Before merging one, compare the versions:
apigit breaking origin/main HEAD openapi/orders.yaml
It lists the changes that can break a client, across everything the document refers to.
A reasonable starting set
For a new API, these are worth defining on the first day: an Error schema, the 400, 401, 403, 404 and 429 responses, the pagination parameters, the security schemes, and the identifiers used in paths. That set alone removes most of the repetition in a typical document.
Related: The structure of an OpenAPI document and oneOf, allOf and anyOf.