FastAPI 查询参数完全指南:从基础到高级用法 🚀
title: FastAPI 查询参数完全指南:从基础到高级用法 🚀
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
@app.get("/users/")
async def read_users(user_id: int, is_active: bool = True):
return {"user_id": user_id, "is_active": is_active}
@app.get("/products/")
async def read_products(page: int = 1, per_page: int = 20):
return {"page": page, "per_page": per_page}
@app.get("/search/")
async def search_items(q: str, skip: int = 0, limit: int = 10):
return {"q": q, "skip": skip, "limit": limit}
from typing import List
@app.get("/products/")
async def read_products(categories: List[str] = Query(...)):
return {"categories": categories}
from pydantic import Field
@app.get("/orders/")
async def read_orders(order_id: int = Query(..., gt=0), status: str = Field(..., regex=r"^(pending|completed)$")):
return {"order_id": order_id, "status": status}
@app.get("/users/")
async def read_users(user_id: int = Query(..., alias="id")):
return {"user_id": user_id}
@app.get("/products/")
async def read_products(category: str = Query(..., description="Filter products by category")):
return {"category": category}
@app.get("/items/")
async def read_items(old_param: str = Query(None, deprecated=True)):
return {"old_param": old_param}
@app.get("/items/")
async def read_items(required_param: int, optional_param: str = "default"):
return {"required_param": required_param, "optional_param": optional_param}
from typing import List
@app.get("/products/")
async def read_products(categories: List[str] = Query(...)):
return {"categories": categories}
错误代码 | 典型触发场景 | 解决方案 |
---|---|---|
422 | 类型转换失败/正则不匹配 | 检查参数定义的校验规则 |
404 | 查询参数格式正确但资源不存在 | 验证业务逻辑中的数据存在性 |
500 | 未捕获的参数处理异常 | 添加 try/except 包裹敏感操作 |
400 | 自定义校验规则触发拒绝 | 检查验证器的逻辑条件 |
from enum import Enum
class Status(str, Enum):
ACTIVE = "active"
INACTIVE = "inactive"
@app.get("/users/")
async def get_users(status: Status):
return {"status": status}
@app.get("/files/")
async def read_files(path: str = Query(..., alias="file-path")):
return {"path": path}
curl -X GET "http://localhost:8000/items/?skip=0&limit=10"
评论
发表评论