Oscar
Oscar

Reputation: 2345

In OpenAPI, can I use a regular schema component as a parameter?

I have an endpoint defined in my API that takes a path parameter.

The valid values for that parameter are already expressed as an enum, which I've defined as a schema component and used in a response.

Two questions:

  1. If you can just use a reference to that schema component as the parameter, why ever set up dedicated parameter components instead of using a generic schema component that you can re-use anywhere?
  2. If you should use parameters instead of generic schemas, can you create a parameter component that refers to a schema component? I can't find any syntax to do this that passes validation.

I'd paste my definitions here but I can't find any formatting option that doesn't make a hideous mess.

Upvotes: 2

Views: 1025

Answers (1)

Helen
Helen

Reputation: 97717

If you can just use a reference to that schema component as the parameter, why ever set up dedicated parameter components instead of using a generic schema component that you can re-use anywhere?

Parameter definitions have additional attributes not present in schemas, such as the parameter location in the request (in: path, in: query, etc.), serialization method for array and object values, and others. A schema is just one of the parameter attributes, but a schema alone does not provide enough information to effectively describe a parameter.

can you create a parameter component that refers to a schema component?

Yes. Parameters have a schema, it can be an inline schema or a $ref:

paths:
  /something/{role}:
    get:
      parameters:
        - $ref: '#/components/parameters/role'
...

components:
  parameters:
    role:
      in: path
      name: role
      required: true
      schema:
        $ref: '#/components/schemas/UserRole'  # <-----

  schemas:
    UserRole:
      type: string
      enum: [user, admin]

Upvotes: 2

Related Questions