现在位置: 首页 > FastAPI 教程 > 正文

FastAPI 响应状态码

HTTP 状态码是响应的一部分,用于告知客户端请求的处理结果。FastAPI 允许你在路径操作装饰器中声明默认的状态码,也可以在函数中动态修改。


声明状态码

使用 status_code 参数在装饰器中声明响应状态码:

实例

from fastapi import FastAPI, status

app = FastAPI()


# 创建资源时,使用 201 状态码
@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(name: str):
    return {"name": name}

status_code 是装饰器方法的参数(如 @app.post()),不是路径操作函数的参数。它可以是数字(如 201),也可以使用 fastapi.status 中的常量(推荐,有编辑器自动补全支持)。


HTTP 状态码速查

范围类别常用状态码含义
1xx信息--很少直接使用
2xx成功200 OK请求成功(默认状态码)
201 Created资源创建成功
204 No Content成功但无内容返回
3xx重定向304 Not Modified资源未修改(缓存有效)
4xx客户端错误400 Bad Request请求格式错误
401 Unauthorized未认证
403 Forbidden已认证但无权限
404 Not Found资源不存在
5xx服务器错误500 Internal Server Error服务器内部错误

使用 status 常量

fastapi.status 提供了所有 HTTP 状态码的常量,配合编辑器自动补全使用更方便:

实例

from fastapi import FastAPI, status

app = FastAPI()


# POST - 创建资源,返回 201
@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(name: str):
    return {"name": name}


# DELETE - 删除资源,返回 204(无内容)
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int):
    # 删除操作通常不返回内容
    pass


# GET - 获取资源,返回 200(默认)
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

204 No Content 表示成功但没有内容返回,适用于删除操作。注意 204 响应不能包含响应体。


常用状态码常量

常量使用场景
status.HTTP_200_OK200GET 请求成功(默认)
status.HTTP_201_CREATED201POST 创建资源成功
status.HTTP_204_NO_CONTENT204DELETE 成功,无返回内容
status.HTTP_400_BAD_REQUEST400请求参数错误
status.HTTP_401_UNAUTHORIZED401未登录或 token 无效
status.HTTP_403_FORBIDDEN403无权限访问
status.HTTP_404_NOT_FOUND404资源不存在
status.HTTP_409_CONFLICT409资源冲突(如重复创建)
status.HTTP_422_UNPROCESSABLE_ENTITY422数据校验失败
status.HTTP_500_INTERNAL_SERVER_ERROR500服务器内部错误

小结

  • 使用装饰器的 status_code 参数声明默认状态码
  • 推荐使用 fastapi.status 常量,有编辑器自动补全支持
  • POST 创建资源用 201,DELETE 删除资源用 204,GET 获取资源用 200
  • 4xx 表示客户端错误,5xx 表示服务器错误