FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 支持。它具有异步支持,用于快速和高效地处理大量并发请求。
快速开始
安装 FastAPI: 使用 pip 安装 FastAPI:
pip install fastapi
创建一个基本的 FastAPI 应用:
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello World"}
运行应用: 在命令行中运行以下命令:
uvicorn main:app --reload
其中
main
是你的 Python 文件名,app
是 FastAPI 应用的实例。
路由和响应
FastAPI 使用 Python 函数来定义路由和响应。以下是一个简单的路由示例:
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
这个路由会匹配 /items/<item_id>
路径,并返回一个包含 item_id
的 JSON 响应。
数据验证
FastAPI 提供了强大的数据验证功能,可以使用 Pydantic 模型来定义数据结构:
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
description: str = None
price: float
tax: float = None
然后,你可以使用这个模型来验证和解析传入的数据:
@app.post("/items/")
async def create_item(item: Item):
return item
异步支持
FastAPI 是异步的,这意味着它可以同时处理多个请求。这是通过 Python 的 async/await
语法实现的。
@app.get("/items/{item_id}")
async def read_item(item_id: int):
# 模拟异步数据库操作
await asyncio.sleep(1)
return {"item_id": item_id}
扩展阅读
更多关于 FastAPI 的信息,请访问官方文档:FastAPI 文档
FastAPI Logo