Components 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:
After:
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:
This way you can define local “aliases” for external definitions that you can use instead of repeating the external file paths in all references. If the location of the referenced file changes, you only need to change it in one place (in components
) instead of in all references.
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: schem_A_s
vs securitySchem_E_s
). The references are changed accordingly to reflect the new structure:
References
Did not find what you were looking for? Ask the community
Found a mistake? Let us know