Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to specify if a field is optional or required in OpenAPI/Swagger?

How to I define in OpenAPI/Swagger if a field is optional or required and what is the default?

question from:https://stackoverflow.com/questions/40113049/how-to-specify-if-a-field-is-optional-or-required-in-openapi-swagger

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

1 Reply

0 votes
by (71.8m points)

By default, fields in a model are optional unless you put them in the required list. Below is an example - id, category are optional fields, name is required. Note that required is not an attribute of fields, but an attribute of the object itself - it's a list of required properties.

type: object
required:  # List the required properties here
  - name
properties:
  id:
    type: integer
    format: int64
  category:
    $ref: '#/definitions/Category'
  name:
    type: string
    example: doggie

Ref: https://github.com/swagger-api/swagger-codegen/blob/master/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml#L658

If this is the model for the request body, you'll probably also need to mark the body itself as required:

# swagger: '2.0'

parameters:
  - in: body
    name: body
    required: true  # <----
    schema:
      $ref: '#/definitions/Pet'

# openapi: 3.0.1

requestBody:
  required: true  # <----
  content:
    ...

To specify the default value of optional fields, you can use the default attribute. Here is an example:

type: object
properties:
  huntingSkill:
    type: string
    description: The measured skill for hunting
    default: lazy

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...