我正在使用Swagger编辑器编写API文档,但是包含JSON对象的多部分POST请求存在问题。这是我的Swagger YAML文件:
swagger: '2.0'
info:
version: 1.0.0
title: Documentation API
paths:
/agent:
post:
consumes:
- multipart/form-data
produces:
- text/html
parameters:
- in: query
name: method
description: name of method to access
required: true
type: string
- in: body
name: param
description: parameter to send
required: true
schema:
$ref: "#/definitions/Param"
responses:
201:
description: item created
400:
description: invalid input, object invalid
409:
description: an existing item already exists
definitions:
Param: # <----------
type: object
required:
- username
- password
- imsi
- imei
- deviceId
properties:
username:
type: string
password:
type: string
imsi:
type: string
imei:
type: string
deviceId:
type: string
host: 'localhost'
basePath: /v1/api
schemes:
- https
当我执行请求时,我得到像这样的curl命令:
curl -X POST "https://localhost/v1/api/agent?method=login" -H "accept: text/html" -H "content-type: multipart/form-data" -F {"username":"1234567890","password":"1234567890","imsi":"310260000000000","imei":"000000000000000","deviceId":"9ca9b02b237a6dae"}
但我希望得到这个:
curl -X POST "https://localhost/v1/api/agent?method=login" -H "accept: text/html" -H "content-type: multipart/form-data" -F 'param={"username":"1234567890","password":"1234567890","imsi":"310260000000000","imei":"000000000000000","deviceId":"9ca9b02b237a6dae"}'
也就是说,应使用键名param
发送body参数。
答案 0 :(得分:1)
multipart/*
请求可以使用OpenAPI 3.0来描述,但不能使用OpenAPI / Swagger 2.0来描述。
OpenAPI 3.0原生支持JSON objects in multipart/form-data
个请求:
paths:
/agent:
post:
parameters:
- in: query
name: method
description: name of method to access
required: true
schema:
type: string
requestBody:
required: true
content:
multipart/form-data:
schema:
type: object
properties:
# Here, "param" is part/parameter name in a multipart payload.
# Parameter value is an object defined by the "Param" schema.
# Default Content-Type for objects is application/json.
param:
$ref: "#/components/schemas/Param"
responses:
...
在OpenAPI / Swagger 2.0中,当使用表单数据(application/x-www-form-urlencoded
或multipart/form-data
)时,其值为JSON字符串的表单参数仅被描述为type: string
,并且您无法定义JSON字符串的结构。
paths:
/agent:
post:
consumes:
- multipart/form-data
produces:
- text/html
parameters:
- ...
- in: formData # <-------
name: param
description: parameter to send
required: true
type: string # <-------
要传入JSON对象,操作需要使用application/json
代替:
paths:
/agent:
post:
consumes:
- application/json # <-----
produces:
- text/html
parameters:
- ...
- in: body
name: param
description: parameter to send
required: true
schema:
$ref: "#/definitions/Param"