Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

Swagger/OpenAPI - use $ref to pass a reusable defined parameter

Let's say I've got a parameter like limit. This one gets used all over the place and it's a pain to have to change it everywhere if I need to update it:

parameters:
    - name: limit
      in: query
      description: Limits the number of returned results
      required: false
      type: number
      format: int32

Can I use $ref to define this elsewhere and make it reusable? I came across this ticket which suggests that someone wants to change or improve feature, but I can't tell if it already exists today or not?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This feature already exists in Swagger 2.0. The linked ticket talks about some specific mechanics of it which doesn't affect the functionality of this feature.

At the top level object (referred to as the Swagger Object), there's a parameters property where you can define reusable parameters. You can give the parameter any name, and refer to it from paths/specific operations. The top level parameters are just definitions and are not applied to all operations in the spec automatically.

You can find an example for it here - https://github.com/swagger-api/swagger-spec/blob/master/fixtures/v2.0/json/resources/reusableParameters.json - even with a limit parameter.

In your case, you'd want to do this:

# define a path with parameter reference
/path:
   get:
      parameters:
         - $ref: "#/parameters/limitParam"
         - $ref: "#/parameters/offsetParam"

# define reusable parameters:
parameters:
   limitParam:
      name: limit
      in: query
      description: Limits the number of returned results
      required: false
      type: integer
      format: int32
   offsetParam:
      name: offset
      in: query
      description: Offset from which start returned results
      required: false
      type: integer
      format: int32

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...