跳过正文
  1. 文章/

FastAPI 完全指南:Python 现代高性能 Web 框架

·702 字·4 分钟
sun.ao
作者
sun.ao
我是 sun.ao,一名热爱技术的程序员,专注于 AI 和数智化领域。
目录

当 Python 开发者厌倦了 Flask 的"随意"和 Django 的"笨重"时,FastAPI 出现了。它以"快"为名,迅速成为 Python Web 开发的新宠。

FastAPI 是什么?
#

FastAPI 是 Sebastian Ramirez 于 2018 年创建的现代 Python Web 框架。它的核心特点是:高性能、异步支持、自动文档、现代 Python

类比理解
#

对比项DjangoFlaskFastAPI
风格全家桶微型现代微框架
异步需要额外配置需要额外配置原生支持
文档Admin 后台需要额外配置自动生成
性能较低中等非常高
就像豪华轿车自行车电动车

FastAPI 的性能可以与 Node.js 和 Go 相媲美,是 Python 生态最快的框架之一。

核心特性
#

1. 异步支持:async/await 原生
#

FastAPI 原生支持 Python 的 async/await 语法:

from fastapi import FastAPI
import asyncio

app = FastAPI()

# 异步路径操作
@app.get("/async-data")
async def get_async_data():
    # 使用 await 进行异步操作
    data = await fetch_data_from_api()
    return data

# 同步路径操作(也可以)
@app.get("/sync-data")
def get_sync_data():
    data = fetch_data_sync()
    return data

async def fetch_data_from_api():
    await asyncio.sleep(1)  # 模拟异步 IO
    return {"message": "异步获取的数据"}

def fetch_data_sync():
    time.sleep(1)  # 模拟同步 IO
    return {"message": "同步获取的数据"}

2. 类型提示:现代 Python
#

FastAPI 完全基于 Python 类型提示:

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional, List

app = FastAPI()

# 定义数据模型
class User(BaseModel):
    name: str
    email: str
    age: Optional[int] = None
    tags: List[str] = []

# 类型提示的路径参数
@app.get("/users/{user_id}")
async def get_user(user_id: int) -> User:
    return User(
        name="张三",
        email="zhangsan@example.com",
        age=25,
        tags=["developer", "python"]
    )

# 请求体
@app.post("/users")
async def create_user(user: User) -> User:
    # 自动验证数据类型
    return user

3. 自动生成 API 文档
#

FastAPI 自动生成交互式 API 文档:

  • Swagger UI/docs
  • ReDoc/redoc
from fastapi import FastAPI

app = FastAPI(
    title="我的 API",
    description="这是一个示例 API",
    version="1.0.0"
)

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
    """
    读取项目

    - **item_id**: 项目 ID
    - **q**: 可选的查询参数
    """
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

访问 http://localhost:8000/docs 即可看到自动生成的交互式文档。

4. 数据验证:Pydantic
#

FastAPI 使用 Pydantic 进行数据验证:

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, Field, validator

app = FastAPI()

class UserCreate(BaseModel):
    username: str = Field(..., min_length=3, max_length=50)
    email: EmailStr  # 自动验证邮箱格式
    password: str = Field(..., min_length=8)
    age: int = Field(ge=0, le=150)  # 年龄范围验证

    @validator('password')
    def password_strength(cls, v):
        if not any(c.isupper() for c in v):
            raise ValueError('密码必须包含大写字母')
        if not any(c.isdigit() for c in v):
            raise ValueError('密码必须包含数字')
        return v

@app.post("/users/")
async def create_user(user: UserCreate):
    return {"username": user.username, "email": user.email}

5. 依赖注入:强大的 DI 系统
#

FastAPI 提供了强大的依赖注入系统:

from fastapi import FastAPI, Depends, HTTPException
from typing import Annotated

app = FastAPI()

# 模拟数据库
fake_db = {"alice": {"email": "alice@example.com"}}

# 定义依赖
async def get_current_user(token: str = Depends(lambda: "current_user")):
    if token != "valid_token":
        raise HTTPException(status_code=401, detail="未授权")
    return {"username": "alice", "email": "alice@example.com"}

# 使用依赖
@app.get("/profile")
async def get_profile(user: dict = Depends(get_current_user)):
    return user

# 类作为依赖
class QueryParams:
    def __init__(self, q: str = "default", skip: int = 0, limit: int = 10):
        self.q = q
        self.skip = skip
        self.limit = limit

@app.get("/items")
async def read_items(params: QueryParams = Depends(QueryParams)):
    return {"q": params.q, "skip": params.skip, "limit": params.limit}

6. 中间件支持
#

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# CORS 中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.middleware("http")
async def add_header(request, call_next):
    response = await call_next(request)
    response.headers["X-Custom-Header"] = "FastAPI"
    return response

为什么 FastAPI 如此流行?
#

1. 性能极高
#

FastAPI 基于 Starlette(Web 框架)和 Pydantic(数据验证),性能接近 Node.js 和 Go:

框架每秒请求数
FastAPI35,000+
Flask6,000+
Django3,000+
Node.js30,000+
Go50,000+

2. 开发体验好
#

  • 类型提示:代码提示更准确
  • 自动文档:省去写文档的时间
  • 错误提示:清晰的错误信息

3. 现代 Python
#

完全基于 Python 3.7+ 的现代特性:

  • 类型提示
  • async/await
  • dataclasses

4. 适合微服务
#

FastAPI 非常适合构建微服务:

  • 轻量
  • 快速启动
  • 易于部署
  • 原生支持异步

适用场景
#

场景适合程度说明
REST API⭐⭐⭐⭐⭐核心场景
微服务⭐⭐⭐⭐⭐轻量快速
ML/AI 服务⭐⭐⭐⭐⭐Python 原生
实时应用⭐⭐⭐⭐WebSocket 支持
简单 Web 应用⭐⭐⭐可以,但 Flask 更简单
大型全栈应用⭐⭐⭐可以,Django 更适合

学习路线建议
#

入门阶段(1 周)
#

  1. 掌握 Python 基础和类型提示
  2. 理解 FastAPI 基本用法
  3. 学会定义路径操作
  4. 掌握 Pydantic 模型

进阶阶段(1-2 周)
#

  1. 深入依赖注入
  2. 掌握异步数据库操作
  3. 学会使用 SQLModel
  4. 理解中间件

高级阶段(持续学习)
#

  1. 性能优化
  2. 部署(Docker、UVicorn)
  3. 测试
  4. 与其他服务集成

与其他 Python 框架对比
#

特性FastAPIFlaskDjango
性能⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
易用性⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
功能完整⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
文档自动生成⭐⭐⭐⭐⭐⭐⭐⭐
异步支持⭐⭐⭐⭐⭐⭐⭐⭐⭐
适合场景API、微服务小型应用大型全栈

简单来说:

  • FastAPI:API 开发首选,性能高,现代
  • Flask:轻量灵活,适合小型项目
  • Django:全栈框架,适合大型项目

常用扩展
#

# 数据库
pip install sqlalchemy
pip install databases
pip install sqlmodel

# 认证
pip install python-jose[cryptography]
pip install passlib[bcrypt]

# 验证
pip install email-validator

# 异步
pip install uvicorn[standard]
pip install httpx

总结
#

FastAPI 为 Python 开发者提供了一个现代、高效的 API 开发选择:

  1. 高性能—— 接近 Node.js 和 Go
  2. 异步原生—— 充分利用 Python async/await
  3. 自动文档—— 省去编写 API 文档的时间
  4. 类型提示—— 更好的开发体验和代码提示
  5. Pydantic 验证—— 强大的数据验证能力

如果你需要构建 Python API,特别是微服务或 ML/AI 相关的服务,FastAPI 是最佳选择。


下期预告:FastAPI 用的是 Python,而 NestJS 用的是 TypeScript—— 它把 Angular 的架构思想带到了后端开发。下一篇文章我们来详细介绍这个"Node.js 版的 Spring Boot"。

相关文章