FastAPI

适合:小白入门 / 老程序员快速掌握 / 企业级团队文档

FastAPI 是一个现代、高性能的 Python Web 框架,基于 Starlette(异步 Web 框架)Pydantic(数据验证) 构建,拥有自动文档、强类型、异步支持等特性。 它的性能接近 Node.js 和 Go,非常适合构建高并发 API 服务。

1. FastAPI 的核心优势(企业级视角)

特性 说明
高性能 基于 async/await,性能接近 Node.js/Go
自动文档 自动生成 Swagger UI / ReDoc(官方教程强调)
强类型 基于 Python 类型提示,自动校验请求数据
异步支持 原生 async/await
依赖注入(DI) 内置 DI 系统,适合大型项目
可扩展性强 基于 Starlette,可用中间件、事件、WebSocket

2. 快速上手(Hello World)

创建 main.py

复制代码
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def index():
    return {"message": "Hello FastAPI"}

运行(官方教程示例):

复制代码
fastapi dev main.py

自动文档:

  • Swagger UI: http://127.0.0.1:8000/docs

  • ReDoc: http://127.0.0.1:8000/redoc

3. 路由(API 构建基础)

3.1 基础路由

复制代码
@app.get("/users")
def get_users():
    return ["Tom", "Jerry"]

3.2 路径参数

复制代码
@app.get("/users/{user_id}")
def get_user(user_id: int):
    return {"id": user_id}

3.3 查询参数

复制代码
@app.get("/search")
def search(keyword: str, limit: int = 10):
    return {"keyword": keyword, "limit": limit}

4. Pydantic 模型(FastAPI 的灵魂)

Pydantic 用于 数据验证 + 自动文档 + 自动类型转换

复制代码
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

用于 POST 请求:

复制代码
@app.post("/users")
def create_user(user: User):
    return user

5. 异步支持(async/await)

FastAPI 原生支持异步(官方教程强调 async/await 支持):

复制代码
@app.get("/items")
async def get_items():
    return ["a", "b", "c"]

适合:

  • 高并发

  • I/O 密集型(数据库、HTTP 调用)

  • WebSocket

6. 依赖注入(DI)------企业级必备

FastAPI 内置 DI 系统,非常适合大型项目(GitHub 完整课程也包含 DI 章节)。

复制代码
from fastapi import Depends

def get_db():
    db = "db connection"
    return db

@app.get("/items")
def read_items(db = Depends(get_db)):
    return {"db": db}

用途:

  • 数据库连接

  • 权限校验

  • 配置管理

  • 业务服务注入

7. 中间件(Middleware)

复制代码
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

用途:

  • CORS

  • 日志

  • 鉴权

  • 限流

8. 异常处理(企业级)

复制代码
from fastapi import HTTPException

@app.get("/error")
def error():
    raise HTTPException(status_code=404, detail="Not Found")

自定义异常:

复制代码
from fastapi.responses import JSONResponse

@app.exception_handler(ValueError)
def value_error_handler(request, exc):
    return JSONResponse(status_code=400, content={"error": str(exc)})

9. 数据库集成(SQLAlchemy)

GitHub 完整课程包含数据库集成章节。

复制代码
from sqlalchemy.orm import Session
from fastapi import Depends

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

10. 项目结构(企业级)

复制代码
app/
│── main.py
│── api/
│   ├── users.py
│   ├── auth.py
│── models/
│── schemas/
│── services/
│── core/
│   ├── config.py
│   ├── security.py
│── db/
│   ├── session.py
│   ├── base.py

特点:

  • 路由模块化

  • 数据模型与 Pydantic schema 分离

  • 业务逻辑放在 service 层

  • 配置集中管理

11. 自动文档(Swagger / ReDoc)

FastAPI 自动生成文档(官方教程强调自动文档能力)。

你可以自定义:

复制代码
app = FastAPI(
    title="My API",
    description="企业级 API 文档",
    version="1.0.0"
)

12. 安全(OAuth2 / JWT)

FastAPI 内置 OAuth2 支持。

复制代码
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/me")
def read_me(token: str = Depends(oauth2_scheme)):
    return {"token": token}

13. 性能优化(企业级)

GitHub 完整课程包含性能优化章节。

  • 使用 Uvicorn + Gunicorn(多 worker)

  • 使用 async/await

  • 数据库连接池

  • 缓存(Redis)

  • 中间件限流

  • Pydantic v2(更快)

14. 部署(生产环境)

推荐架构:

复制代码
Nginx → Gunicorn → UvicornWorker → FastAPI

启动:

复制代码
gunicorn main:app -k uvicorn.workers.UvicornWorker -w 4 -b 0.0.0.0:8000

15. 测试(pytest)

复制代码
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_index():
    r = client.get("/")
    assert r.status_code == 200

16. 高级功能(官方教程包含大量进阶内容)

  • WebSocket

  • Background Tasks

  • Events(startup/shutdown)

  • Streaming Response

  • File Upload

  • CORS

  • 自定义中间件

  • 异步数据库(SQLModel / Tortoise ORM)

17. 学习路线(结合 GitHub 完整课程笔记)

  1. API 基础

  2. FastAPI 基础

  3. 构建 REST API

  4. 数据库集成

  5. JWT 鉴权

  6. 异步编程

  7. 高级特性(WebSocket、依赖注入)

  8. 测试与调试

  9. 性能优化

  10. 部署(Docker + Nginx + Gunicorn)

相关推荐
minhuan22 分钟前
搭建本地人脸识别系统:解析FastAPI+InsightFace+FAISS全栈实现原理与优化方案26.6
fastapi·faiss·insightface·大模型应用·人脸识别模型·本地化人脸识别系统
tryCbest1 小时前
FastAPI中passlib包的作用
python·fastapi·passlib
青 春 记 忆21 小时前
零基础入门python66:FastAPI AI标题、摘要和标签
python·fastapi·后端开发
青 春 记 忆21 小时前
零基础入门python65:FastAPI 安全调用大模型API
python·fastapi·后端开发
逆风飞翔的小叔1 天前
【Python 基础】FastAPI ORM 操作MySql 实战使用详解
fastapi·fastapi orm·fastapi orm详解·fastapi orm使用·fastapi orm操作
青 春 记 忆1 天前
零基础入门python68:FastAPI 完整博客运行与项目验收
python·fastapi·后端开发
青 春 记 忆1 天前
零基础入门python69:为 FastAPI 项目构建可复现 Docker 镜像
python·fastapi·后端开发
the局外人1 天前
学习 FastAPI 的 Day 2:用异步 ORM 完成增删改查
后端·python·fastapi
2601_962283881 天前
Python 开发框架:Django、Flask和FastAPI
python·django·flask·fastapi·web开发
cui_ruicheng2 天前
FastAPI 应用开发(二):请求响应、Pydantic 模型与依赖注入
python·fastapi·web