FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 的类型提示驱动。它旨在快速开发,具有高性能,并且易于扩展。本文将为你提供一份新手必看的 FastAPI 教程和官方文档指南,帮助你快速上手并开始构建你的第一个 FastAPI 应用。
快速开始
安装 FastAPI
首先,你需要安装 FastAPI 和 Uvicorn(一个 ASGI 服务器)。你可以使用 pip 来安装它们:
pip install fastapi uvicorn
创建一个基本的 FastAPI 应用
创建一个新的 Python 文件,例如 main.py,并添加以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
现在,你可以使用 Uvicorn 运行你的应用:
uvicorn main:app --reload
打开浏览器,访问 http://127.0.0.1:8000/,你应该会看到以下响应:
{
"message": "Hello World"
}
FastAPI 路由和视图
FastAPI 使用路由和视图来定义 API。路由是 URL,视图是处理请求的函数。
路由参数
你可以使用路径参数来创建动态路由:
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
现在,访问 http://127.0.0.1:8000/items/5 将返回:
{
"item_id": 5
}
嵌套路由
你也可以创建嵌套路由:
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(user_id: int, item_id: int):
return {"user_id": user_id, "item_id": item_id}
访问 http://127.0.0.1:8000/users/1/items/2 将返回:
{
"user_id": 1,
"item_id": 2
}
FastAPI 数据验证
FastAPI 使用 Pydantic 来验证和序列化输入数据。
定义 Pydantic 模型
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
使用 Pydantic 模型验证请求
@app.post("/items/")
async def create_item(item: Item):
return item
现在,你可以发送一个 POST 请求到 http://127.0.0.1:8000/items/ 并包含 JSON 数据:
{
"id": 1,
"name": "Test Item"
}
这将返回创建的项:
{
"id": 1,
"name": "Test Item"
}
FastAPI 中间件
中间件是处理 HTTP 请求的钩子,可以用于日志记录、认证等。
from fastapi import FastAPI, Request
app = FastAPI()
@app.middleware("http")
async def log_requests(request: Request, call_next):
print(f"Received {request.method} request for {request.url}")
response = await call_next(request)
print(f"Response {response.status_code}")
return response
现在,每次请求都会打印出请求方法和 URL,以及响应状态码。
官方文档指南
FastAPI 的官方文档非常全面,包含了从基础到高级的所有内容。以下是一些值得关注的官方文档部分:
总结
通过本文,你了解了 FastAPI 的基础知识,包括如何创建一个基本的 FastAPI 应用、定义路由和视图、数据验证以及中间件。要成为一名 FastAPI 高手,你需要深入学习和实践。官方文档是学习 FastAPI 的最佳资源,它包含了丰富的教程和参考文档。祝你学习愉快!
