通过实战的形式带我学会使用fastapi 的参数的传递方式

通过实际示例来学习 FastAPI 的参数传递方式。我会逐步讲解不同的参数传递方式,并配上代码示例,你可以在本地运行并测试效果。


1. 路径参数 (Path Parameters)

路径参数是 URL 的一部分,通常用于标识特定的资源。例如:

python 复制代码
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

📌 测试方式

  • 启动 FastAPI 服务器 uvicorn filename:app --reload
  • 访问 http://127.0.0.1:8000/items/42
  • 你会得到 {"item_id": 42}

🚀 关键点

  • {item_id} 是路径参数,必须在 URL 中提供。
  • FastAPI 自动将 item_id 解析为 int,如果传入错误类型(如 string),会返回 422 错误。

2. 查询参数 (Query Parameters)

查询参数通常用于可选参数,它们出现在 ?key=value 形式的 URL 中。

python 复制代码
@app.get("/search/")
async def search_items(q: str = "default", page: int = 1, size: int = 10):
    return {"q": q, "page": page, "size": size}

📌 测试方式

  • 访问 http://127.0.0.1:8000/search/?q=FastAPI&page=2&size=5
  • 你会得到 {"q": "FastAPI", "page": 2, "size": 5}

🚀 关键点

  • q: str = "default" 设定了默认值,用户可以不提供参数。
  • page: int = 1, size: int = 10 也有默认值,不传时会使用默认值。

3. 请求体参数 (Request Body Parameters)

适用于 POST, PUT 等请求,数据格式通常为 JSON。

python 复制代码
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float
    quantity: int

@app.post("/items/")
async def create_item(item: Item):
    return {"message": "Item created", "item": item}

📌 测试方式 : 使用 POST 请求,发送 JSON 数据:

json 复制代码
{
  "name": "Laptop",
  "description": "A high-end gaming laptop",
  "price": 1299.99,
  "quantity": 5
}

你会得到:

json 复制代码
{
  "message": "Item created",
  "item": {
    "name": "Laptop",
    "description": "A high-end gaming laptop",
    "price": 1299.99,
    "quantity": 5
  }
}

🚀 关键点

  • BaseModel 让 FastAPI 自动验证数据类型,并在 Swagger UI 显示接口文档。
  • description 是可选字段(设定为 None)。

4. 路径参数 + 查询参数

你可以组合路径参数和查询参数,比如:

python 复制代码
@app.get("/users/{user_id}")
async def get_user(user_id: int, detailed: bool = False):
    if detailed:
        return {"user_id": user_id, "details": "Full user details here"}
    return {"user_id": user_id}

📌 测试方式

  • http://127.0.0.1:8000/users/100 -> {"user_id": 100}
  • http://127.0.0.1:8000/users/100?detailed=true -> {"user_id": 100, "details": "Full user details here"}

🚀 关键点

  • user_id 是路径参数,必须提供。
  • detailed 是查询参数,默认 False,可选提供。

5. 表单参数 (Form Parameters)

当你的 POST 请求是 application/x-www-form-urlencoded 时,需要 Form 来解析参数。

python 复制代码
from fastapi import Form

@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

📌 测试方式 : 用 POST 请求:

ini 复制代码
username=admin&password=secret

返回:

json 复制代码
{"username": "admin"}

🚀 关键点

  • Form(...) 强制字段必填。
  • 适用于 HTML 表单提交数据的情况。

6. 文件上传参数

FastAPI 也支持上传文件:

python 复制代码
from fastapi import File, UploadFile

@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

📌 测试方式: 在 API 工具(如 Postman)上传文件,返回:

json 复制代码
{"filename": "example.txt"}

🚀 关键点

  • UploadFile 允许获取文件名、内容、MIME 类型等信息。

总结

参数类型 适用情况 示例
路径参数 URL 路径中的必需参数 /items/{item_id}
查询参数 可选参数,使用 ?key=value 形式 /search/?q=FastAPI&page=2
请求体参数 发送 JSON 数据 POST /items/
路径+查询参数 结合两者 /users/{user_id}?detailed=true
表单参数 application/x-www-form-urlencoded 表单提交 POST /login/
文件上传参数 上传文件 POST /upload/

你可以根据自己的需求灵活运用不同的参数传递方式,现在试着在本地运行 FastAPI 代码,看看效果吧!🚀

相关推荐
曲幽16 小时前
FastAPI + SQLite:从基础CRUD到安全并发的实战指南
python·sqlite·fastapi·web·jwt·form·sqlalchemy·oauth2
Psycho_MrZhang16 小时前
FastAPI 设计思想总结
fastapi
七夜zippoe18 小时前
依赖注入:构建可测试的Python应用架构
开发语言·python·架构·fastapi·依赖注入·反转
山沐与山20 小时前
【Python】深入理解Python Web框架:从Flask到FastAPI的并发之路
python·flask·fastapi
西西弗Sisyphus2 天前
Python FastAPI 和 Uvicorn 同步 (Synchronous) vs 异步 (Asynchronous)
python·fastapi·uvicorn
钱彬 (Qian Bin)2 天前
项目实践14—全球证件智能识别系统(切换回SQLite数据库并基于Docker实现离线部署和日常管理)
运维·docker·容器·fastapi·证件识别
闲人编程2 天前
电商平台用户系统API设计
数据库·后端·消息队列·fastapi·监控·容器化·codecapsule
曲幽2 天前
FastAPI + TinyDB并发陷阱与实战:告别数据错乱的解决方案
python·json·fastapi·web·并发·queue·lock·文件锁·tinydb
natide2 天前
Llama2 API部署错误调试
fastapi·llama
bst@微胖子3 天前
CrewAI+FastAPI实现多Agent协作项目
java·前端·fastapi