FastAPI 学习之路(十五)响应状态码

本文介绍如何在FastAPI框架中通过指定status_code参数来自定义HTTP响应状态码,并解释了不同状态码的含义及应用场景。

我们可以规定对应请求的状态码,那么我们应该如何来实现。在以下任意的接口路径中使用 status_code 参数来声明用于响应的 HTTP 状态码:

  • @app.get()
  • @app.post()
  • @app.put()
  • @app.delete()

我们可以简单的看下:

from fastapi import FastAPI

app = FastAPI()


@app.post("/items", status_code=201)
def create_item(name: str):
    return {"name": name}

我们看下结果 

接口可以正常请求,状态码返回的也是我们定义的201。

       在接口文档上也可以正常展示我们成功的状态码

对于http的状态码,每个数字代表不一样的含义。

  • 100 及以上状态码用于「消息」响应。你很少直接使用它们。具有这些状态代码的响应不能带有响应体。
  • 200 及以上状态码用于「成功」响应。这些是你最常使用的。
    • 200 是默认状态代码,它表示一切「正常」。
    • 另一个例子会是 201,「已创建」。它通常在数据库中创建了一条新记录后使用。
    • 一个特殊的例子是 204,「无内容」。此响
FastAPI 中,状态码的获取和设置通常通过 `response` 参数或返回 `Response` 对象来实现。以下是一些常用的方法和技巧: ### 获取响应状态码 1. **使用 `response` 参数控制状态码** 在定义路由时,可以通过 `response` 参数指定响应模型,并结合 `status_code` 来设置特定的状态码。例如,在处理成功请求时返回 `200 OK`,在发生错误时返回 `404 Not Found`。 ```python from fastapi import FastAPI, status from fastapi.responses import JSONResponse app = FastAPI() @app.get("/example") async def example_endpoint(): return JSONResponse(content={"message": "Success"}, status_code=status.HTTP_200_OK) ``` 2. **通过异常处理获取状态码** 使用 `HTTPException` 可以抛出带有特定状态码的异常,FastAPI 会自动捕获并返回对应的 HTTP 响应。 ```python from fastapi import FastAPI, HTTPException app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id not in items: raise HTTPException(status_code=404, detail="Item not found") return {"item_id": item_id} ``` 3. **自定义中间件中获取状态码** 在自定义的 `ResponseMiddleware` 中,可以通过拦截请求和响应来读取或修改状态码。例如,记录每个请求的响应状态码。 ```python from fastapi import Request, FastAPI from fastapi.middleware import Middleware from fastapi.middleware.base import BaseHTTPMiddleware class ResponseMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): response = await call_next(request) print(f"Response status code: {response.status_code}") # 获取状态码[^1] return response app = FastAPI() app.add_middleware(ResponseMiddleware) ``` 4. **直接操作 `Response` 对象** 如果需要更精细地控制响应内容和状态码,可以直接返回 `Response` 子类(如 `JSONResponse`, `PlainTextResponse` 等)的实例。 ```python from fastapi import FastAPI from fastapi.responses import Response app = FastAPI() @app.get("/custom-response") async def custom_response(): return Response(content="Custom content", status_code=201) # 自定义状态码[^2] ``` ### 示例:获取状态码的完整示例 ```python from fastapi import FastAPI, Request, Response, HTTPException from fastapi.middleware.base import BaseHTTPMiddleware class StatusLoggingMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): response = await call_next(request) print(f"Request path: {request.url.path}, Status Code: {response.status_code}") # 日志记录状态码[^1] return response app = FastAPI() app.add_middleware(StatusLoggingMiddleware) @app.get("/success") async def success(): return {"message": "OK"} # 默认返回 200 状态码 @app.get("/error") async def error(): raise HTTPException(status_code=400, detail="Bad Request") # 抛出 400 错误[^2] @app.get("/custom-status") async def custom_status(): return Response(content="Created", status_code=201) # 返回 201 状态码[^2] ``` ---
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值