Component Section
Often, multiple API operations have some common parameters or return the same response structure. To avoid code duplication, you can place the common definitions in the global components section and reference them using $ref. In the example below, duplicate definitions of a User object are replaced with a single component and references to that component. Before:
paths:
/users/{userId}:
get:
summary: Get a user by ID
parameters:
...
responses:
'200':
description: A single user.
content:
application/json:
schema:
type: object
properties:
id:
type: integer
name:
type: string
/users:
get:
summary: Get all users
responses:
'200':
description: A list of users.
content:
application/json:
schema:
type: array
items:
type: object
properties:
id:
type: integer
name:
type: stringAfter:
Components Structure
components serve as a container for various reusable definitions – schemas (data models), parameters, responses, examples, and others. The definitions in components have no direct effect on the API unless you explicitly reference them from somewhere outside the components. That is, components are not parameters and responses that apply to all operations; they are just pieces of information to be referenced elsewhere. Under components, the definitions are grouped by type – schemas, parameters and so on. The following example lists the available subsections. All subsections are optional.
Each subsection contains one or more named components (definitions):
The component names can consist of the following characters only:
Examples of valid names:
The component names are used to reference the components via $ref from other parts of the API specification:
For example:
An exception are definitions in securitySchemes which are referenced directly by name (see Authentication).
Components Example
Below is an example of components that contains reusable data schemas, parameters and responses. Other component types (links, examples, and others) are defined similarly.
Externally Defined Components
Individual definitions in components can be specified either inline (as in the previous example) or using a $ref reference to an external definition:
Differences From OpenAPI 2.0
OpenAPI 2.0 had separate sections for reusable components – definitions, parameters, responses and securityDefinitions. In OpenAPI 3.0, they all were moved inside components. Also, definitions were renamed to schemas and securityDefinitions were renamed to securitySchemes (note the different spelling: schemAs vs securitySchemEs). The references are changed accordingly to reflect the new structure:
References
Last updated