我有一个 API 端点,它使用以下形式的查询参数响应 POST 请求:
json_string = '{"items":%20[{"name":%20"chicken",%20"quantity":%201,%20"basePrice":%20499,%20"priceWithModifiers":%20499},%20{"name":%20"soda",%20"quantity":%201,%20"basePrice":%20399,%20"priceWithModifiers":%20399}],%20"salesTax":%20{"id":%20"T8JKFEVBE6F30",%20"name":%20"Sales%20Tax",%20"rate":%20900000,%20"isDefault":%20true},%20"orderType":%20{"id":%20"ZJQ5ND5FZAAVP",%20"taxable":%20true,%20"isDefault":%20true,%20"filterCategories":%20false,%20"isHidden":%20false,%20"hoursAvailable":%20"BUSINESS",%20"isDeleted":%20false}}'
因此,完整的 url 是“endpoint/?{json_string}”。我尝试使用 content -> application/json -> schema 将参数描述为字符串,但由于我必须为参数指定名称,因此查询参数中的某处总会有不需要的“=”。 我不想重写API本身。
您可以使用 Javascript 创建类似的字符串
const my_dict = {"items": [5,6,7], "SalesTax": {"id": "foobar"}, "orderType": {"id": "Takeout"}}
query_param = JSON.stringify(my_dict)
或者用Python
import json
my_dict = {"items": [5,6,7], "SalesTax": {"id": "foobar"}, "orderType": {"id": "Takeout"}}
query_param = json.dumps(the_dict)
您不使用带有请求正文的 POST 是否有原因?在查询中维护json字符串的目的是什么? url 的字符限制为 2048。如果您的 json 字符串增长超过这个数字,您将遇到更大的问题。另一个优点是您不需要对请求正文进行编码。
POST /endpoint HTTP/1.1
content-type: application/json
[
{ "name": "chicken",
"quantity": 1,
"basePrice": 499,
"priceWithModifiers": 499
}
]
这被定义为 JSON Schema,如下所示:
{
"$id": "itemWithPricing",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"quantity": {
"type": "number"
},
"basePrice": {
"type": "number"
},
"priceWithModifiers": {
"type": "number"
}
}
}
}
然后您可以在您的 OpenAPI 描述中使用它
{
"openapi": "3.1.0",
"info": {},
"servers": [],
"paths": {
"/endpoint": {
"post": {
"summary": "create a new item with pricing",
"parameters": [],
"requestBody": {
"description": "create a new item",
"content": {
"application/json": {
"schema": {
"$id": "itemWithPricing",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "array",
"uniqueItems": true,
"items": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"quantity": {
"type": "number"
},
"basePrice": {
"type": "number"
},
"priceWithModifiers": {
"type": "number"
}
}
}
}
}
}
},
"responses": {
"201": {
"description": "Created",
"content": {
"application/json": {
"schema": {}
}
}
}
}
}
}
}
}