Python FastAPI 快速入门:构建高性能异步 API

Raj Kumar | 2026-08-27T20:54:49 | Python

从零搭建 FastAPI 项目,涵盖路由定义、Pydantic 校验、依赖注入、中间件和自动文档生成。

# Python FastAPI 快速入门 ## 为什么选 FastAPI? FastAPI 基于 Starlette 和 Pydantic,性能接近 Node.js/Go,同时拥有自动 API 文档和类型安全。 ## 安装 ```bash pip install fastapi uvicorn[standard] ``` ## 基础应用 ```python from fastapi import FastAPI, HTTPException from pydantic import BaseModel, Field from typing import Optional, List import uvicorn app = FastAPI(title="Blog API", version="1.0.0") # 数据模型 class PostCreate(BaseModel): title: str = Field(..., min_length=1, max_length=200) content: str = Field(..., min_length=10) tags: List[str] = [] class PostResponse(BaseModel): id: int title: str content: str tags: List[str] created_at: str # 内存存储(演示用) posts_db = [] next_id = 1 @app.post("/posts", response_model=PostResponse, status_code=201) async def create_post(post: PostCreate): global next_id from datetime import datetime new_post = { "id": next_id, "title": post.title, "content": post.content, "tags": post.tags, "created_at": datetime.now().isoformat(), } posts_db.append(new_post) next_id += 1 return new_post @app.get("/posts", response_model=List[PostResponse]) async def list_posts(skip: int = 0, limit: int = 10, tag: Optional[str] = None): result = posts_db if tag: result = [p for p in result if tag in p["tags"]] return result[skip:skip + limit] @app.get("/posts/{post_id}", response_model=PostResponse) async def get_post(post_id: int): for p in posts_db: if p["id"] == post_id: return p raise HTTPException(status_code=404, detail="文章不存在") ``` ## 依赖注入 ```python from fastapi import Depends from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials security = HTTPBearer() async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)): token = credentials.credentials # 验证 JWT token user = verify_jwt(token) if not user: raise HTTPException(status_code=401, detail="无效的 Token") return user @app.get("/me") async def get_profile(user = Depends(get_current_user)): return {"id": user.id, "name": user.name} ``` ## 中间件 ```python import time from fastapi import Request @app.middleware("http") async def add_process_time_header(request: Request, call_next): start = time.time() response = await call_next(request) process_time = time.time() - start response.headers["X-Process-Time"] = "{:.4f}".format(process_time) return response ``` ## 启动 ```bash uvicorn main:app --reload --host 0.0.0.0 --port 8000 ``` 访问 `http://localhost:8000/docs` 查看自动生成的 Swagger UI。 ## 与 Flask/Django 的对比 | 特性 | FastAPI | Flask | Django REST | |------|---------|-------|------------| | 异步 | 原生 | 需扩展 | 3.1+ | | 类型校验 | 自动 | 手动 | Serializer | | 文档 | 自动 | 手动 | 需插件 | | 性能 | 极高 | 中等 | 中等 |

← Back to Blog