我想用Swagger POST一个json体,就像这样:
curl -H "Content-Type: application/json" -X POST -d {"username":"foobar","password":"xxxxxxxxxxxxxxxxx", "email": "foo@bar.com"}' http://localhost/user/register
目前,我有这个定义:
"/auth/register": {
"post": {
"tags": [
"auth"
],
"summary": "Create a new user account",
"parameters": [
{
"name": "username",
"in": "query",
"description": "The username of the user",
"required": true,
"type": "string"
},
{
"name": "password",
"in": "query",
"description": "The password of the user",
"required": true,
"type": "string",
"format": "password"
},
{
"name": "email",
"in": "query",
"description": "The email of the user",
"required": true,
"type": "string",
"format": "email"
}
],
"responses": {
"201": {
"description": "The user account has been created",
"schema": {
"$ref": "#/definitions/User"
}
},
"default": {
"description": "Unexpected error",
"schema": {
"$ref": "#/definitions/Errors"
}
}
}
}
}
但是数据是在URL中发送的。这里生成的卷曲由Swagger提供:
curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' 'http://localhost/user/register?username=foobar&password=password&email=foo%40bar.com'
我知道query
关键字不好,但我没有找到POST JSON主体的方法。我试过了formData
,但它没有用。
答案 0 :(得分:39)
您需要使用body
参数:
"parameters": [
{
"in": "body",
"name": "body",
"description": "Pet object that needs to be added to the store",
"required": false,
"schema": {
"$ref": "#/definitions/Pet"
}
}
],
和#/definitions/Pet
被定义为模型:
"Pet": {
"required": [
"name",
"photoUrls"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"category": {
"$ref": "#/definitions/Category"
},
"name": {
"type": "string",
"example": "doggie"
},
"photoUrls": {
"type": "array",
"xml": {
"name": "photoUrl",
"wrapped": true
},
"items": {
"type": "string"
}
},
"tags": {
"type": "array",
"xml": {
"name": "tag",
"wrapped": true
},
"items": {
"$ref": "#/definitions/Tag"
}
},
"status": {
"type": "string",
"description": "pet status in the store",
"enum": [
"available",
"pending",
"sold"
]
}
},
"xml": {
"name": "Pet"
}
},
OpenAPI / Swagger v2规范:https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameter-object
对于OpenAPI v3规范,不推荐使用body
参数。要定义HTTP有效负载,需要使用requestBody
代替,例如https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/test/resources/3_0/petstore.json#L39-L41
OpenAPI v3规范:https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#requestBodyObject