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}
相关推荐
Aric_Jones6 小时前
从实战理解异步、并发并行与GIL:FastAPI vs SpringBoot
java·spring boot·fastapi
不是株8 小时前
FastAPI
python·fastapi
星星也在雾里8 小时前
Dify + FastAPI + 讯飞WebSocket实现方言识别
人工智能·fastapi
Ares-Wang1 天前
FastAPI 数据验证 Pydantic Flask 用 WTForms
python·flask·fastapi
曲幽1 天前
FastAPI自动生成的API文档太丑?我花了一晚上把它改成了客户愿意付费的样子
python·fastapi·web·swagger·openapi·scalar·docs
PieroPc2 天前
一个功能强大的 Web 端标签设计和打印工具,支持服务器端直接打印到局域网打印机。Fastapi + html
前端·html·fastapi
别抢我的锅包肉2 天前
FastAPI + Vue3 + Vite 跨域报错全解:从 `Access-Control-Allow-Origin missing` 到彻底修复
中间件·状态模式·fastapi
Chase_______2 天前
【FastAPI】内网/离线环境docs文档无法显示的解决方案
fastapi
小李云雾2 天前
FastAPI 后端开发:文件上传 + 表单提交
开发语言·python·lua·postman·fastapi
曲幽2 天前
告别手写 API 胶水代码:FastAPI 与 Vue 的“契约自动机” OpenAPI 实战
python·typescript·vue·fastapi·web·swagger·openapi·codegen