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

相关推荐
Anesthesia丶2 天前
Vue3 + naive-ui + fastapi使用心得
vue.js·ui·fastapi
weixin_307779132 天前
使用FastAPI微服务在AWS EKS中构建上下文增强型AI问答系统
人工智能·python·云计算·fastapi·aws
掘金-我是哪吒2 天前
分布式微服务系统架构第130集:Python工程化FastAPI,运维Nginx-keepalived+Nginx实现高可用集群
运维·分布式·微服务·系统架构·fastapi
LingRannn2 天前
JWT的介绍与在Fastapi框架中的应用
fastapi
Python私教3 天前
使用FastAPI和React以及MongoDB构建全栈Web应用05 FastAPI快速入门
前端·react.js·fastapi
Python私教3 天前
全栈开发实战:FastAPI + React + MongoDB 构建现代Web应用
前端·react.js·fastapi
weixin_307779134 天前
使用FastAPI和Apache Flink构建跨环境数据管道
redis·python·云计算·fastapi·aws
真智AI7 天前
构建安全的机器学习推理API:基于FastAPI的用户认证与管理实战
安全·机器学习·fastapi
Data 实验室10 天前
爬虫管理平台-最新版本发布
开发语言·爬虫·python·fastapi
eihh2333310 天前
模型部署与提供服务
fastapi·llamafactory