前置环境
本项目基于 Python 生态,依赖包较少,无需复杂配置。
pip install fastapi uvicorn requests
SQLite3 是 Python 标准库的一部分,开箱即用。
技术选型
- FastAPI: 现代异步 Web 框架,自动生成交互式文档。
- SQLite3: 轻量级嵌入式数据库,适合本地或小型服务。
- Requests: 标准的 HTTP 请求库,方便调试接口。
- Uvicorn: 高性能 ASGI 服务器,驱动 FastAPI 运行。
数据库交互
操作 SQLite 遵循'连接 - 游标 - 执行 - 提交'的标准流程。
import sqlite3
conn = sqlite3.connect("test.db")
cursor = conn.cursor()
如果目标文件不存在,连接操作会自动创建它。执行完 SQL 语句后,务必提交变更并关闭连接。
# 创建表结构
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER
)''')
# 插入记录
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("张三", 18))
# 查询数据
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()
conn.commit()
conn.close()
接口定义
使用装饰器映射 URL 路径到 Python 函数。
from fastapi import FastAPI
app = FastAPI()
@app.get("/hello")
def hello():
return {"message": "Hello FastAPI"}
@app.post("/add")
def add(name: str, age: int):
return {"接收数据": {: name, : age}}


