FastAPI 中,‌最常用且核心的装饰器是路由装饰器

在 FastAPI 中,‌最常用且核心的装饰器是路由装饰器‌,例如:

@app.get("/path")     # 处理 GET 请求
@app.post("/path")    # 处理 POST 请求
@app.put("/path")     # 处理 PUT 请求
@app.delete("/path")  # 处理 DELETE 请求

核心作用

这些装饰器用于将函数标记为 ‌API 端点‌,并定义以下内容:

  1. HTTP 方法‌(GET/POST/PUT/DELETE 等)

  2. 请求路径‌(如 /items 或 /users/{id})

  3. 附加功能‌(如状态码、响应模型、依赖项等)


详细用法

1. 基本路由定义
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}
2. 路径参数
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}
3. 查询参数
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}
4. 请求体(POST)
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
async def create_item(item: Item):
    return item

常用附加参数

参数

说明

response_model

定义响应数据的模型(自动过滤敏感字段)

status_code

指定 HTTP 状态码(如 201 表示创建成功)

tags

为 OpenAPI 文档分组(如 tags=["Items"])

dependencies

注入依赖项(如身份验证)

summary

API 的简短描述(显示在文档中)

response_description

响应描述的详细说明

示例:带参数的装饰器
@app.post(
    "/items/",
    response_model=Item,
    status_code=201,
    tags=["Items"],
    summary="Create a new item"
)
async def create_item(item: Item):
    return item

为什么这是最常用的装饰器?

  1. 定义 API 的核心行为‌:所有端点都需要通过它声明。

  2. 高度可配置‌:通过参数集成数据验证、文档生成、依赖注入等功能。

  3. 与 OpenAPI 无缝集成‌:自动生成交互式文档(Swagger UI)。


其他常用装饰器

装饰器

用途

@app.middleware("http")

添加 HTTP 中间件

@app.exception_handler

自定义异常处理

@app.websocket("/ws")

处理 WebSocket 连接


总结

@app.get、@app.post 等路由装饰器是 FastAPI 的基石‌,几乎每个 API 端点都需要使用它们。它们的简洁语法和强大功能(如自动验证、文档生成)是 FastAPI 高效开发的核心原因。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值