FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,与 Python 3.6+ 类型提示一起使用。它基于标准 Python 类型提示,旨在提供一种简单而一致的方法来构建 API,并且与 Python 中的异步功能完全集成。
简介
FastAPI 的主要特点包括:
- 异步支持:FastAPI 使用异步 Python,这意味着它可以处理成千上万的并发连接。
- 自动文档:FastAPI 生成交互式 API 文档,可以直接在浏览器中查看。
- 类型安全:使用 Python 3.6+ 的类型提示进行数据验证和自动文档。
- 易于扩展:FastAPI 可以很容易地与各种中间件和工具集成。
环境准备
在开始之前,确保你已经安装了 Python 3.6 或更高版本。接下来,我们可以使用 pip 来安装 FastAPI 和 uvicorn(一个 ASGI 服务器,用于运行 FastAPI 应用)。
pip install fastapi uvicorn
创建第一个 FastAPI 应用
创建一个名为 main.py 的文件,并添加以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
这段代码定义了一个简单的 FastAPI 应用,其中包含一个根路径的 GET 路由。
运行应用
要运行你的 FastAPI 应用,打开终端并导航到包含 main.py 的目录。然后运行以下命令:
uvicorn main:app --reload
这将启动一个本地服务器,默认情况下是 http://127.0.0.1:8000。你可以打开浏览器并访问这个地址,应该会看到一个显示 “Hello World” 的页面。
路由和视图函数
FastAPI 中的路由是通过 @app.get()、@app.post()、@app.put()、@app.delete() 等装饰器来定义的。以下是一个包含多个路由的示例:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
id: int
name: str
description: str = None
price: float
tax: float = None
@app.get("/")
async def root():
return {"message": "Hello World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
@app.post("/items/")
async def create_item(item: Item):
return item
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
return {"item_id": item_id}
数据验证
FastAPI 使用 Pydantic 进行数据验证。在上面的 Item 类中,我们定义了一个包含各种字段的模型。FastAPI 将自动验证传入的 JSON 数据是否符合该模型。
中间件
FastAPI 允许你添加中间件来处理请求和响应。以下是一个简单的中间件示例,它会在每个请求上添加一个响应头:
@app.middleware("http")
async def add_header(request, call_next):
response = await call_next(request)
response.headers["X-Custom-Header"] = "application/json"
return response
生成自动文档
当你启动 FastAPI 应用时,它会在默认的 http://127.0.0.1:8000/docs 和 http://127.0.0.1:8000/redoc 地址上提供交互式 API 文档。
总结
FastAPI 是一个功能强大的工具,可以让你轻松构建高效的 Web 应用。通过异步支持、自动文档、类型安全和易于扩展的特点,FastAPI 成为了现代 Python Web 开发者的首选框架。
在这个教程系列中,我们将更深入地探讨 FastAPI 的各个方面,包括如何处理复杂的数据模型、集成数据库、创建自定义验证器等。让我们一起踏上这个激动人心的旅程吧!
