4

有没有办法将属性表示为通常只读,但允许在 POST 或 PUT(即创建或替换)操作期间写入属性?

换句话说,在创建资源时,我希望该属性是可写的。但是一旦创建了资源,我想保持它不可变。属性可以是 POSTable/PUTable,但不是 PATCHable?

例子:

# OK example.
/AwesomeResource POST
{"owner": "ownerID123"}

vs

# Bad Request example.
/AwesomeResource/456 PATCH
{"owner": "ownerID789"}
4

1 回答 1

6

POST/PUT 和 PATCH/GET 需要单独的模型。具有可写属性的 POST/PUT 模型owner可以作为基础模型,PATCH/GET 模型将通过添加readOnly约束对其进行扩展。

# openapi: 3.0.0

components:
  schemas:

    # Model for POST and PUT
    NewAwesomeResource:
      type: object
      properties:
        owner:
          type: string
          example: ownerID789
        ...

    # Model for PATCH and GET
    AwesomeResource:
      allOf:
        - $ref: '#/components/schemas/NewAwesomeResource'
        - properties:
            owner:
              readOnly: true
于 2020-02-07T09:01:27.803 回答