使用FastAPI构建API接口
使用 FastAPI 构建高性能 API 接口
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API。它基于 Python 3.7+ 的类型提示,并使用了 Starlette 和 Pydantic,分别用于处理异步请求和数据验证。FastAPI 的速度堪比 NodeJS 和 Go,同时提供了自动交互式文档、数据验证和依赖注入等强大功能,极大地提升了 API 开发效率。本文将详细介绍如何使用 FastAPI 构建 API 接口,涵盖从基础到高级的各个方面。
一、安装和准备
首先,确保你的 Python 版本是 3.7 或更高。然后,使用 pip 安装 FastAPI 和 Uvicorn(一个 ASGI 服务器):
bash
pip install fastapi uvicorn[standard]
二、创建第一个 API
创建一个名为 main.py
的文件,并添加以下代码:
```python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello, FastAPI!"}
```
运行应用:
bash
uvicorn main:app --reload
--reload
参数允许在代码更改时自动重新加载应用程序。
现在,访问 http://127.0.0.1:8000/
,你将看到 {"message": "Hello, FastAPI!"}
的 JSON 响应。
三、路径参数和查询参数
FastAPI 支持使用类型提示声明路径参数和查询参数:
```python
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., title="The ID of the item to get"), q: str | None = Query(default=None, max_length=50)):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
```
item_id: int = Path(...)
定义了一个名为item_id
的路径参数,类型为整数,...
表示该参数是必需的。q: str | None = Query(default=None, max_length=50)
定义了一个名为q
的查询参数,类型为字符串或 None,默认值为 None,最大长度为 50。
四、请求体
使用 Pydantic 模型定义请求体:
```python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.post("/items/")
async def create_item(item: Item):
return item
```
现在,你可以发送 POST 请求到 /items/
,并在请求体中包含 JSON 数据,FastAPI 会自动将其转换为 Item
对象。
五、数据验证
Pydantic 提供了强大的数据验证功能:
```python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, conint
app = FastAPI()
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
quantity: conint(gt=0) # 数量必须大于 0
@app.post("/items/")
async def create_item(item: Item):
if item.quantity > 100:
raise HTTPException(status_code=400, detail="Quantity cannot exceed 100")
return item
```
六、依赖注入
依赖注入可以帮助你编写更简洁、可重用的代码:
```python
from fastapi import FastAPI, Depends
app = FastAPI()
async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
```
七、异步处理
FastAPI 支持异步处理,可以提高性能:
```python
from fastapi import FastAPI
app = FastAPI()
async def slow_process():
# 模拟耗时操作
await asyncio.sleep(1)
return {"message": "Slow process completed"}
@app.get("/slow/")
async def slow_endpoint():
result = await slow_process()
return result
```
八、中间件
中间件可以在请求处理前后执行一些操作,例如记录日志、身份验证等:
```python
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
```
九、错误处理
可以使用 @app.exception_handler
装饰器定义自定义错误处理程序:
```python
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail},
)
```
十、自动交互式文档
FastAPI 自动生成交互式 API 文档,可以使用 Swagger UI 或 ReDoc 浏览:
- Swagger UI:
http://127.0.0.1:8000/docs
- ReDoc:
http://127.0.0.1:8000/redoc
十一、部署
可以使用 Uvicorn 或其他 ASGI 服务器部署 FastAPI 应用。例如,使用 Uvicorn 部署到生产环境:
bash
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
总结:
FastAPI 提供了丰富的功能和强大的性能,使得构建 API 变得更加简单和高效。本文涵盖了 FastAPI 的核心概念和常用功能,希望能帮助你快速入门并构建高性能的 API 接口。 深入学习 FastAPI 的更多高级特性,例如 WebSockets、后台任务、数据库集成等,可以参考官方文档,进一步提升你的 API 开发技能。 通过实践和探索,你将能够充分利用 FastAPI 的优势,构建出更加健壮和高效的 Web 应用。