如果我们看一个消息 API(例如)
我希望它能够
消息包含外部引用(来自消费者的唯一 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
我看到的唯一解决方案:
有没有更好的解决方案来实现这一目标?理想的解决方案是只有一个 Message 定义,并在 PATCH 方法中覆盖 Message 定义(删除该字段)。
我不知道这是否可能。
谢谢
最佳答案
要处理此用例,您必须定义 2 条消息:
UpdateMessage
包含除 external_id
之外的所有属性Message
包含所有 UpdateMessage
属性加external_id
使用 allOf
是使用 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"
关于api - 在 swagger 2.0 (openapi) 中,如何在 POST 和 PUT 请求之间有不同的资源定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38244375/