FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,与 Python 3.6+ 类型提示一起使用。它旨在快速开发,具有高性能、易于学习和使用。本指南将带您从零开始,逐步掌握 FastAPI 框架,并构建一个高效的 RESTful API。
快速入门
安装 FastAPI
首先,确保您已安装 Python 3.6 或更高版本。然后,使用以下命令安装 FastAPI:
pip install fastapi uvicorn
创建一个基本的 FastAPI 应用
创建一个名为 main.py 的文件,并添加以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
运行您的 FastAPI 应用
使用以下命令启动您的 FastAPI 应用:
uvicorn main:app --reload
访问 http://127.0.0.1:8000,您将看到以下响应:
{
"message": "Hello World"
}
快速学习 FastAPI
路由和视图函数
FastAPI 使用 Python 函数作为路由和视图函数。您可以使用 @app.get()、@app.post() 等装饰器定义不同的 HTTP 方法。
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
数据验证和解析
FastAPI 自动验证和解析传入的请求数据。您可以使用 Pydantic 模式定义请求和响应模型。
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
异步支持
FastAPI 是异步的,这意味着您可以编写高效的 I/O 密集型代码。您可以使用 async def 定义异步视图函数。
@app.post("/items/")
async def create_item(item: Item):
return item
高效构建 RESTful API
定义 API 资源
RESTful API 中的资源通常由 URL 表示。您可以使用路径参数和查询参数来表示资源之间的关系。
@app.get("/items/")
async def list_items():
return [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"id": item_id, "name": "Item 1"}
使用数据库
FastAPI 支持多种数据库,例如 SQLite、PostgreSQL 和 MongoDB。您可以使用 SQLModel 或 Pydantic ORM 来定义数据库模型。
from sqlmodel import SQLModel, create_engine, Session
SQLModel.metadata.create_all(bind=create_engine("sqlite:///database.db"))
class Item(SQLModel, table=True):
id: int
name: str
description: str = None
price: float
tax: float = None
@app.get("/items/")
async def list_items():
db = Session()
results = db.query(Item).all()
db.close()
return results
集成认证和授权
FastAPI 支持多种认证和授权机制,例如 OAuth2 密码、JWT 和 API 密钥。
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(fake_db, form_data.username, form_data.password)
if not user:
raise HTTPException(status_code=400, detail="Incorrect username or password")
return {"access_token": create_access_token(data={"sub": user.username}), "token_type": "bearer"}
总结
本指南为您提供了从零开始掌握 FastAPI 框架的实用技巧。通过学习如何创建路由、定义数据模型、使用数据库和集成认证机制,您将能够构建高效、可扩展的 RESTful API。祝您学习愉快!
