FastAPI 实战:高效构建 Web API 并集成 MySQL 数据库
FastAPI 作为一款现代化的 Python Web 框架,凭借其高性能、易用性和自动生成 API 文档的特性,迅速成为开发 Web API 的热门选择。对于需要持久化数据的项目,连接 MySQL 数据库是不可或缺的一环。本文将详细介绍如何使用 FastAPI 快速开发 Web API 项目,并重点讲解如何与 MySQL 数据库建立连接,实现数据的增删改查(CRUD)操作。
一、FastAPI 简介与优势
FastAPI 基于 Starlette 和 Pydantic 构建,支持异步请求处理,能够提供接近原生异步框架的性能。其核心优势包括:
- 自动生成交互式 API 文档:基于 OpenAPI 和 JSON Schema,自动生成 Swagger UI 和 ReDoc 文档,极大提升开发效率。
- 类型提示支持:利用 Python 的类型提示功能,提供编辑器支持,减少错误。
- 高性能:基于 Starlette 的异步特性,能够处理高并发请求。
- 简洁的语法:代码简洁易读,适合快速开发。
二、环境准备与依赖安装
在开始开发前,需要确保环境配置正确,并安装必要的依赖库。
1. 创建项目目录
mkdir fastapi_mysql_democd fastapi_mysql_demopython -m venv venvsource venv/bin/activate # Linux/macOS# venv\Scripts\activate # Windows
2. 安装 FastAPI 和 Uvicorn
Uvicorn 是一个 ASGI 服务器,用于运行 FastAPI 应用。
pip install fastapi uvicorn
3. 安装 MySQL 连接库
选择 mysql-connector-python 或 pymysql 作为 MySQL 的 Python 客户端。
pip install mysql-connector-python# 或pip install pymysql
三、连接 MySQL 数据库
1. 配置数据库连接
在项目中创建一个 database.py 文件,用于管理数据库连接。
import mysql.connectorfrom mysql.connector import Errordef create_connection():"""创建并返回数据库连接"""try:connection = mysql.connector.connect(host='localhost',user='your_username',password='your_password',database='your_database')if connection.is_connected():print("成功连接到 MySQL 数据库")return connectionexcept Error as e:print(f"连接 MySQL 数据库时出错: {e}")return None
2. 使用连接池(可选)
对于高并发应用,建议使用连接池管理数据库连接。
from mysql.connector import poolingdbconfig = {"host": "localhost","user": "your_username","password": "your_password","database": "your_database"}connection_pool = pooling.MySQLConnectionPool(pool_name="my_pool",pool_size=5,**dbconfig)def get_connection():"""从连接池获取连接"""return connection_pool.get_connection()
四、实现 CRUD 操作
1. 创建数据模型
使用 Pydantic 定义数据模型,用于数据的验证和序列化。
from pydantic import BaseModelclass Item(BaseModel):name: strdescription: str | None = Noneprice: floaton_offer: bool = False
2. 实现 CRUD 路由
在 main.py 中定义 FastAPI 应用,并实现 CRUD 路由。
from fastapi import FastAPI, HTTPExceptionfrom typing import Listfrom database import create_connection, get_connection # 假设已实现from pydantic import BaseModelapp = FastAPI()# 模拟数据库表操作class Item(BaseModel):name: strdescription: str | None = Noneprice: floaton_offer: bool = False# 假设的数据库表items_db = []@app.post("/items/", response_model=Item)def create_item(item: Item):"""创建新项目"""# 实际应用中,这里应插入数据库items_db.append(item)return item@app.get("/items/", response_model=List[Item])def read_items():"""获取所有项目"""# 实际应用中,这里应从数据库查询return items_db@app.get("/items/{item_id}", response_model=Item)def read_item(item_id: int):"""根据ID获取项目"""# 实际应用中,这里应从数据库查询if item_id < len(items_db):return items_db[item_id]raise HTTPException(status_code=404, detail="Item not found")@app.put("/items/{item_id}", response_model=Item)def update_item(item_id: int, item: Item):"""更新项目"""# 实际应用中,这里应更新数据库if item_id < len(items_db):items_db[item_id] = itemreturn itemraise HTTPException(status_code=404, detail="Item not found")@app.delete("/items/{item_id}")def delete_item(item_id: int):"""删除项目"""# 实际应用中,这里应从数据库删除if item_id < len(items_db):del items_db[item_id]return {"message": "Item deleted successfully"}raise HTTPException(status_code=404, detail="Item not found")
实际数据库操作示例(以 create_item 为例):
from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom database import get_connection # 假设使用连接池app = FastAPI()class Item(BaseModel):name: strdescription: str | None = Noneprice: floaton_offer: bool = False@app.post("/items/", response_model=Item)def create_item(item: Item):"""创建新项目并插入数据库"""connection = get_connection()if connection is None:raise HTTPException(status_code=500, detail="Database connection failed")try:cursor = connection.cursor()query = """INSERT INTO items (name, description, price, on_offer)VALUES (%s, %s, %s, %s)"""cursor.execute(query, (item.name, item.description, item.price, item.on_offer))connection.commit()# 假设能获取自增ID(实际需根据数据库调整)item.id = cursor.lastrowidreturn itemexcept Error as e:connection.rollback()raise HTTPException(status_code=500, detail=str(e))finally:cursor.close()connection.close() # 注意:实际连接池实现中可能不需要显式关闭
五、运行与测试
1. 运行 FastAPI 应用
uvicorn main:app --reload
2. 测试 API
使用浏览器访问 http://127.0.0.1:8000/docs,利用 Swagger UI 测试 API。
或使用 curl:
# 创建项目curl -X POST "http://127.0.0.1:8000/items/" -H "accept: application/json" -H "Content-Type: application/json" -d '{"name": "Foo", "description": "An item", "price": 10.5, "on_offer": false}'# 获取所有项目curl "http://127.0.0.1:8000/items/"
六、最佳实践与注意事项
- 错误处理:妥善处理数据库异常,避免泄露敏感信息。
- 连接管理:使用连接池管理数据库连接,避免频繁创建和销毁连接。
- 安全性:使用环境变量存储数据库凭据,避免硬编码。
- 异步支持:对于 I/O 密集型操作,考虑使用异步数据库客户端(如
asyncpg配合databases库)。 - ORM 使用:对于复杂项目,可考虑使用 SQLAlchemy 或 Tortoise-ORM 等 ORM 工具。
七、总结
通过本文,我们了解了如何使用 FastAPI 快速开发 Web API 项目,并详细讲解了如何与 MySQL 数据库建立连接,实现数据的 CRUD 操作。FastAPI 的高性能和易用性,结合 MySQL 的稳定性和可靠性,为开发高效的 Web API 项目提供了强大的支持。希望本文能为你的 FastAPI 开发之路提供有益的指导。