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}
相关推荐
曲幽4 小时前
FastAPI 身份验证总踩坑?这份 FastAPI Users “避坑指南”请收好
python·fastapi·web·jwt·oauth2·user·authentication
海鸥-w16 小时前
用python (fastapi)做项目第一天创建项目结构,数据建表,ORM配置安装,写第一个接口
数据库·python·fastapi
li星野18 小时前
从零搭建文件上传系统:FastAPI 后端 + Streamlit 前端
前端·状态模式·fastapi
至天2 天前
FastAPI 接入 FastAPI-Limiter 以及使用 Redis 进行限流指南
redis·python·fastapi·请求限流
li星野2 天前
FastAPI 中间件完全指南:从原理到实战,掌控请求响应的全局钩子
中间件·fastapi
Derrick__12 天前
基于 LangGraph + FastAPI 搭建一个带人工审核的行业分析多智能体系统
ai·agent·fastapi·vibe coding
ss2733 天前
【Python实战】基于FastAPI的绿植养护管理系统 - 完整项目
python·fastapi
li星野3 天前
FastAPI 响应类型完全指南:从 JSON 到流式响应、异常处理与输出模型
前端·json·fastapi
海鸥-w4 天前
python(fastapi) 实现更新,新增,删除接口
android·python·fastapi
我叫张小白。4 天前
Redis BitMap实现用户签到功能
数据库·redis·缓存·fastapi