FastAPI 将为模型生成模式,这些模式可以用作请求正文 https://fastapi.tiangolo.com/tutorial/body/ or 响应模型 https://fastapi.tiangolo.com/tutorial/response-model/。申报时query_args: FaultQueryParams = Depends()
(using Depends https://fastapi.tiangolo.com/tutorial/dependencies/),您的端点不会期望request body
, 反而query
参数;因此,FaultQueryParams
不会包含在架构中OpenAPI https://fastapi.tiangolo.com/tutorial/first-steps/#openapi docs.
要添加其他模式,您可以扩展/修改 OpenAPI 架构 https://fastapi.tiangolo.com/advanced/extending-openapi/#modify-the-openapi-schema。下面给出了示例(确保在定义所有路由之后添加用于修改架构的代码,即在代码末尾)。
class FaultQueryParams(BaseModel):
f_id: Optional[int] = Field(None, description="id for the host", example=12345, title="Fault ID")
hostname: Optional[str]
status: Literal["open", "closed", "all"] = Field("open")
...
@app.post('/predict')
def predict(query_args: FaultQueryParams = Depends()):
return query_args
def get_extra_schemas():
return {
"FaultQueryParams": {
"title": "FaultQueryParams",
"type": "object",
"properties": {
"f_id": {
"title": "Fault ID",
"type": "integer",
"description": "id for the host",
"example": 12345
},
"hostname": {
"title": "Hostname",
"type": "string"
},
"status": {
"title": "Status",
"enum": [
"open",
"closed",
"all"
],
"type": "string",
"default": "open"
},
...
}
}
}
from fastapi.openapi.utils import get_openapi
def custom_openapi():
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="FastAPI",
version="1.0.0",
description="This is a custom OpenAPI schema",
routes=app.routes,
)
new_schemas = openapi_schema["components"]["schemas"]
new_schemas.update(get_extra_schemas())
openapi_schema["components"]["schemas"] = new_schemas
app.openapi_schema = openapi_schema
return app.openapi_schema
app.openapi = custom_openapi
一些有用的注释
Note 1
您可以让 FastAPI 使用该模型向您的代码添加一个端点(您随后将在获取架构后将其删除),从而让 FastAPI 为您完成此操作,而不是手动键入要添加到文档中的额外模型的架构作为请求正文或响应模型,例如:
@app.post('/predict')
def predict(query_args: FaultQueryParams):
return query_args
然后,您可以在以下位置获取生成的 JSON 模式:http://127.0.0.1:8000/openapi.json http://127.0.0.1:8000/openapi.json,如中所述文档 https://fastapi.tiangolo.com/tutorial/first-steps/#check-the-openapijson。从那里,您可以将模型的架构复制并粘贴到您的代码中并直接使用它(如get_extra_schema()
方法)或将其保存到文件并从文件中加载 JSON 数据,如下所示:
import json
...
new_schemas = openapi_schema["components"]["schemas"]
with open('extra_schemas.json') as f:
extra_schemas = json.load(f)
new_schemas.update(extra_schemas)
openapi_schema["components"]["schemas"] = new_schemas
...
Note 2
To 声明元数据 https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#declare-more-metadata, 例如description
, example
等,对于您的查询参数,您应该使用以下方式定义您的参数Query
代替Field
,并且由于您无法使用 Pydantic 模型做到这一点,因此您可以声明一个自定义依赖类 https://fastapi.tiangolo.com/tutorial/dependencies/classes-as-dependencies/#classes-as-dependencies_1,如上所述here https://stackoverflow.com/a/64366434并如下图所示:
from fastapi import FastAPI, Query, Depends
from typing import Optional
class FaultQueryParams:
def __init__(
self,
f_id: Optional[int] = Query(None, description="id for the host", example=12345)
):
self.f_id = f_id
app = FastAPI()
@app.post('/predict')
def predict(query_args: FaultQueryParams = Depends()):
return query_args
上面的内容可以重写为@dataclass https://docs.python.org/3/library/dataclasses.html装饰器,如下图:
from fastapi import FastAPI, Query, Depends
from typing import Optional
from dataclasses import dataclass
@dataclass
class FaultQueryParams:
f_id: Optional[int] = Query(None, description="id for the host", example=12345)
app = FastAPI()
@app.post('/predict')
def predict(query_args: FaultQueryParams = Depends()):
return query_args