You might have noticed that our specification is not very DRY – we are repeatedly specifying common responses like the 500 Internal Error. Therefore, before we learn how to specify URL parameters and our security schemes, let's first see how we can use the components root property to define common entities in a single location, and reference it throughout the OpenAPI specification. We will do this for our Create User object, as well as all our responses.
Let's start by adding the following components section as a root property to our specification:
components:
schemas:
Profile:
title: User Profile
type: object
properties:
bio:
type: string
summary:
type: string
name:
type: object
properties:
first:
type: string
middle:
type: string
last:
type: string
additionalProperties: false
We can now refer to this Profile schema component anywhere in our specification using the reference '#/components/schemas/Profile'. In other words, we can shorten our definition for the requestBody property of our Create User endpoint to the following:
requestBody:
description: The New User object
required: true
content:
application/json:
schema:
properties:
email:
type: string
format: email
digest:
type: string
pattern: ^\\$2[aby]?\\$\\d{1,2}\\$[.\\/A-Za-z0-9]{53}$
profile:
$ref: '#/components/schemas/Profile'
additionalProperties: false
required:
- digest
Let's go through another example. Currently, our GET /salt endpoint can respond with a 200 response:
paths:
/salt:
get:
summary: ...
description: ...
parameters: ...
responses:
'200':
description: Salt Retrieved
content:
text/plain:
schema:
type: string
...
We can pull this response out and define it as a component:
components:
schemas:
Profile:
title: User Profile
...
responses:
SaltRetrieved:
description: Salt Retrieved
content:
text/plain:
schema:
type: string
And just like before, we can reference the SaltRetrieved response component by reference:
paths:
/salt:
get:
summary: ...
description: ...
parameters: ...
responses:
'200':
$ref: '#/components/responses/SaltRetrieved'
...
Having gone through two examples, you should now try to pull out as many common components as you can. Once you're done, check the code bundle to see our implementation.