FastAPI 是一个现代、快速(使用 Starlette 和 Pydantic 构建)、基于类型的 Python web 框架。它提供了自动文档生成、输入验证、依赖注入等功能,使得构建 API 变得非常简单。以下是 FastAPI 的简单教程:

安装 FastAPI

使用 pip 安装 FastAPI 和 uvicorn(一个 ASGI 服务器):
pip install fastapi uvicorn

创建一个 FastAPI 应用

创建一个 Python 文件(比如 main.py)并添加以下内容:
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

运行应用

使用以下命令启动 FastAPI 应用:
uvicorn main:app --reload

现在,你可以通过访问 http://127.0.0.1:8000/docs 来查看自动生成的 API 文档,并通过 http://127.0.0.1:8000 来访问 API。

使用查询参数

FastAPI 自动解析查询参数,并通过类型注解来验证输入。在上述代码中,item_id 是路径参数,而 q 是查询参数。

使用 Pydantic 模型

FastAPI 使用 Pydantic 模型来自动验证请求体和响应体。在上述代码中,你可以看到 Item 模型的使用:
from typing import Optional
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

然后,在路由中使用这个模型:
@app.post("/items/")
def create_item(item: Item):
    return item

使用依赖项

FastAPI 允许你使用依赖项(Dependency)来组织和注入代码。例如,你可以创建一个验证 API key 的依赖项:
from fastapi import Depends, HTTPException, status

async def verify_api_key(api_key: str = Depends(get_api_key)):
    if api_key != "fake-super-secret-key":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API Key",
        )
    return api_key

@app.get("/protected")
async def protected_route(api_key: str = Depends(verify_api_key)):
    return {"message": "This is a protected route"}

在这个例子中,verify_api_key 是一个依赖项,它使用 get_api_key 函数获取 API key,并验证其有效性。然后,这个依赖项可以在需要进行 API key 验证的路由中使用。

这只是 FastAPI 的入门教程,FastAPI 提供了更多高级功能,例如 WebSocket 支持、OAuth2 认证、数据库集成等。深入了解 FastAPI 可以在构建 API 时提供更多的灵活性和性能。更多信息请参阅 [FastAPI 官方文档](https://fastapi.tiangolo.com/)。


转载请注明出处:http://www.zyzy.cn/article/detail/13926/FastAPI