问题描述
如何在 OpenAPI/Swagger 中定义字段是可选的还是必需的,默认值是什么?
How to I define in OpenAPI/Swagger if a field is optional or required and what is the default?
推荐答案
默认情况下,模型中的字段是可选的,除非您将它们放在 required
列表中.下面是一个示例 - id
、category
是可选字段,name
是必需的.请注意,required
不是字段的属性,而是对象本身的属性 - 它是必需属性的列表.
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
如果这是请求正文的模型,您可能还需要将正文本身标记为required
:
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:
...
要指定可选字段的默认值,您可以使用 default
属性.下面是一个例子:
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
这篇关于如何在 OpenAPI/Swagger 中指定字段是可选的还是必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!