在 FastAPI 中,你可以通过指定 status_code 参数来更改默认的状态代码。以下是一些示例:

1. 返回不同的状态码的 JSON 响应:
from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/items/{item_id}/", response_class=JSONResponse)
async def read_item(item_id: int):
    if item_id == 42:
        content = {"message": "Item found"}
        return JSONResponse(content=content, status_code=200)
    else:
        content = {"message": "Item not found"}
        return JSONResponse(content=content, status_code=404)

在这个例子中,我们使用了 JSONResponse 类,并通过 status_code 参数指定了不同的状态码。

2. 返回不同状态码的 HTML 响应:
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

app = FastAPI()

@app.get("/items/{item_id}/", response_class=HTMLResponse)
async def read_item(item_id: int):
    if item_id == 42:
        content = "<html><body><h1>Item found</h1></body></html>"
        return HTMLResponse(content=content, status_code=200)
    else:
        content = "<html><body><h1>Item not found</h1></body></html>"
        return HTMLResponse(content=content, status_code=404)

在这个例子中,我们使用了 HTMLResponse 类,并通过 status_code 参数指定了不同的状态码。

3. 使用默认响应模型和状态码:
from fastapi import FastAPI, HTTPException

app = FastAPI()

class ItemNotFoundModel:
    detail: str = "Item not found"

@app.get("/items/{item_id}/")
async def read_item(item_id: int):
    if item_id != 42:
        raise HTTPException(status_code=404, detail=ItemNotFoundModel())
    
    return {"message": "Item found"}

在这个例子中,我们使用了 HTTPException 异常,并通过 status_code 参数指定了状态码,同时也可以返回一个带有详细信息的响应模型。

通过这些示例,你可以更灵活地在 FastAPI 中控制返回的响应状态码。


转载请注明出处:http://www.zyzy.cn/article/detail/7412/FastAPI