FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,它具有异步支持,并且基于标准 Python 类型提示。FastAPI 的设计哲学是“快速开发,快速部署”,它使用 Python 3.6+ 的异步功能,使得创建高性能的 Web 应用变得简单而高效。
以下是一个详细的教程,将帮助你学会 FastAPI 并创建一个简单的 Web 应用实例。
快速开始
安装 FastAPI 和 Uvicorn
首先,你需要安装 FastAPI 和 Uvicorn。Uvicorn 是一个 ASGI 服务器,用于运行 FastAPI 应用。
pip install fastapi uvicorn
创建项目结构
创建一个新目录,并设置项目的基本结构:
mkdir my_fastapi_app
cd my_fastapi_app
touch main.py
编写第一个 FastAPI 应用
打开 main.py 文件,并编写以下代码:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello World"}
这段代码创建了一个简单的 FastAPI 应用,其中包含一个根路由 /,当访问该路由时,会返回一个 JSON 对象 { "message": "Hello World" }。
运行应用
在命令行中,运行以下命令来启动应用:
uvicorn main:app --reload
--reload 参数使得在修改代码后无需重新启动服务器。
访问应用
打开浏览器或使用curl命令访问 http://127.0.0.1:8000/,你应该会看到以下输出:
{
"message": "Hello World"
}
创建更复杂的路由
FastAPI 允许你创建更复杂的路由,例如:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
if item_id == 404:
raise HTTPException(status_code=404, detail="Item not found")
return {"item_id": item_id}
在这个例子中,我们创建了一个新的路由 /items/{item_id},它接受一个名为 item_id 的路径参数。如果 item_id 等于 404,我们将引发一个 HTTPException。
使用 Pydantic 模式
FastAPI 使用 Pydantic 来定义输入和输出模型。以下是一个使用 Pydantic 的例子:
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class Item(BaseModel):
id: int
name: str
@app.post("/items/")
async def create_item(item: Item):
return item
在这个例子中,我们定义了一个 Item 模型,它有两个属性:id 和 name。然后,我们创建了一个 POST 路由 /items/,它接受一个 Item 对象作为请求体。
使用依赖注入
FastAPI 支持依赖注入,这使得管理应用状态变得更加容易。以下是一个使用依赖注入的例子:
from fastapi import FastAPI, Depends, HTTPException
from typing import List
app = FastAPI()
fake_db = {"1": {"name": "Item1"}, "2": {"name": "Item2"}}
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10, user_id: str = Depends(get_current_user)):
if user_id not in fake_db:
raise HTTPException(status_code=404, detail="User not found")
return fake_db[user_id]
def get_current_user(token: str = Depends(get_token)):
# 在这里验证 token
return token
def get_token():
# 在这里生成或验证 token
return "user123"
在这个例子中,我们使用 Depends 装饰器来注入依赖项。get_current_user 和 get_token 函数用于验证用户身份。
总结
通过这个教程,你学习了如何使用 FastAPI 创建一个简单的 Web 应用。FastAPI 提供了丰富的功能,可以帮助你快速构建高性能的 API。随着你的深入学习和实践,你将能够利用 FastAPI 的强大功能来创建更复杂的 Web 应用。
