如果我们查看消息API(例如)
我希望它能够
>创建一条消息
>得到一条消息
>更新消息
消息包含外部引用(来自使用者的唯一ID)
>应使用POST请求在创建时设置此external_id
>无法使用PATCH更改此external_id
实施它的解决方案是什么?
API示例:
swagger: '2.0'
host: api.com
basePath: /v2
schemes:
- https
info:
title: dummy
version: 1.0.0
consumes:
- application/json
produces:
- application/json
paths:
/messages:
post:
summary: Create a message
parameters:
- name: message
in: body
required: true
schema:
$ref: '#/definitions/Message'
responses:
201:
description: Ok
schema:
$ref: '#/definitions/Message'
/messages/{id}:
get:
summary: "Get a message by ID"
parameters:
- name: id
in: path
description: The message ID
required: true
type: string
format: uuid
responses:
200:
description: OK - the message
schema:
$ref: '#/definitions/Message'
patch:
summary: Modify a message
parameters:
- name: id
in: path
description: The message ID
required: true
type: string
format: uuid
- name: message
in: body
required: true
schema:
$ref: '#/definitions/Message'
responses:
201:
description: Ok
schema:
$ref: '#/definitions/Message'
definitions:
Message:
type: object
required:
- id
- external_id
- title
- content
- created_at
properties:
id:
type: string
readOnly: true
external_id:
type: string
description: "Your own reference ID"
title:
type: string
content:
type: string
created_at:
type: string
format: date-time
readOnly: true
我看到的唯一解决方案:
>使用allOf定义2个定义(Message和UpdatedMessage)
>不使用PATCH方法或GET / POST方法中的定义
有没有更好的解决方案来实现这一目标?理想的解决方案是只有一个Message定义,并在PATCH方法中覆盖Message定义(删除字段).
我不知道是否有可能.
谢谢
最佳答案 要处理此用例,您必须定义2条消息:
>包含除external_id之外的所有属性的UpdateMessage
>包含所有UpdateMessage属性的消息加上使用allOf的external_id是使用OpenAPI(fka.Swagger)2.0版本实现此目的的唯一方法.
这是相应的YAML:
swagger: '2.0'
host: api.com
basePath: /v2
schemes:
- https
info:
title: dummy
version: 1.0.0
consumes:
- application/json
produces:
- application/json
paths:
/messages:
post:
summary: Create a message
parameters:
- name: message
in: body
required: true
schema:
$ref: '#/definitions/Message'
responses:
201:
description: Ok
schema:
$ref: '#/definitions/Message'
/messages/{id}:
get:
summary: "Get a message by ID"
parameters:
- name: id
in: path
description: The message ID
required: true
type: string
format: uuid
responses:
200:
description: OK - the message
schema:
$ref: '#/definitions/Message'
patch:
summary: Modify a message
parameters:
- name: id
in: path
description: The message ID
required: true
type: string
format: uuid
- name: message
in: body
required: true
schema:
$ref: '#/definitions/UpdateMessage'
responses:
201:
description: Ok
schema:
$ref: '#/definitions/Message'
definitions:
UpdateMessage:
type: object
required:
- id
- title
- content
- created_at
properties:
id:
type: string
readOnly: true
title:
type: string
content:
type: string
created_at:
type: string
format: date-time
readOnly: true
Message:
allOf:
- $ref: '#/definitions/UpdateMessage'
- required:
- external_id
properties:
external_id:
type: string
description: "Your own reference ID"