mcpField
F
fastapi-templates

fastapi-templates

github.com/midudev開発7.0k60 回インストール2 週間前に更新
リポジトリ

fastapi-templates について

FastAPIアプリケーションの構成と実装方法を示すスキルです。非同期APIやサービスを開発する人向けに、依存性注入、ミドルウェア、データベースアクセス、テストのパターンを扱います。

主な機能

  1. 01推奨されるFastAPIプロジェクト構成
  2. 02依存性注入のパターン
  3. 03非同期ルートとデータベース操作
  4. 04ミドルウェアとバックグラウンドタスクのパターン
  5. 05テスト例

活用シーン

  1. 01FastAPIプロジェクトの開始
  2. 02非同期REST APIの構築
  3. 03Pythonマイクロサービスの構成
  4. 04APIテストの設定

インストール

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

$npx skills add https://github.com/midudev/autoskills --skill fastapi-templates

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

同梱ファイルreferences/details.md

詳細

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

本番環境で利用可能な FastAPI プロジェクト構成。非同期パターン、依存性注入、ミドルウェア、および高性能 API を構築するためのベストプラクティスを備えています。

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

  • 新規 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. 依存性注入

Depends を使用した FastAPI 組み込みの DI システム:

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

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

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

詳細な実例とパターン

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

テスト

# tests/conftest.py
import pytest
import asyncio
from httpx import 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:"

@pytest.fixture(scope="session")
def event_loop():
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

@pytest.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

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

    app.dependency_overrides[get_db] = override_get_db

    async with AsyncClient(app=app, base_url="http://test") as client:
        yield client

# 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

コメント