假设我们有一个json swagger规范示例:
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Some API"
},
"basePath": "/api/v1",
"consumes": [
"application/json"
],
"produces": [
"application/json",
"text/csv"
],
"paths": {
"/some/endpoint": {
"get": {
"parameters": [
{
"in": "body",
"name": "body",
"required": false,
"schema": {
"$ref": "#/definitions/BodyParamsDefinition"
}
}
],
"responses": {
"200": { ?? } ...
可以生成两种内容类型:
- application/json
- text.csv
GET /some/endpoint
的默认响应是csv文件,但如果像/some/endpoint?format=json
这样使用format
查询参数,则响应将为json格式。
我很难找到如何以正确的响应完成规范。当我使用这种方法时:https://swagger.io/docs/specification/describing-responses/我得到一个验证错误:...get.responses['200'] should NOT have additional properties
您就快到了,只需要为响应定义一个schema
。此schema
定义了与此状态代码相关联的所有内容类型的响应结构。
例如,如果操作返回以下JSON:
[
{
"petType": "dog",
"name": "Fluffy"
},
{
"petType": "cat",
"name": "Crookshanks"
}
]
这个CSV:
petType,name
dog,Fluffy
cat,Crookshanks
你会使用:
# YAML
responses:
200:
description: OK
schema:
type: array
items:
type: object
properties:
petType:
type: string
name:
type: string
更多信息:描述响应
在OpenAPI 3.0中,内容类型定义得到了改进,架构可能因内容类型而异:
openapi: 3.0.0
...
paths:
/some/endpoint:
get:
responses:
'200':
description: OK
content:
# JSON data is an object
application/json:
schema:
type: object
properties:
message:
type: string
# CSV data is a string of text
text/csv:
schema:
type: string
GET /some/endpoint
的默认响应是csv文件,但如果像这样使用/some/endpoint?format=json
的format
查询参数,则响应将为json格式。
目前还没有办法将特定的响应映射到特定的操作参数,但在OpenAPI规范库中有几个相关的建议:
- 通过在路径中允许查询参数来适应遗留API
- 路径规范中的Querystring
- 支持每个路径具有多个规范的操作
- 过载