第1章:FastAPI简介
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,用 Python 3.6+ 类型提示功能编写。它基于标准 Python 类型提示,这使得它非常易于学习,并且可以创建具有强大类型提示功能的代码。
1.1 FastAPI 的特点
- 快速:FastAPI 构建在 Starlette 和 Pydantic 之上,这意味着它具有高性能,并且可以快速创建 API。
- 易于学习:由于其类型提示和简单的语法,FastAPI 非常易于学习。
- 强大:FastAPI 支持异步功能,这使得它可以处理大量的并发请求。
- 跨平台:FastAPI 可以在 Windows、macOS 和 Linux 上运行。
1.2 安装 FastAPI
在开始之前,您需要安装 FastAPI。可以通过以下命令安装:
pip install fastapi uvicorn
第2章:FastAPI 基础
2.1 创建第一个 FastAPI 应用
创建一个名为 main.py 的文件,并添加以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
运行此代码,您可以使用以下命令:
uvicorn main:app --reload
这将启动一个本地服务器,并在浏览器中访问 http://127.0.0.1:8000/。
2.2 定义路由
在 FastAPI 中,使用 @app.get()、@app.post() 等装饰器来定义路由。
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
2.3 使用 Pydantic 模式
Pydantic 模式用于定义请求和响应的格式。
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
第3章:FastAPI 高级特性
3.1 异步功能
FastAPI 支持异步功能,这意味着您可以使用异步函数来处理请求。
@app.get("/items/{item_id}")
async def read_item(item_id: int):
await asyncio.sleep(1) # 模拟异步操作
return {"item_id": item_id}
3.2 依赖注入
FastAPI 支持依赖注入,这使得您可以在函数中注入其他服务。
from fastapi import Depends, HTTPException
@app.get("/users/{user_id}")
async def read_user(user_id: int, db: Session = Depends(get_db)):
user = get_user_by_id(db, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
3.3 安全性
FastAPI 支持多种安全性措施,包括 OAuth2、JWT 等。
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(fake_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status_code.UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer"}
第4章:FastAPI 最佳实践
4.1 测试
FastAPI 支持自动测试,您可以使用 pytest 来编写测试。
from fastapi.testclient import TestClient
client = TestClient(app)
response = client.get("/items/1")
assert response.status_code == 200
assert response.json() == {"item_id": 1}
4.2 部署
FastAPI 可以部署到各种云平台,如 Heroku、AWS 等。
# Heroku
git push heroku main
heroku open
第5章:总结
在本教程中,您学习了如何从零开始使用 FastAPI 框架构建高效的 API。通过学习 FastAPI 的基础、高级特性和最佳实践,您将能够快速掌握这个强大的 Web 框架,并将其应用于您的项目中。
希望这个教程对您有所帮助!祝您在 FastAPI 之旅中一切顺利!
