OpenAPI $ref reusable parameter
Using $ref
to reference a reusable parameter in an OpenAPI specification is a key practice for keeping your API definitions clean, consistent, and maintainable. This method centralizes common parameters, like Authorization
headers or a userId
path parameter, in a single location and allows you to reference them from any endpoint.
How to Define and Reference a Reusable Parameter
The process involves two main steps:
- Define the Parameter: You must first define the reusable parameter within the
components
section of your OpenAPI document. Thecomponents
section is the central location for all reusable objects, including schemas, responses, and parameters. - Reference the Parameter: You then use the
$ref
keyword to reference this defined parameter from any path or operation where it's needed.
Step-by-Step Example (OpenAPI 3.0/3.1)
Let's say you have an API where multiple endpoints require a userId
in the path and a page
query parameter for pagination.
1. Define the Parameters in components
In your openapi.yaml
file, add a parameters
section under components
:
openapi: 3.0.0
info:
title: My API
version: 1.0.0
paths:
/users/{userId}:
get:
summary: Get a user by ID
parameters:
- $ref: '#/components/parameters/UserId'
/posts:
get:
summary: Get a list of posts
parameters:
- $ref: '#/components/parameters/PageParameter'
- $ref: '#/components/parameters/PageSize' # Another reusable parameter
- name: sort
in: query
description: Field to sort posts by
schema:
type: string
components:
parameters:
UserId:
name: userId
in: path
required: true
schema:
type: string
format: uuid
description: The unique ID of the user.
PageParameter:
name: page
in: query
description: The page number for pagination.
required: false
schema:
type: integer
default: 1
minimum: 1
PageSize:
name: pageSize
in: query
description: Number of items per page.
required: false
schema:
type: integer
default: 10
minimum: 1
maximum: 100
2. Reference the Parameters
Once defined, you can use $ref
to point to the reusable parameter. The syntax is #/components/parameters/ParameterName
.
In the example above:
- The
/users/{userId}
endpoint references theUserId
parameter. - The
/posts
endpoint references both thePageParameter
andPageSize
parameters.
This approach ensures consistency. If you ever need to change the description, type, or format of the userId
parameter, you only have to do it in one place (components
), and the changes will automatically propagate to every endpoint that references it.