如何在 OpenAPI/Swagger 中指定字段是可选的还是必需的? [英] How to specify if a field is optional or required in OpenAPI/Swagger?

查看:272
本文介绍了如何在 OpenAPI/Swagger 中指定字段是可选的还是必需的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 OpenAPI/Swagger 中定义字段是可选的还是必需的,默认值是什么?

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

推荐答案

默认情况下,模型中的字段是可选的,除非您将它们放在 required 列表中.下面是一个示例 - idcategory 是可选字段,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

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

如果这是请求正文的模型,您可能还需要将正文本身标记为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 中指定字段是可选的还是必需的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆