Fastapi async api

From findscripter/everything-skills · View interactive version

Fastapi async api is an AI agent skill from the GitHub repository findscripter/everything-skills. 当用 FastAPI 构建高并发异步 API/微服务、需要 async SQLAlchemy 2.0 + Pydantic V2 + JWT 鉴权、连接池与缓存等生产实践时使用;做异步端点、数据模型、依赖注入、测试与可观测性的设计与落地产物;不适用于同步 WSGI 框架(Flask/Django 同步视图)、纯前端或非 Python 服务。触发词:FastAPI、异步 API、Pydantic、SQLAlchemy async

How to use this skill

Skill file

何时使用

适用:

不该用:

边界:本技能给出工程范式与可运行骨架,不替代针对你环境的压测、安全审计与代码评审。缺少关键输入(数据库类型、鉴权要求、部署目标)时先澄清再动手。

步骤

  1. 厘清需求:识别可异步化的 IO 点(DB、外部 HTTP、消息队列),确定鉴权与并发目标。
  2. 先定契约:用 Pydantic V2 模型设计 request/response schema,再写端点。
  3. 实现端点:async def + 依赖注入(DB session、当前用户),统一异常处理。
  4. 接数据层:async SQLAlchemy 2.0 引擎 + 连接池,避免在 async 路径调用同步阻塞库。
  5. 加鉴权与防护:OAuth2 + JWT,CORS、限流、输入校验。
  6. 写异步测试:pytest + pytest-asyncio + httpx.AsyncClient / TestClient 覆盖边界。
  7. 优化:缓存(Redis)、eager loading 防 N+1、分页(推荐游标分页)、响应压缩。
  8. 可观测与部署:结构化日志、健康检查、Uvicorn/Gunicorn 生产配置、Docker 多阶段构建。

指令

示例

最小异步骨架(FastAPI + async SQLAlchemy 2.0 + Pydantic V2 + lifespan):

from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import FastAPI, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import (
    create_async_engine, async_sessionmaker, AsyncSession,
)
from sqlalchemy import select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

engine = create_async_engine(
    "postgresql+asyncpg://user:pwd@localhost/app",
    pool_size=20, max_overflow=10, pool_pre_ping=True,
)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)

class Base(DeclarativeBase): ...

class Item(Base):
    __tablename__ = "items"
    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str]

class ItemOut(BaseModel):
    id: int
    name: str
    model_config = {"from_attributes": True}  # Pydantic V2

@asynccontextmanager
async def lifespan(app: FastAPI):
    yield
    await engine.dispose()

app = FastAPI(lifespan=lifespan)

async def get_db():
    async with SessionLocal() as session:
        yield session

@app.get("/items/{item_id}", response_model=ItemOut)
async def read_item(item_id: int, db: Annotated[AsyncSession, Depends(get_db)]):
    item = await db.get(Item, item_id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

异步测试(httpx + pytest-asyncio):

import pytest
from httpx import AsyncClient, ASGITransport
from app.main import app

@pytest.mark.asyncio
async def test_read_item():
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as ac:
        resp = await ac.get("/items/1")
    assert resp.status_code in (200, 404)

生产启动(多 worker):

gunicorn app.main:app -k uvicorn.workers.UvicornWorker -w 4 --bind 0.0.0.0:8000
# 开发热重载
uvicorn app.main:app --reload

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.