Python FastAPI介绍
Python FastAPI 说明
1. 简介
FastAPI 是一个现代、高性能的 Web 框架,用于基于 Python 3.7+ 构建 API。它基于标准 Python 类型提示(type hints)构建,能够自动生成交互式 API 文档,并具备数据验证、序列化、依赖注入等强大功能。FastAPI 底层使用 Starlette(处理 Web 部分)和 Pydantic(处理数据部分),因此性能出色,常被比作“Python 领域的 Node.js 或 Go”。
2. 主要特点
- 高性能:性能与 Node.js 和 Go 相当,是 Python 最快的 Web 框架之一。
- 开发效率高:借助类型提示和自动文档,开发速度可提升 2~3 倍。
- 减少错误:通过 Pydantic 进行数据验证,可减少约 40% 的人为错误。
- 智能编辑器支持:代码补全、类型检查等功能完善。
- 易于使用:设计简洁,学习曲线平缓,但功能强大。
- 基于标准:完全兼容 OpenAPI、JSON Schema 和 OAuth 2.0 等标准。
- 自动文档:自动生成 Swagger UI(
/docs)和 ReDoc(/redoc)交互式文档。 - 原生异步:支持
async/await,也兼容同步函数。
3. 安装
需要 Python 3.7 及以上版本。
pip install fastapi
pip install "uvicorn[standard]"
uvicorn 是 ASGI 服务器,用于运行 FastAPI 应用。[standard] 会安装一些常用依赖(如 websockets、httptools 等)。
4. 快速开始
创建一个 main.py 文件:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
运行服务器:
uvicorn main:app --reload
main:模块名(文件名main.py)app:FastAPI 实例变量名--reload:开发模式下自动重载(代码修改后自动重启)
启动后访问:
http://127.0.0.1:8000/items/5?q=hello返回{"item_id":5,"q":"hello"}http://127.0.0.1:8000/docs查看自动生成的 Swagger UI 文档http://127.0.0.1:8000/redoc查看 ReDoc 文档
5. 核心概念
5.1 路径参数(Path Parameters)
路径参数使用 {} 声明,FastAPI 会自动根据类型提示进行转换和验证。
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}
访问 /users/abc 会返回 422 验证错误,因为 abc 不是整数。
5.2 查询参数(Query Parameters)
函数参数中不属于路径参数的参数会自动被视为查询参数。
@app.get("/search")
def search(q: str = None, page: int = 1, size: int = 10):
return {"q": q, "page": page, "size": size}
5.3 请求体(Request Body)
使用 Pydantic 模型定义请求体,FastAPI 会自动验证、转换和生成文档。
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post("/items")
def create_item(item: Item):
return {"item_name": item.name, "item_price": item.price}
客户端发送 JSON 时,FastAPI 会解析并验证数据类型。
5.4 数据验证与响应模型
- 请求验证:通过 Pydantic 模型自动校验字段类型、必填项、默认值等。
- 响应模型:使用
response_model参数指定返回数据结构,自动过滤、转换和文档化。
@app.post("/items", response_model=Item)
def create_item(item: Item):
return item
5.5 依赖注入(Dependency Injection)
FastAPI 提供了一个简单但强大的依赖注入系统,用于共享逻辑、数据库连接、认证等。
from fastapi import Depends
def common_parameters(q: str = None, page: int = 1):
return {"q": q, "page": page}
@app.get("/items")
def list_items(commons: dict = Depends(common_parameters)):
return commons
依赖可以嵌套,也可以使用类、生成器等。
5.6 安全性(Security)
FastAPI 内置了对 OAuth2、API Key、HTTP Basic 等安全方案的支持。
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.get("/users/me")
def read_current_user(token: str = Depends(oauth2_scheme)):
return {"token": token}
5.7 中间件(Middleware)
中间件可以在请求处理前后执行代码。
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
5.8 后台任务(Background Tasks)
用于在响应发送后执行一些轻量级任务。
from fastapi import BackgroundTasks
def write_log(message: str):
with open("log.txt", "a") as f:
f.write(message + "\n")
@app.post("/send-notification")
def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, f"Notification sent to {email}")
return {"message": "Notification sent"}
5.9 异步支持
FastAPI 原生支持 async def 和 def。对于 I/O 密集型操作,使用 async def 可以提高并发性能。
@app.get("/async")
async def read_async():
await some_async_operation()
return {"message": "async"}
如果使用同步函数,FastAPI 会在线程池中运行,不会阻塞事件循环。
6. 自动文档
FastAPI 根据代码中的类型提示和 Pydantic 模型自动生成 OpenAPI Schema,并提供两种交互式文档:
- Swagger UI:
/docs— 可直接在浏览器中测试 API - ReDoc:
/redoc— 更适合阅读的文档格式
这些文档会实时反映代码变化,无需额外维护。
7. 项目结构建议
对于一个中等规模的项目,推荐以下目录结构:
project/
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI 入口
│ ├── models.py # Pydantic 模型
│ ├── routers/ # 路由模块
│ │ ├── __init__.py
│ │ ├── users.py
│ │ └── items.py
│ ├── dependencies.py # 依赖项
│ └── config.py # 配置
├── tests/
└── requirements.txt
使用 APIRouter 组织路由:
# app/routers/users.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/users")
def list_users():
return [{"username": "alice"}]
在 main.py 中引入:
from fastapi import FastAPI
from app.routers import users
app = FastAPI()
app.include_router(users.router)
8. 部署
生产环境通常使用 uvicorn 配合 gunicorn 或直接使用 uvicorn。
使用 uvicorn 直接运行:
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
使用 gunicorn(需要安装 gunicorn 和 uvicorn.workers.UvicornWorker):
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
也可以使用 Docker 部署,FastAPI 官方提供了基础镜像。
9. 总结
FastAPI 结合了 Python 的简洁性和现代 Web 框架的高性能,通过类型提示和 Pydantic 提供了强大的数据验证和自动文档功能。它非常适合构建 RESTful API、微服务、实时应用等。无论是初学者还是有经验的开发者,都能快速上手并高效开发。
- 点赞
- 收藏
- 关注作者
评论(0)