简介:本文详细介绍FastAPI框架的核心特性、安装步骤、基础路由与请求处理、数据验证与模型定义、以及异步编程支持,帮助开发者快速掌握FastAPI的使用方法。
在Python生态中,Web框架的选择直接影响开发效率与项目性能。传统框架如Django功能全面但相对重型,Flask轻量灵活但需手动集成许多功能。而FastAPI作为新一代异步Web框架,凭借其高性能、自动API文档生成和类型提示支持,迅速成为开发者构建现代API的首选。其核心优势包括:
async/await语法,提升高并发场景性能。FastAPI运行需Python 3.7+,推荐使用虚拟环境隔离项目依赖:
python -m venv fastapi_envsource fastapi_env/bin/activate # Linux/macOS# 或 fastapi_env\Scripts\activate (Windows)
FastAPI本身不包含服务器,需搭配ASGI服务器(如Uvicorn)运行:
pip install fastapi uvicorn
新建main.py文件,定义一个简单GET接口:
from fastapi import FastAPIapp = FastAPI()@app.get("/")def read_root():return {"message": "Hello FastAPI!"}
运行服务:
uvicorn main:app --reload
main:app:模块名:对象名。--reload:开发模式自动重载代码变更。路径参数:通过{param}定义动态路径:
@app.get("/items/{item_id}")def read_item(item_id: int):return {"item_id": item_id}
查询参数:通过函数参数直接获取:
@app.get("/search/")def search_items(query: str, limit: int = 10):return {"query": query, "limit": limit}
通过BaseModel定义请求/响应数据结构:
from pydantic import BaseModelclass Item(BaseModel):name: strdescription: str | None = Noneprice: floattax: float | None = None@app.post("/items/")def create_item(item: Item):item_dict = item.dict()if item.tax:price_with_tax = item.price + item.taxitem_dict.update({"price_with_tax": price_with_tax})return item_dict
item.dict()转换为字典。支持复杂数据结构:
class User(BaseModel):username: strfull_name: str | None = Noneclass Order(BaseModel):user: Useritems: list[Item]@app.post("/orders/")def create_order(order: Order):return order
使用async def定义异步接口,调用异步数据库操作:
from fastapi import FastAPI, Dependsimport httpxasync def fetch_data(url: str):async with httpx.AsyncClient() as client:return await client.get(url)@app.get("/async-data/")async def get_async_data(url: str = "https://example.com"):response = await fetch_data(url)return response.json()
通过Depends实现依赖注入,支持异步依赖项:
async def get_db():# 模拟异步数据库连接db = {"users": []}yield dbdb.clear() # 清理资源@app.get("/users/")async def read_users(db: dict = Depends(get_db)):return db["users"]
启动服务后,访问以下URL:
http://127.0.0.1:8000/docshttp://127.0.0.1:8000/redoc通过FastAPI初始化参数配置文档元数据:
app = FastAPI(title="商品管理系统",description="基于FastAPI的RESTful API",version="1.0.0",contact={"name": "开发者", "url": "http://example.com"},)
全局处理请求/响应,如记录日志:
from fastapi import Requestasync def log_middleware(request: Request, call_next):print(f"请求路径: {request.url.path}")response = await call_next(request)print(f"响应状态码: {response.status_code}")return responseapp.middleware("http")(log_middleware)
--workers 4利用多核。@cache装饰器(需安装cachetools)。asyncpg(PostgreSQL)或aiomysql。
from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom typing import Optionalapp = FastAPI()# 模型定义class Product(BaseModel):name: strprice: floatstock: int = 0# 模拟数据库fake_db = []# 路由@app.post("/products/")def create_product(product: Product):fake_db.append(product)return {"message": "商品创建成功"}@app.get("/products/{product_id}")def get_product(product_id: int):if product_id >= len(fake_db):raise HTTPException(status_code=404, detail="商品不存在")return fake_db[product_id]@app.put("/products/{product_id}")def update_product(product_id: int, product: Product):if product_id >= len(fake_db):raise HTTPException(status_code=404, detail="商品不存在")fake_db[product_id] = productreturn {"message": "商品更新成功"}
numpy与pandas高效处理数据。通过本文的快速入门,开发者已掌握FastAPI的核心功能。建议进一步探索依赖注入系统、安全模块(OAuth2)和测试工具(TestClient),以构建更健壮的Web应用。