简介
FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,由 Python 3.6+ 支持。它基于标准 Python 类型提示,具有自动文档生成、依赖注入和异步支持等特性。本指南将带您深入了解 FastAPI,并展示如何快速上手 RESTful API 开发。
FastAPI 简介
FastAPI 是由 Sébastien Eustace 开发的一个开源项目,它旨在提供一种简单、高效的方式来创建 Web API。以下是 FastAPI 的一些关键特性:
- 异步支持:FastAPI 使用 Starlette 和 Pydantic 库,这些库都支持异步操作,因此可以创建高性能的异步 API。
- 自动文档:FastAPI 会自动生成交互式 API 文档,无需额外配置。
- 类型提示:FastAPI 充分利用 Python 的类型提示功能,使代码更加清晰、易于维护。
- 依赖注入:FastAPI 提供了一个内置的依赖注入系统,可以方便地注入服务、数据库连接等。
快速开始
安装 FastAPI
首先,您需要安装 FastAPI 和 Uvicorn(一个 ASGI 服务器),可以使用 pip 来安装:
pip install fastapi uvicorn
创建一个简单的 FastAPI 应用
创建一个名为 main.py
的 Python 文件,并添加以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
运行 FastAPI 应用
使用以下命令运行您的应用:
uvicorn main:app --reload
此时,您可以在浏览器中访问 http://127.0.0.1:8000/
,将看到如下响应:
{
"message": "Hello World"
}
创建 RESTful API
路径参数
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., title="The id of the item to get")):
return {"item_id": item_id}
查询参数
from fastapi import FastAPI, Query
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(..., title="Query parameter")):
if q:
return {"q": q}
return {"items": [{"id": 1, "name": "Item1"}, {"id": 2, "name": "Item2"}]}
响应模型
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
@app.post("/items/")
async def create_item(item: Item):
return item
异步视图函数
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
item = await get_item_by_id(item_id)
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return item
async def get_item_by_id(item_id: int):
# 模拟数据库查询
return {"id": item_id, "name": "Item " + str(item_id)}
总结
通过本指南,您已经了解了 FastAPI 的基本概念和如何创建一个简单的 RESTful API。FastAPI 提供了许多高级特性,可以帮助您快速构建高性能、易于维护的 Web API。希望您能将 FastAPI 应用于您的项目中,并享受其带来的便利。