目录

  1. FastAPI 简介
  2. 安装 FastAPI
  3. 创建第一个 FastAPI 应用
  4. 路由和请求方法
  5. 请求和响应模型
  6. 依赖注入
  7. 后台任务
  8. FastAPI 与数据库集成
  9. FastAPI 与 JWT 认证
  10. 部署 FastAPI 应用
  11. 参考资料

1. FastAPI 简介

FastAPI 是一个现代、快速(高性能)、Web 框架,用于构建 API,它基于 Python 3.7+ 和 Starlette 框架构建。它能够利用 Python 类型提示提供更高效的开发体验。FastAPI 是基于 ASGI(异步服务网关接口)标准,因此它支持异步编程,可以处理更多的请求。

FastAPI 的特点包括:

  • 高性能:基于 Starlette 和 Pydantic,性能接近 Node.js 和 Go。
  • 自动文档生成:使用 OpenAPI 和 JSON Schema 自动生成交互式 API 文档。
  • 简洁易用:通过 Python 类型提示和自动验证让开发者快速上手。

2. 安装 FastAPI

要安装 FastAPI,你需要使用 pip 来安装它及其依赖项:

# 安装 FastAPI 和 Uvicorn(作为 ASGI 服务器)
pip install fastapi uvicorn

uvicorn 是一个 ASGI 服务器,FastAPI 使用它来运行应用程序。


3. 创建第一个 FastAPI 应用

在 FastAPI 中,创建一个基本的应用非常简单。以下是创建一个简单应用的示例:

# app.py
from fastapi import FastAPI

app = FastAPI()

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

  • FastAPI():创建 FastAPI 应用实例。
  • @app.get("/"):定义一个 GET 请求的路由,处理根路径 /
  • read_root():视图函数,返回一个 JSON 响应。

然后,你可以通过 uvicorn 运行应用:

uvicorn app:app --reload

  • --reload:使开发过程中的代码更改自动重新加载。

访问 http://127.0.0.1:8000,你将看到返回的 JSON:

{"message": "Hello, World!"}


4. 路由和请求方法

FastAPI 支持多种 HTTP 请求方法,例如 GETPOSTPUTDELETE 等。以下是一些常用的示例:

GET 请求

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

  • 通过路径参数 item_id 和查询参数 q 获取值。

POST 请求

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
def create_item(item: Item):
    return {"name": item.name, "price": item.price}

  • 使用 pydantic 创建请求体模型,接收并处理 POST 请求中的 JSON 数据。

5. 请求和响应模型

在 FastAPI 中,可以使用 Pydantic 模型来定义请求体和响应体的数据结构。Pydantic 模型会自动进行数据验证,确保请求的数据符合定义的格式。

请求模型

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

响应模型

from typing import List

class ItemResponse(BaseModel):
    name: str
    price: float

@app.get("/items/", response_model=List[ItemResponse])
def get_items():
    return [{"name": "Item1", "price": 10.5}, {"name": "Item2", "price": 20.0}]

  • response_model:指定返回的数据类型,FastAPI 会自动将返回的数据转换为响应模型。

6. 依赖注入

FastAPI 支持依赖注入,可以轻松地在不同的视图函数之间共享逻辑。依赖项可以是数据库连接、认证逻辑、配置等。

from fastapi import Depends

def get_db():
    db = "Database connection"
    try:
        yield db
    finally:
        print("Closing database connection")

@app.get("/items/")
def read_items(db: str = Depends(get_db)):
    return {"db_connection": db}

  • Depends:用于声明依赖项,FastAPI 会自动解析并注入。

7. 后台任务

FastAPI 支持后台任务,允许你在响应返回后执行一些任务。例如,发送电子邮件或记录日志等操作:

from fastapi import BackgroundTasks

def write_log(message: str):
    with open("log.txt", "a") as log:
        log.write(message)

@app.get("/items/")
async def get_items(background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, "Item fetched")
    return {"message": "Items fetched"}

  • background_tasks.add_task:在响应返回之前,执行后台任务。

8. FastAPI 与数据库集成

FastAPI 支持与多种数据库集成,如 SQLAlchemy、Tortoise ORM 等。下面是使用 SQLAlchemy 与 FastAPI 集成的基本示例:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

Base = declarative_base()
engine = create_engine("sqlite:///./test.db")
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    price = Column(Integer)

Base.metadata.create_all(bind=engine)

# 使用 SQLAlchemy 进行数据库查询

你可以使用数据库会话(SessionLocal)与数据库进行交互。


9. FastAPI 与 JWT 认证

FastAPI 提供了对 JWT(JSON Web Token)认证的支持。你可以使用 FastAPI 的 Depends 和一些自定义逻辑来实现认证。

JWT 认证示例

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, "SECRET_KEY", algorithms=["HS256"])
        return payload
    except JWTError:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")

@app.get("/users/me")
def read_users_me(current_user: dict = Depends(get_current_user)):
    return current_user

  • 使用 OAuth2PasswordBearer 处理登录请求。
  • 通过 JWT 令牌验证用户身份。

10. 部署 FastAPI 应用

FastAPI 可以通过 uvicorn 运行,也可以与 Nginx、Docker 等集成部署。以下是基本的部署步骤:

使用 Uvicorn 运行 FastAPI

uvicorn app:app --host 0.0.0.0 --port 8000 --reload

与 Nginx 配合使用

配置 Nginx 来作为反向代理,将请求转发给 Uvicorn。


11. 参考资料

出站链接

站内链接