快速入门
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 支持。它具有以下特点:
- 基于标准 Python 类型提示
- 自动请求验证
- 自动文档和交互式 API 测试
- 高性能
下面,我们将从零开始,一步一步地学习如何使用 FastAPI。
安装 FastAPI
首先,你需要安装 FastAPI。打开终端或命令提示符,运行以下命令:
pip install fastapi uvicorn
创建第一个 FastAPI 应用
创建一个新的 Python 文件,例如 app.py,并添加以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
现在,你已经创建了一个基本的 FastAPI 应用。接下来,我们将使用 Uvicorn 运行它。
使用 Uvicorn 运行 FastAPI 应用
Uvicorn 是一个 ASGI 服务器,用于运行 FastAPI 应用。打开终端或命令提示符,运行以下命令:
uvicorn app:app --reload
这将在默认的 8000 端口上启动应用,并且 --reload 参数使得应用在代码更改时自动重新加载。
路由和操作
FastAPI 使用 Python 路由功能。下面是一个示例,展示了如何创建一个路由和操作:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 404:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
在这个例子中,我们创建了一个名为 /items/{item_id} 的路由,它接受一个名为 item_id 的参数。如果 item_id 等于 404,我们将抛出一个 HTTP 404 异常。
响应模型
FastAPI 使用 Pydantic 模型来定义响应。下面是一个示例:
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
@app.get("/items/{item_id}")
async def read_item(item_id: int):
item = Item(id=item_id, name="Hello World")
return item
在这个例子中,我们创建了一个名为 Item 的 Pydantic 模型,它定义了响应的结构。然后,我们在路由操作中返回了一个 Item 实例。
请求模型
FastAPI 还支持请求模型,用于验证和解析请求参数。下面是一个示例:
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(...)):
results = {"items": [{"id": 1, "name": "hello"}, {"id": 2, "name": "world"}]}
if q:
results["items"] = [item for item in results["items"] if q.lower() in item["name"].lower()]
return results
在这个例子中,我们创建了一个名为 /items/ 的路由,它接受一个可选的查询参数 q。我们使用 Pydantic 的 Query 函数来验证和解析这个参数。
异常处理
FastAPI 支持自定义异常处理。下面是一个示例:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 404:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
在这个例子中,如果 item_id 等于 404,我们抛出一个 HTTP 404 异常。
安全性
FastAPI 支持多种安全性方案,例如 JWT、OAuth2、密码等。下面是一个使用 JWT 的示例:
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from datetime import datetime, timedelta
SECRET_KEY = "your_secret_key"
ALGORITHM = "HS256"
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def create_access_token(data: dict, expires_delta: timedelta = timedelta(minutes=30)):
to_encode = data.copy()
expire = datetime.utcnow() + expires_delta
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(username=form_data.username, password=form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(
data={"sub": user}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/items/")
async def read_items(token: str = Depends(oauth2_scheme)):
return {"message": "Hello World"}
在这个例子中,我们使用 JWT 来保护 /items/ 路由。
总结
本教程介绍了如何从零开始快速掌握 FastAPI 框架。通过学习本教程,你应该已经了解了 FastAPI 的基本概念和用法。希望这个教程能够帮助你开始使用 FastAPI 构建你的下一个 Web 应用。
