mcpField
F
fastapi-templates

fastapi-templates

github.com/wshobson開発41.9k26.1k 回インストール2 週間前に更新
リポジトリ

fastapi-templates について

fastapi-templates は FastAPI サービス向けのプロジェクト構成と実装パターンを提供するスキルです。非同期 API の構築に取り組む開発者を対象に、依存性注入、ミドルウェア、テストを扱います。

主な機能

  1. 01FastAPI プロジェクト構成
  2. 02非同期ルートと DB パターン
  3. 03依存性注入の実践
  4. 04ミドルウェアパターン
  5. 05非同期テスト例

活用シーン

  1. 01FastAPI プロジェクトの新規作成
  2. 02非同期 REST API の実装
  3. 03PostgreSQL または MongoDB アプリの設計
  4. 04API のテスト構成

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/wshobson/agents --skill fastapi-templates

インストール後、Claude Code で/fastapi-templatesを入力して読み込まれたか確認します。

同梱ファイルreferences/details.md

詳細

FastAPI プロジェクトテンプレート

非同期パターン、依存性注入、ミドルウェア、ベストプラクティスを取り入れ、高性能な API を構築するための、本番環境対応の FastAPI プロジェクト構成です。

このスキルを使用する場面

  • FastAPI プロジェクトをゼロから始める
  • Python で非同期 REST API を実装する
  • 高性能な Web サービスやマイクロサービスを構築する
  • PostgreSQL、MongoDB を使用した非同期アプリケーションを作成する
  • 適切な構成とテストを備えた API プロジェクトを設定する

主な概念

1. プロジェクト構成

推奨レイアウト:

app/
├── api/                    # API routes
│   ├── v1/
│   │   ├── endpoints/
│   │   │   ├── users.py
│   │   │   ├── auth.py
│   │   │   └── items.py
│   │   └── router.py
│   └── dependencies.py     # Shared dependencies
├── core/                   # Core configuration
│   ├── config.py
│   ├── security.py
│   └── database.py
├── models/                 # Database models
│   ├── user.py
│   └── item.py
├── schemas/                # Pydantic schemas
│   ├── user.py
│   └── item.py
├── services/               # Business logic
│   ├── user_service.py
│   └── auth_service.py
├── repositories/           # Data access
│   ├── user_repository.py
│   └── item_repository.py
└── main.py                 # Application entry
2. 依存性注入

FastAPI に組み込まれている Depends を使用した DI システム:

  • データベースセッションの管理
  • 認証/認可
  • 共有するビジネスロジック
  • 設定の注入
3. 非同期パターン

適切な async/await の使用方法:

  • 非同期ルートハンドラー
  • 非同期データベース操作
  • 非同期バックグラウンドタスク
  • 非同期ミドルウェア
4. 依存関係

サンプルでインポートするパッケージ:

# requirements.txt
fastapi
uvicorn[standard]
pydantic-settings
sqlalchemy[asyncio]>=2.0  # DeclarativeBase; [asyncio] installs greenlet for the async engine
asyncpg                   # PostgreSQL driver: postgresql+asyncpg://...
PyJWT
pwdlib[argon2]
python-multipart          # only for a login route that uses OAuth2PasswordRequestForm

# requirements-dev.txt
pytest
pytest-asyncio
httpx
aiosqlite                 # test database: sqlite+aiosqlite:///:memory:

詳細な実例とパターン

詳しいセクション(## Implementation Patterns から始まります)は references/details.md にあります。上記のナビゲーション概要だけでは不十分な場合は、このファイルを参照してください。

テスト

# tests/conftest.py
import pytest_asyncio
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

from app.main import app
from app.core.database import get_db, Base

TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"

# Async fixtures need pytest_asyncio.fixture in pytest-asyncio's default strict mode
@pytest_asyncio.fixture
async def db_session():
    engine = create_async_engine(TEST_DATABASE_URL, echo=True)
    async with engine.begin() as conn:
        await conn.run_sync(Base.metadata.create_all)

    AsyncSessionLocal = sessionmaker(
        engine, class_=AsyncSession, expire_on_commit=False
    )

    async with AsyncSessionLocal() as session:
        yield session
    await engine.dispose()

@pytest_asyncio.fixture
async def client(db_session):
    async def override_get_db():
        yield db_session

    app.dependency_overrides[get_db] = override_get_db

    # httpx 0.28 removed AsyncClient(app=...); use an ASGI transport
    transport = ASGITransport(app=app)
    async with AsyncClient(transport=transport, base_url="http://test") as client:
        yield client
    app.dependency_overrides.clear()

# tests/test_users.py
import pytest

@pytest.mark.asyncio
async def test_create_user(client):
    response = await client.post(
        "/api/v1/users/",
        json={
            "email": "[email protected]",
            "password": "testpass123",
            "name": "Test User"
        }
    )
    assert response.status_code == 201
    data = response.json()
    assert data["email"] == "[email protected]"
    assert "id" in data

コメント