Agent skill

Fastapi Patterns

by affaan-m in affaan-m/ECC

非同期API、依存性注入、Pydanticのリクエスト・レスポンスモデル、OpenAPIドキュメント、テスト、セキュリティ、本番対応のためのFastAPIパターン。

MITAuto-check passedBackend & APIs

Install Fastapi Patterns

skills CLI
$ npx skills add affaan-m/ECC --skill fastapi-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install affaan-m/ECC fastapi-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/affaan-m/ECC.git skills-src && mkdir -p .claude/skills && cp -r skills-src/docs/ja-JP/skills/fastapi-patterns .claude/skills/fastapi-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
fastapi-patterns
GitHub stars
275k
Token cost
~2k tokens
SKILL.md length
85 words
Files
1
Skills in repo
645
Repo updated
First seen
Licence
MIT

At a glance

非同期API、依存性注入、Pydanticのリクエスト・レスポンスモデル、OpenAPIドキュメント、テスト、セキュリティ、本番対応のためのFastAPIパターン。

  • Tasks that involve Backend development
  • SKILL.md covers 使用するタイミング, 仕組み, プロジェクトレイアウト and アプリケーションファクトリー, plus 10 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md
  • Tasks that involve OpenAPI specifications

What it does

Fastapi Patterns is an agent skill from affaan-m/ECC. 非同期API、依存性注入、Pydanticのリクエスト・レスポンスモデル、OpenAPIドキュメント、テスト、セキュリティ、本番対応のためのFastAPIパターン。

Its SKILL.md is about 2k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering Backend development and OpenAPI specifications. It works with FastAPI, OpenAPI and Pydantic. The repository describes itself as: The agent harness performance optimization system. Skills, instincts, memory, security, and research-first development for Claude Code, Codex, Opencode, Cursor and beyond. The licence is MIT.

When your agent uses it

  • Tasks that involve Backend development
  • Tasks that involve OpenAPI specifications

Example prompts

  • “/fastapi-patterns”

Requirements

  • Python 3

What it can do on your machine

Read from SKILL.md and the folder at commit ef648e0. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Fastapi Patterns loads about 2k tokens when it runs. Until then it costs about 25 tokens; SKILL.md has 85 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~25
When it runs · the whole SKILL.md, loaded when a task matches
~2k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from affaan-m/ECC at commit ef648e0, republished under its MIT licence (© affaan-m). 85 words, ~1,958 tokens.

Download SKILL.mdSave it as .claude/skills/fastapi-patterns/SKILL.md (or your agent's skills folder).
name
fastapi-patterns
description
非同期API、依存性注入、Pydanticのリクエスト・レスポンスモデル、OpenAPIドキュメント、テスト、セキュリティ、本番対応のためのFastAPIパターン。
origin
community

FastAPIパターン

本番指向のFastAPIサービスのためのパターン。

使用するタイミング

  • FastAPIアプリを構築またはレビューする場合。
  • ルーター、スキーマ、依存関係、データベースアクセスを分割する場合。
  • データベースや外部サービスを呼び出す非同期エンドポイントを記述する場合。
  • 認証、認可、OpenAPIドキュメント、テスト、またはデプロイ設定を追加する場合。
  • FastAPI PRをコピー可能な例とリスクについて確認する場合。

仕組み

FastAPIアプリを明示的な依存関係とサービスコードの上の薄いHTTPレイヤーとして扱います:

  • main.py はアプリ構築、ミドルウェア、例外ハンドラー、ルーター登録を担当する。
  • schemas/ はPydanticのリクエストとレスポンスモデルを担当する。
  • dependencies.py はデータベース、認証、ページネーション、リクエストスコープの依存関係を担当する。
  • services/ または crud/ はビジネスと永続化操作を担当する。
  • tests/ は本番リソースを開かずに依存関係をオーバーライドする。

小さなルーターと明示的なresponse_model宣言を優先します。レスポンススキーマには生のORMオブジェクト、シークレット、フレームワークのグローバル変数を含めないでください。

プロジェクトレイアウト

text
app/
|-- main.py
|-- config.py
|-- dependencies.py
|-- exceptions.py
|-- api/
|   `-- routes/
|       |-- users.py
|       `-- health.py
|-- core/
|   |-- security.py
|   `-- middleware.py
|-- db/
|   |-- session.py
|   `-- crud.py
|-- models/
|-- schemas/
`-- tests/

アプリケーションファクトリー

テストとワーカーが制御された設定でアプリをビルドできるように、ファクトリーを使用します。

python
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from app.api.routes import health, users
from app.config import settings
from app.db.session import close_db, init_db
from app.exceptions import register_exception_handlers


@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_db()
    yield
    await close_db()


def create_app() -> FastAPI:
    app = FastAPI(
        title=settings.api_title,
        version=settings.api_version,
        lifespan=lifespan,
    )

    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.cors_origins,
        allow_credentials=bool(settings.cors_origins),
        allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
        allow_headers=["Authorization", "Content-Type"],
    )

    register_exception_handlers(app)
    app.include_router(health.router, prefix="/health", tags=["health"])
    app.include_router(users.router, prefix="/api/v1/users", tags=["users"])
    return app


app = create_app()

allow_credentials=Trueと一緒にallow_origins=["*"]を使用しないでください; ブラウザはその組み合わせを拒否し、Starletteは認証情報付きリクエストに対してそれを禁止します。

Pydanticスキーマ

リクエスト、更新、レスポンスのモデルを分離します。

python
from datetime import datetime
from typing import Annotated
from uuid import UUID

from pydantic import BaseModel, ConfigDict, EmailStr, Field


class UserBase(BaseModel):
    email: EmailStr
    full_name: Annotated[str, Field(min_length=1, max_length=100)]


class UserCreate(UserBase):
    password: Annotated[str, Field(min_length=12, max_length=128)]


class UserUpdate(BaseModel):
    email: EmailStr | None = None
    full_name: Annotated[str | None, Field(min_length=1, max_length=100)] = None


class UserResponse(UserBase):
    model_config = ConfigDict(from_attributes=True)

    id: UUID
    created_at: datetime
    updated_at: datetime

レスポンスモデルにはパスワードハッシュ、アクセストークン、リフレッシュトークン、内部認可状態を含めてはなりません。

依存関係

リクエストスコープのリソースには依存性注入を使用します。

python
from collections.abc import AsyncIterator
from uuid import UUID

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.security import decode_token
from app.db.session import session_factory
from app.models.user import User


oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")


async def get_db() -> AsyncIterator[AsyncSession]:
    async with session_factory() as session:
        try:
            yield session
            await session.commit()
        except Exception:
            await session.rollback()
            raise


async def get_current_user(
    token: str = Depends(oauth2_scheme),
    db: AsyncSession = Depends(get_db),
) -> User:
    payload = decode_token(token)
    user_id = UUID(payload["sub"])
    user = await db.get(User, user_id)
    if user is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
    return user

ルートハンドラー内でインラインにセッション、クライアント、または認証情報を作成しないでください。

非同期エンドポイント

I/Oを実行する場合はルートハンドラーを非同期にし、その内部で非同期ライブラリを使用します。

python
from fastapi import APIRouter, Depends, Query
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_current_user, get_db
from app.models.user import User
from app.schemas.user import UserResponse


router = APIRouter()


@router.get("/", response_model=list[UserResponse])
async def list_users(
    limit: int = Query(default=50, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    result = await db.execute(
        select(User).order_by(User.created_at.desc()).limit(limit).offset(offset)
    )
    return result.scalars().all()

非同期ハンドラーからの外部HTTP呼び出しにはhttpx.AsyncClientを使用してください。非同期ルートでrequestsを呼び出さないでください。

エラー処理

ドメイン例外を一元化し、レスポンスの形状を安定させます。

python
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse


class ApiError(Exception):
    def __init__(self, status_code: int, code: str, message: str):
        self.status_code = status_code
        self.code = code
        self.message = message


def register_exception_handlers(app: FastAPI) -> None:
    @app.exception_handler(ApiError)
    async def api_error_handler(request: Request, exc: ApiError):
        return JSONResponse(
            status_code=exc.status_code,
            content={"error": {"code": exc.code, "message": exc.message}},
        )

OpenAPIカスタマイズ

カスタムOpenAPI呼び出し可能オブジェクトをapp.openapiに割り当ててください; 関数を一度だけ呼び出さないでください。

python
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi


def install_openapi(app: FastAPI) -> None:
    def custom_openapi():
        if app.openapi_schema:
            return app.openapi_schema
        app.openapi_schema = get_openapi(
            title="Service API",
            version="1.0.0",
            routes=app.routes,
        )
        return app.openapi_schema

    app.openapi = custom_openapi

テスト

ルートハンドラーが決して参照しない内部ヘルパーではなく、Dependsで使用される依存関係をオーバーライドします。

python
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession

from app.dependencies import get_db
from app.main import create_app


@pytest.fixture
async def client(test_session: AsyncSession):
    app = create_app()

    async def override_get_db():
        yield test_session

    app.dependency_overrides[get_db] = override_get_db
    async with AsyncClient(
        transport=ASGITransport(app=app),
        base_url="http://test",
    ) as test_client:
        yield test_client
    app.dependency_overrides.clear()

セキュリティチェックリスト

  • argon2-cffi、bcrypt、または現在のpasslib互換ハッシャーでパスワードをハッシュする。
  • JWTの発行者、オーディエンス、有効期限、署名アルゴリズムを検証する。
  • CORSオリジンを環境固有に保つ。
  • 認証と書き込み負荷の高いエンドポイントにレート制限を設ける。
  • すべてのリクエストボディにPydanticモデルを使用する。
  • ORMパラメーターバインディングまたはSQLAlchemy Coreの式を使用する; f文字列でSQLを構築しない。
  • ログからトークン、認可ヘッダー、クッキー、パスワードを削除する。
  • CIで依存関係の監査ツールを実行する。

パフォーマンスチェックリスト

  • データベース接続プールを明示的に設定する。
  • リストエンドポイントにページネーションを追加する。
  • N+1クエリに注意し、イーガーローディングを意図的に使用する。
  • 非同期パスでは非同期HTTP/データベースクライアントを使用する。
  • ペイロードサイズとCPUのトレードオフを確認してから圧縮を追加する。
  • 明示的な無効化の後ろで安定した高コストの読み取りをキャッシュする。

使用例

これらの例はプロジェクト全体のテンプレートではなく、パターンとして使用してください:

  • アプリケーションファクトリー: create_appでミドルウェアとルーターを一度設定する。
  • スキーマの分割: UserCreate、UserUpdate、UserResponseはそれぞれ異なる責務を持つ。
  • 依存関係のオーバーライド: テストはget_dbを直接オーバーライドする。
  • OpenAPIのカスタマイズ: app.openapi = custom_openapiを割り当てる。

関連情報

  • エージェント: fastapi-reviewer
  • コマンド: /fastapi-review
  • スキル: python-patterns
  • スキル: python-testing
  • スキル: api-design

© affaan-m, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in docs/ja-JP/skills/fastapi-patterns of affaan-m/ECC.

Open the folder on GitHubat commit ef648e0

Compare with similar skills

Fastapi Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Fastapi Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Fastapi Patterns this skillaffaan-m/ECC275k—~2kAutomated safety check: PassMIT
API Surface Reviewpolarsource/polar10k—~1.3kAutomated safety check: PassMIT
FastAPI ExpertJeffallan/claude-skills12k—~1.8kAutomated safety check: PassMIT
Python Fastapi Patternsaiskillstore/marketplace4301 repos~1.3kAutomated safety check: NotesNone
API Docs GeneratorMathews-Tom/armory328—~1.7kAutomated safety check: PassMIT
Fastapi Init Skilljiushiwon/wg-skills112—~1.8kAutomated safety check: NotesApache-2.0

Similar skills

  • API Surface Review

    polarsource/polar

    Review changes to Polar's API contract — Pydantic schemas, FastAPI endpoints, OpenAPI output and the generated SDKs.

    10k GitHub stars~1.3k tokensUpdated today
    Backend & APIsAuto-check passed
  • FastAPI Expert

    Jeffallan/claude-skills

    Builds async Python APIs with FastAPI and Pydantic V2, covering endpoints, JWT authentication, async SQLAlchemy, WebSockets and pytest checks against the OpenAPI docs.

    12k GitHub stars~1.8k tokensUpdated 4 days ago
    Backend & APIsAuto-check passed
  • Python Fastapi Patterns

    aiskillstore/marketplace

    FastAPI web framework patterns. An agent skill from aiskillstore/marketplace.

    430 GitHub starsUsed in 1 repo~1.3k tokens
    Backend & APIsAuto-check: notes
  • API Docs Generator

    Mathews-Tom/armory

    Audits and enhances FastAPI and REST API documentation: missing descriptions, response codes, examples, docstrings, Pydantic models, OpenAPI spec.

    328 GitHub stars~1.7k tokensUpdated 2 days ago
    Backend & APIsAuto-check passed
  • Fastapi Init Skill

    jiushiwon/wg-skills

    FastAPI 项目一键初始化技能。面向零基础小白,提供环境探测、自动安装、完整 Web 骨架生成、SSE 流式框架、JWT 鉴权、统一响应封装、文件上传接口、一键启动/重启脚本、Swagger 文档,内置 MySQL(默认)/ PostgreSQL / MongoDB 数据库选择。用户只需说"帮我搭一个 FastAPI 项目"即可一条命令完成从零到跑的完整链路。触发词:"FastAPI…

    112 GitHub stars~1.8k tokensUpdated yesterday
    Backend & APIsAuto-check: notes
  • Implementing API Patterns

    ancoleman/ai-design-components

    API design and implementation across REST, GraphQL, gRPC, and tRPC patterns.

    526 GitHub starsUsed in 1 repo~3k tokens
    Backend & APIsAuto-check passed

More from affaan-m/ECC

All 645 skills in this repo
  • Videodb

    affaan-m/ECC

    Ingest, index, search, edit, and monitor video and audio with the VideoDB Python SDK — upload from files, URLs, or RTSP feeds, build spoken and scene indexes with timestamped search and playable…

    275k GitHub starsUsed in 3 repos~3.5k tokens
    Auto-check: notes
  • Rules Distillation

    affaan-m/ECC

    Scans installed skills for principles that recur across them and proposes rule-file changes: append, revise, add a section, create a file or leave as covered.

    275k GitHub starsUsed in 2 repos~2.3k tokens
    Auto-check passed
  • Builds DRAFT counterparty agreements from one markdown template and a small JSON spec per party, with clauses picked by the party's role.

    275k GitHub stars~2.9k tokensUpdated 3 days ago
    Auto-check passed
  • Measures whether agents actually follow a skill, rule or agent definition by generating scenarios at three strictness levels and scoring tool-call traces.

    275k GitHub starsUsed in 1 repo~623 tokens
    Auto-check passed
  • Instinct-based learning system that observes sessions via hooks, creates atomic instincts with confidence scoring, and evolves them into skills/commands/agents.

    275k GitHub stars~3.5k tokensUpdated 3 days ago
    Auto-check passed
  • Adds one optional external Codex critique that tries to break a council's decision draft, sent to OpenAI only after you consent.

    275k GitHub stars~1.5k tokensUpdated 3 days ago
    Auto-check passed

Categories

Questions about Fastapi Patterns

What does Fastapi Patterns do?

非同期API、依存性注入、Pydanticのリクエスト・レスポンスモデル、OpenAPIドキュメント、テスト、セキュリティ、本番対応のためのFastAPIパターン。. Fastapi Patterns is an agent skill from affaan-m/ECC.

When should I use Fastapi Patterns?

Fastapi Patterns fits situations like: tasks that involve Backend development; tasks that involve OpenAPI specifications.

How do I install Fastapi Patterns in Claude Code?

Run `npx skills add affaan-m/ECC --skill fastapi-patterns -a claude-code`. Or copy the skill folder (docs/ja-JP/skills/fastapi-patterns in affaan-m/ECC) into .claude/skills/fastapi-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Fastapi Patterns in Codex?

Run `npx skills add affaan-m/ECC --skill fastapi-patterns -a codex`. Or copy the skill folder (docs/ja-JP/skills/fastapi-patterns in affaan-m/ECC) into .agents/skills/fastapi-patterns in your project. Codex loads it when a task matches its description.

Can I use Fastapi Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add affaan-m/ECC --skill fastapi-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/fastapi-patterns, .gemini/skills/fastapi-patterns, .github/skills/fastapi-patterns and .opencode/skills/fastapi-patterns in your project.

What does Fastapi Patterns need to run?

SKILL.md names no scripts, command-line tools or credentials: Fastapi Patterns is instructions for the agent only. Our summary lists: Python 3.

Does Fastapi Patterns access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Fastapi Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Fastapi Patterns use?

Fastapi Patterns is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Fastapi Patterns use?

About 2k tokens (SKILL.md is roughly 7.8k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Fastapi Patterns?

Skills that share tags, products or a category with Fastapi Patterns: API Surface Review (polarsource/polar, 10k stars), FastAPI Expert (Jeffallan/claude-skills, 12k stars), Python Fastapi Patterns (aiskillstore/marketplace, 430 stars) and API Docs Generator (Mathews-Tom/armory, 328 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Fastapi Patterns?

affaan-m (a GitHub user) maintains it in affaan-m/ECC, which has 275,023 GitHub stars. The repository holds 645 skills in this directory. The repository was last updated on October 5, 2026.

Source: affaan-m/ECC on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.