通过实战的形式带我学会使用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 代码,看看效果吧!🚀

相关推荐
勘察加熊人1 天前
fastapi+angular外卖系统
前端·fastapi·angular.js
堕落年代3 天前
Python使用FastAPI结合Word2vec来向量化200维的语言向量数值
开发语言·python·fastapi
勘察加熊人3 天前
fastapi +angular迷宫求解可跨域
前端·fastapi·angular.js
勘察加熊人4 天前
fastapi+angular实现Tcp在线聊天室功能
tcp/ip·fastapi·angular.js
m0_751018666 天前
fastapi celery flower rabbitmq redis 可运行demo
分布式·rabbitmq·fastapi
AI浩6 天前
【高并发】高速将图片提交到flask、fastapi等主流服务框架
python·flask·fastapi
Wiktok7 天前
基于ThinkPHP6用户登录逻辑,结合FastAPI框架实现用户登录系统的全流程解析
python·fastapi
Amd7947 天前
FastAPI 核心机制:分页参数的实现与最佳实践
性能优化·fastapi·安全实践·web开发·分页·错误处理·数据库查询
小宁爱Python7 天前
Python从入门到精通1:FastAPI
python·beautifulsoup·numpy·fastapi