5

Learning about REST APIs and am following https://apihandyman.io/writing-openapi-swagger-specification-tutorial-part-2-the-basics/.

The API can receive two parameters: username and bla, but only username is required by using the required keyword. This makes sense to me.

The API will return firstname, lastname, and username, but only username is required by using the required keyword. This does not make sense to me. Does the lack of the required keyword indicate that the other two might sometimes not be required? What influences whether they are or are not?

paths:
  /persons/{username}:
    get:
      summary: Gets a person
      description: Returns a single person for its username.
      parameters:
        - name: username
          in: path
          required: true
          description: The person's username
          type: string
        - name: bla
          in: query
          description: bla bla bla
          type: string
      responses:
        200:
          description: A Person
          schema:
            required:
              - username
            properties:
              firstName:
                type: string
              lastName:
                type: string
              username:
                type: string
        404:
          description: The Person does not exists.
4

1 回答 1

8

你的解释是正确的。如果响应对象的属性列在required属性列表中,则必须存在于响应对象中才能使其有效,这与required参数对象中的字段非常相似。响应中是否包含非必需属性由应用程序的业务逻辑决定。

一些更多信息,其中包含指向以下规范相关部分的指针:

  • 响应对象的属性列表的语义required被定义为OpenAPI 规范的模式对象部分的一部分。那里说模式对象“基于 JSON 模式规范草案 4 并使用它的预定义子集”。

  • 在JSON Schema Validationrequired规范的validation 关键字的相应部分中,其语义定义如下:

5.4.3. 必需的

5.4.3.1。有效值

这个关键字的值必须是一个数组。这个数组必须至少有一个元素。此数组的元素必须是字符串,并且必须是唯一的。

5.4.3.2。成功验证的条件

如果对象实例的属性集包含此关键字数组值中的所有元素,则对象实例对该关键字有效。

  • 您将在 JSON Schema 规范的示例部分或您正在学习的教程的第 5 部分第 2.2required节中找到有关如何使用关键字的更多示例。
于 2016-09-19T21:17:17.233 回答