我正在使用 fastAPI 来构建 API。
它还显示可能的响应代码列表。默认情况下,它仅显示成功代码和 422 代码。
但在我的应用程序中允许使用更多代码。例如404、401、403等。 所有这些异常都不在端点的代码内。它在一个包裹里
@app.get("/items/{item_id}")
async def read_item(item_id: str):
data, error, message = do_something()
if error != 0:
raise HTTPException(status_code=error, detail=message)
return data
如何通知装饰器所有可能的代码?有可能吗?
您可以在 fastapi 中使用
APIRouter
来定义路由和自定义响应:
from fastapi import HTTPException, APIRouter
router = APIRouter()
@router.get("/items/{item_id}")
async def read_item(item_id: str):
data, error, message = do_something()
if error != 0:
raise HTTPException(status_code=error, detail=message)
return data
然后您可以定义您想要的响应:
read_item.responses = {
200: {"description": "Successful response"},
404: {"description": "Item not found"},
401: {"description": "Unauthorized access"},
403: {"description": "Forbidden access"}
}
在
@router.get()
中定义响应的另一种方法:
@router.get("/items/{item_id}",
description="Retrieves an item by its ID.",
response_model=Item,
responses={
200: {"description": "Successful response"},
404: {"description": "Item not found"},
401: {"description": "Unauthorized access"},
403: {"description": "Forbidden access"}
}
)