Token导航 LogoToken导航TokenDH.com
开发external-serviceclawhub未标认证来源可访问clear审计通过

fastapi-patternsFastAPI 模式

Agent Skill

用于辅助 Python 项目开发、测试、依赖管理和常见框架工作流。它适合让 Agent 阅读 Python 代码、定位测试问题、整理运行命令、生成脚本或分析数据处理逻辑。使用时需要确认项目虚拟环境、依赖版本和测试入口;涉及执行脚本、读写文件、访问数据库或调用外部 API 时,应先明确运行目录和输入输出范围,避免误改生产数据。

总安装

18,228

周安装

775

GitHub Stars

公开资料未说明

下载量

6,386
OpenClaw

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

MIT-0

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:fastapi-patterns(FastAPI 模式)
来源仓库:https://github.com/msruruguay/fastapi-patterns
安装命令:
openclaw skills install fastapi-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 OpenClaw 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

ClawHubOpenClaw
openclaw skills install fastapi-patterns

简介

使用 Pydantic v2、异步端点、OAuth2/JWT、依赖项注入、测试和 Kubernetes 部署的生产 FastAPI 模式

SKILL.md

name
fastapi-patterns
description
Production FastAPI patterns with Pydantic v2, async endpoints, OAuth2/JWT, dependency injection, testing, and Kubernetes deployment
version
1.0.0
tags

FastAPI Production Patterns

Description

Modern FastAPI development patterns for 2026, covering the full spectrum from Pydantic v2 migration to production deployment. Validated against 15+ production sources with 0.95 confidence. This skill keeps you on the current side of breaking changes and equips you with battle-tested patterns for async, security, testing, and performance.

Usage

Install this skill to get production-ready FastAPI patterns including:

  • Pydantic v2 migration guide (breaking changes, 4-17x performance gains)
  • Async vs sync endpoint decision rules
  • OAuth2 + JWT authentication patterns
  • Dependency override testing strategies
  • Docker + Kubernetes deployment with health probes

When working on FastAPI projects, this skill provides context for:

  • Migrating from Pydantic v1 to v2 without breaking existing code
  • Setting up proper lifespan events instead of deprecated @app.on_event()
  • Structuring tests with TestClient (sync) and AsyncClient (async)
  • Configuring Gunicorn + Uvicorn workers for production

Key Patterns

Pydantic v2 Migration

# BEFORE (Pydantic v1 — deprecated)
from pydantic import BaseModel, validator

class User(BaseModel):
    name: str

    @validator('name')
    def name_must_not_be_empty(cls, v):
        if not v:
            raise ValueError('name cannot be empty')
        return v

# AFTER (Pydantic v2 — current)
from pydantic import BaseModel, field_validator

class User(BaseModel):
    name: str

    @field_validator('name')
    @classmethod
    def name_must_not_be_empty(cls, v):
        if not v:
            raise ValueError('name cannot be empty')
        return v

Method renames (v1 to v2): parse_obj() -> model_validate(), dict() -> model_dump(), json() -> model_dump_json(), orm_mode = True -> model_config = ConfigDict(from_attributes=True), conint(ge=0) -> Annotated[int, Field(ge=0)]

Lifespan Events (Modern Pattern)

from contextlib import asynccontextmanager
from fastapi import FastAPI

ml_models = {}

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Startup: load resources
    ml_models["answer"] = load_ml_model()
    yield
    # Shutdown: release resources
    ml_models.clear()

app = FastAPI(lifespan=lifespan)

Do NOT use deprecated @app.on_event(). Use lifespan for: DB connection pools, ML models, resource cleanup.

Async Decision Rule

# Use async def for: asyncpg, motor, httpx (non-blocking I/O)
@app.get('/users/')
async def get_users():
    users = await async_db.fetch('SELECT * FROM users')
    return users

# Use def for: psycopg2, pymongo, requests (blocking libs)
# FastAPI automatically runs def endpoints in a threadpool
@app.get('/users/sync')
def get_users_sync():
    return sync_db.query('SELECT * FROM users')

Rule of thumb: If unsure, use def. FastAPI handles the threadpool for you.

OAuth2 + JWT Authentication

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

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"

async def get_current_user(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if not username:
            raise HTTPException(status_code=401)
        return username
    except:
        raise HTTPException(status_code=401)

CORS (Never Use wildcard in Production)

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com"],  # NOT ["*"]
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Async Testing with httpx

import pytest
from httpx import ASGITransport, AsyncClient

@pytest.mark.anyio
async def test_async_endpoint():
    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://test"
    ) as ac:
        response = await ac.get("/")
    assert response.status_code == 200

Dependency Overrides for Mocking

async def override_get_db():
    db = Database("sqlite:///:memory:")
    yield db
    await db.disconnect()

def test_with_mock_db():
    app.dependency_overrides[get_db] = override_get_db
    client = TestClient(app)
    response = client.get("/users/")
    assert response.status_code == 200
    app.dependency_overrides = {}  # Always clean up

Production Dockerfile

FROM python:3.11-slim
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
COPY ./app /code/app
CMD ["gunicorn", "app.main:app", "--workers", "4",
     "--worker-class", "uvicorn.workers.UvicornWorker", "--bind", "0.0.0.0:80"]

Workers: 1 per CPU core on a single server. For Kubernetes: 1 worker per container, scale at cluster level.

Health Check Endpoints

@app.get("/health")
async def health_check():
    """Liveness: is the process running?"""
    return {"status": "healthy"}

@app.get("/ready")
async def readiness_check():
    """Readiness: can it handle traffic?"""
    try:
        await database.execute("SELECT 1")
        return {"status": "ready", "database": "ok"}
    except Exception as e:
        raise HTTPException(status_code=503, detail=str(e))

Performance Quick Wins

# Connection pooling: 2-3x throughput improvement
database = Database("postgresql://user:pass@localhost/db", min_size=5, max_size=20)

# Response caching: 90%+ database load reduction
@cache(expire=60)
async def get_user(user_id: int):
    return await db.fetch_one(...)

# Async middleware: 10-30% latency reduction
@app.middleware("http")
async def async_middleware(request, call_next):
    return await call_next(request)  # NOT blocking def

Common Pitfall: Blocking Inside Async

# WRONG: blocks the event loop
@app.get("/data")
async def get_data():
    response = requests.get("https://api.com")  # Blocks!

# CORRECT: use async library
import httpx
@app.get("/data")
async def get_data():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://api.com")

Tools & References


*Published by MidOS — MCP Community Library*

适合场景

01

OpenClaw 用户查找和安装 Skill 时

02

用户想查找某类 Agent Skill 时

03

需要根据任务场景推荐可安装能力包时

04

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

OpenClaw

84.98%
按下载量换算5,427

安全审计

VirusTotal

通过

ClawScan

通过

Static analysis

未展示

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills