我试图使用OpenAPI/Swagger运行一个端点,该端点能够使用json字典,发送到函数并获得响应。
我使用operationId来引用我想要调用的函数,但是无法解决如何发送端点接收到的字典。
调用controllers.get_options,但使用我的当前方法不向它发送任何参数。
我想我错过了一些显而易见的东西,但这并不明显!
我会像这样调用端点:
curl -X 'POST' \
'http://localhost:8080/getoptions' \
-H 'accept: */*' \
-H 'Content-Type: application/json' \
-d '{
"product_area": "Main",
"product_type": "New"
}'这是openapi配置文件(./openapi.yaml)
编辑:根据海伦的评论,在下面添加x-body-name: DiscussionResult解决了这个问题
openapi: 3.0.0
info:
title: Test
version: '1.0'
paths:
/getoptions:
post:
description: Return product options from product type and area
operationId: controllers.get_options
requestBody:
required: true
content:
application/json:
x-body-name: DiscussionResult
schema:
$ref: '#/components/schemas/DiscussionResult'
responses:
200:
description: "success"
components:
schemas:
DiscussionResult:
type: object
discriminator:
propertyName: product_type
properties:
product_type:
type: string
example: "New"
product_area:
type: string
example: "Main"我使用connexion运行它,如下所示:
main.py
import connexion
import logging
def create_app():
logging.basicConfig(level=logging.DEBUG)
connex_app = connexion.FlaskApp(__name__, specification_dir="./openapi/")
connex_app.add_api("./openapi.yaml", resolver_error=501)
return connex_app
if __name__ == "__main__":
app = create_app()
app.run(host="0.0.0.0", port=8080)requirements.txt
connexion[swagger-ui]
connexion>=2.2.0
python-jose[cryptography]
six>=1.9
Flask>=0.10.1
sqlathanor这就是我想要调用的函数
def get_options(DiscussionResult):
msg = "{} {}".format(DiscussionResult['product_area'], DiscussionResult['product_type'])
return jsonify(message=msg), 200发布于 2021-09-16 07:19:35
请求处理上的连接文档包括以下注意事项:
在OpenAPI 3.x.x规范中,requestBody没有名称。默认情况下,它将作为“body”传入。您可以选择在
x-body-nameschema中提供requestBody参数,以覆盖将传递给处理程序函数的参数的名称。
看起来,您需要将x-body-name: DiscussionResult添加到requestBody中使用的DiscussionResult架构中。
components:
schemas:
DiscussionResult:
x-body-name: DiscussionResult # <---------
type: object
...或
requestBody:
required: true
content:
application/json:
schema:
x-body-name: DiscussionResult # <---------
$ref: '#/components/schemas/DiscussionResult'发布于 2021-09-15 18:41:10
正如我在前面的评论中已经说过的,我非常推荐FastApi。下面是一些有用的代码。
main.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class DetailsModel(BaseModel):
product_area: str
product_type: str
@app.post("/get_details")
async def _(
input_json: DetailsModel
):
return {"returns": input_json.dict()}从根目录运行uvicorn main:app --reload
然后检查http://127.0.0.1:8000/docs
然后你可以打电话:
curl -X 'POST' \
'http://127.0.0.1:8000/get_details' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"product_area": "Main",
"product_type": "New"
}'Fastapi使用Pydantic检查任何不可处理的实体,这对任何不符合模型的请求都有很大帮助。检查官方和非常详细的文档也https://fastapi.tiangolo.com/。
https://stackoverflow.com/questions/69196537
复制相似问题