FastAPI 的快速入门指南
以下是 FastAPI 的快速入门指南,涵盖从安装到构建第一个API的关键步骤,适合零基础快速上手:
1. 环境准备
# 创建虚拟环境(可选) python -m venv venv source venv/bin/activate # Linux/Mac venv\Scripts\activate # Windows # 安装FastAPI和Uvicorn(ASGI服务器) pip install fastapi uvicorn
2. 第一个API:Hello World
创建一个文件 main.py
:
from fastapi import FastAPI app = FastAPI() # 创建应用实例 @app.get("/") # 定义GET路由 async def root(): return {"message": "Hello World"}
启动服务:
uvicorn main:app --reload
main:app
:main.py
中的app
实例--reload
:开发时自动重启(生产环境去掉)
访问:
API端点:
http://127.0.0.1:8000/
交互文档:
http://127.0.0.1:8000/docs
(自动生成!)
3. 核心功能快速掌握
① 路径参数
@app.get("/items/{item_id}") async def read_item(item_id: int): # 自动类型转换 return {"item_id": item_id}
访问示例:
/items/42
→ 返回{"item_id": 42}
无效类型(如字符串
/items/foo
)会自动返回422错误!
② 查询参数
@app.get("/items/") async def list_items(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}
访问示例:
/items/?skip=20&limit=5
③ 请求体(POST)
使用 Pydantic
模型自动校验数据:
from pydantic import BaseModel class Item(BaseModel): name: str price: float @app.post("/items/") async def create_item(item: Item): # 自动解析请求体 return {"item": item.dict()}
通过
/docs
页面直接测试POST请求!
④ 异步支持
import httpx # 需要安装 pip install httpx @app.get("/fetch-data") async def fetch_external_data(): async with httpx.AsyncClient() as client: response = await client.get("https://api.example.com/data") return response.json()
4. 自动API文档
FastAPI自动生成两种文档:
Swagger UI:
/docs
(交互式测试)ReDoc:
/redoc
(简洁版文档)
无需手动编写,所有路由、参数和返回值自动展示!
5. 调试技巧
查看请求详情:在函数中添加
print(item)
或日志。错误处理:
from fastapi import HTTPException @app.get("/items/{item_id}") async def read_item(item_id: int): if item_id not in database: raise HTTPException(status_code=404, detail="Item not found") return {"item": database[item_id]}
6. 项目结构建议(进阶)
my_project/ ├── main.py # 入口文件 ├── routers/ # 路由拆分 │ ├── items.py │ └── users.py ├── models.py # Pydantic模型 └── database.py # 数据库连接
在 main.py
中引入路由:
from routers import items, users app.include_router(items.router) app.include_router(users.router)
7. 学习资源推荐
实战教程:
视频课程:YouTube上的《FastAPI Full Course》(免费)
总结
5分钟启动:安装 → 写路由 →
uvicorn
运行。核心三板斧:路径参数、查询参数、请求体模型。
杀手锏功能:自动文档、异步支持、类型安全。
下一步:尝试连接数据库(如SQLAlchemy或MongoDB)或添加用户认证(OAuth2)。
按照这个流程,半天即可完成基础功能开发!