FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。
官中用户指南
https://fastapi.tiangolo.com/zh/tutorial/
安装
pip install "fastapi[all]"
目录结构
FastAPI没有固定的目录结构要求,但是通常建议将应用程序代码和配置分开,并使用模块化的方式组织代码。一种常见的目录结构如下:
app/
├── main.py
├── api/
│ ├── __init__.py
│ ├── endpoints/
│ │ ├── __init__.py
│ │ ├── item.py
│ │ └── user.py
│ └── models/
│ ├── __init__.py
│ ├── item.py
│ └── user.py
├── core/
│ ├── __init__.py
│ ├── config.py
│ └── security.py
├── db/
│ ├── __init__.py
│ └── repository.py
└── tests/
├── __init__.py
├── conftest.py
└── test_main.py
其中:
main.py
是 FastAPI 应用程序的主入口点。api/endpoints
目录包含所有 API 端点的代码文件。api/models
目录包含数据模型的代码文件。core
目录包含应用程序的核心功能,例如配置和安全性。db
目录包含与数据库交互的相关代码文件。tests
目录包含所有测试代码文件。
模块解析
用一个示例来解析各个模块
假设我们正在为一个商品列表 API 编写 endpoints,我们可以按照以下方式组织文件:
api/
└── endpoints/
├── __init__.py
└── items.py
在 items.py
文件中,我们定义了用于处理商品 CRUD 操作的 endpoints。例如:
from fastapi import APIRouter
router = APIRouter()
@router.get("/items")
async def read_items():
# return list of all items
pass
@router.get("/items/{item_id}")
async def read_item(item_id: int):
# return item by id
pass
@router.post("/items"