一个用来快速学习 Python 后端开发基本面的个人记账 API。项目刻意保持“小而全”:使用 FastAPI 提供 HTTP 接口,使用 Python 标准库 sqlite3 做持久化,使用 uv 管理 Python 版本、虚拟环境、依赖和锁文件,使用 pytest 与 ruff 做测试和代码质量检查。
uv sync
uv run pytest
uv run ruff check
uv run uvicorn expense_api.main:app --reload启动后打开:
也可以使用项目脚本启动:
uv run expense-apiGET /healthPOST /transactionsGET /transactionsGET /transactions/{id}PATCH /transactions/{id}DELETE /transactions/{id}GET /summaryPOST /imports/csvGET /exports/csv
创建记录示例:
curl -X POST http://127.0.0.1:8000/transactions \
-H 'Content-Type: application/json' \
-d '{
"type": "expense",
"amount": "18.90",
"category": "food",
"note": "lunch",
"occurred_on": "2026-06-11"
}'src/expense_api/
main.py # FastAPI app factory and routes
models.py # Pydantic request/response models
database.py # SQLite connection and table setup
repository.py # SQL CRUD operations
service.py # Business behavior and summary calculation
csv_io.py # CSV import/export helpers
tests/
test_health.py
test_transactions.py
test_summary.py
test_csv_io.py
CSV 导入和导出使用同一组表头:
type,amount,category,note,occurred_on
income,200.00,salary,bonus,2026-06-01
expense,12.30,books,,2026-06-03导入时非法行会被跳过并报告行号,合法行会继续写入数据库。
pyproject.toml类似 Node 项目里的package.json,保存项目元信息、依赖和工具配置。uv.lock类似package-lock.json/pnpm-lock.yaml,固定依赖解析结果。.venv/是项目虚拟环境,类似隔离的node_modules运行环境,但不提交到 git。- Pydantic 模型负责请求校验和响应序列化,FastAPI 会据此生成 OpenAPI 和
/docs。 - 金额使用
Decimal而不是float,避免二进制浮点误差。