FastAPI系列:如何改变响应状态码

FastAPI,顾名思义,是一个快速、现代、高性能的web框架,用于用Python构建后端api。响应状态码是一个三位数,表示请求的结果。例如,200表示OK, 404表示未找到,500表示服务器内部错误。默认情况下,FastAPI将为成功请求返回200状态码,为验证错误返回422状态码。

但是,有时你可能希望更改状态码以指示不同的结果。例如,你可能希望为创建新资源的成功POST请求返回201状态码,或者为无法找到所请求资源的GET请求返回404状态码。在这篇简明的基于示例的博文中,我将向你展示在FastAPI中更改响应状态代码的两种不同方法。

FastAPI系列:如何改变响应状态码_第1张图片

使用路由装饰器的status_code参数

要更改FastAPI中的响应状态代码,可以使用@app中的status_code参数。@app.get, @app.post 或其他路由装饰器。status_code参数接受来starlette.status模块的整数值或常量。例如,要为创建新用户的POST请求返回201状态码,你可以如下所示:

from fastapi import FastAPI
from starlette.status import HTTP_201_CREATED

# create the FastAPI instance
app = FastAPI()

# set the status code to 201
@app.post("/users", status_code=HTTP_201_CREATED)
def create_user(name: str):
    # some logic to create a new user
    return {"name": name}

在上面的代码片段中,我从starlette.status模块中导入了常量HTTP_201_CREATED。starlette.status模块是starlette框架的一部分,它是FastAPI的一个依赖。starlette.status模块为常见的HTTP状态码提供常量,如HTTP_200_OK、HTTP_404_NOT_FOUND等。使用这些常量可以使代码更具可读性,并避免拼写错误或错误。例如,我可以写status_code=HTTP_201_CREATED,而不是写status_code=201,这样更具描述性和清晰度。

运行下面命令重启服务:

uvicorn main:app --reload

然后去http://localhost:8000/docs, 可以看到文档中code的值与我们配置的一致,方便用户调试程序。

使用响应对象

在这种方法中,我们使用fastapi模块中的Response对象在函数体中动态设置状态码。Response对象有status_code属性,你可以从starlette.status模块中分配整数值或常量状态值。

下面的例子返回404状态码的GET请求,不能找到被请求的用户:

from fastapi import FastAPI, Response
from starlette.status import HTTP_404_NOT_FOUND, HTTP_200_OK

app = FastAPI()


@app.get("/users/{user_id}")
def get_user(user_id: int, response: Response):
    # some logic to get the user by id
    user = None

    if user is None:
        # set the status code
        response.status_code = HTTP_404_NOT_FOUND
        return {"detail": "User not found"}
    else:
        # set the status code
        response.status_code = HTTP_200_OK
        return user

查看文档,效果与上面一样。

完整实战案例

这是一个完整的代码示例,展示了如何在不同的场景下更改FastAPI中的响应状态代码:

# main.py

from fastapi import FastAPI, Response
from starlette.status import HTTP_201_CREATED, HTTP_404_NOT_FOUND

app = FastAPI()

# A mock database of users
users = [
    {"id": 1, "name": "Sling Academy"},
    {"id": 2, "name": "Ranni the Witch"},
    {"id": 3, "name": "Khue"},
]


# A helper function to get a user by id
def get_user_by_id(user_id: int):
    for user in users:
        if user["id"] == user_id:
            return user
    return None


# A POST route to create a new user and return a 201 status code
@app.post("/users", status_code=HTTP_201_CREATED)
def create_user(name: str):
    # some logic to create a new user and add it to the database
    new_user = {"id": len(users) + 1, "name": name}
    users.append(new_user)
    return new_user


# A GET route to get a user by id and return either a 200 or a 404 status code
@app.get("/users/{user_id}")
def get_user(user_id: int, response: Response):
    # some logic to get the user by id from the database
    user = get_user_by_id(user_id)
    if user is None:
        response.status_code = HTTP_404_NOT_FOUND
        return {"detail": "User not found"}
    else:
        return user

最后总结

在本文中,我解释了如何使用两种方法在FastAPI中更改响应状态代码:路由装饰器中的status_code参数和函数体中的response对象。你可以根据自己的需要和偏好使用任何一种方法。更改响应状态码可以帮助您更清楚地与客户端进行通信,并遵循RESTful API设计的最佳实践。

你可能感兴趣的:(#,python,fastapi)