FastAPI中路径参数,查询参数,请求体参数之间的区别

1. 路径参数

  • 数据位置:直接嵌入在URL的路径中。

  • 用途 :通常用于定位特定的资源。它是必填的,因为它是URL结构的一部分。

  • 示例/users/{user_id}

python 复制代码
from fastapi import FastAPI

app = FastAPI()

# 假设我们要获取ID为123的用户
# 请求地址:/users/123
@app.get("/users/{user_id}")
async def read_user(user_id: int):  # user_id 是路径参数
    return {"user_id": user_id}

2. 查询参数

  • 数据位置 :URL中 ? 后面的部分,以键值对形式存在。

  • 用途 :通常用于过滤、排序、分页 或提供可选的额外指令。它是可选的(通常有默认值),或者是非必须的。

  • 示例/users?page=2&limit=10

python 复制代码
from fastapi import FastAPI

app = FastAPI()

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

# 请求地址:/items?skip=0&limit=10
@app.get("/items/")
async def list_items(skip: int = 0, limit: int = 10):  # skip 和 limit 是查询参数
    return fake_items_db[skip : skip + limit]

# 可选参数的例子:/users?name=John
@app.get("/users/")
async def get_user(name: str = None):  # name 是可选查询参数
    if name:
        return f"查询名为 {name} 的用户"
    return "返回所有用户"

3. 请求体参数

  • 数据位置 :HTTP请求的**Body(主体)**中。

  • 用途 :通常用于提交创建或更新资源的数据。由于Body可以传输复杂的结构,它适合传输较复杂的数据(如嵌套的JSON对象)。

  • 示例 :在POST请求的Body中放置 {"name": "Foo", "price": 45.2}

python 复制代码
from fastapi import FastAPI
from pydantic import BaseModel  # 需要定义数据模型

app = FastAPI()

# 1. 定义一个 Pydantic 模型,描述请求体的结构
class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = False  # 可选字段,默认False

# 2. 在路径操作函数中使用该模型
@app.post("/items/")
async def create_item(item: Item):  # item 是请求体参数
    # FastAPI 会读取请求体,并验证是否符合 Item 模型的格式
    return {"item_name": item.name, "item_price": item.price}
相关推荐
曲幽3 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
CaffeinePro6 天前
依赖注入:FastAPI最核心的解耦能力案例解析
后端·fastapi
曲幽9 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
CaffeinePro13 天前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
jay神15 天前
基于 FastAPI + Vue 的宠物领养管理系统
前端·vue.js·python·毕业设计·fastapi·宠物
染指111016 天前
6.AI大模型-搭建本地大模型服务体系
fastapi·oneapi
codeaideaai17 天前
使用UV创建python项目
python·fastapi·uv
放下华子我只抽RuiKe517 天前
FastAPI 全栈后端(八):部署与运维
运维·数据库·react.js·oracle·数据挖掘·前端框架·fastapi
SilentSamsara17 天前
模型部署实战:FastAPI + ONNX + Docker 的推理服务化
人工智能·pytorch·python·深度学习·机器学习·fastapi
放下华子我只抽RuiKe517 天前
FastAPI 全栈后端(七):测试与自动化
运维·前端·人工智能·react.js·前端框架·自动化·fastapi