All skills

fastapi-patterns

Official
by Api.AirforcePrepends a system promptBackend & APIs000 uses202,700

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

open-sourceclaude-codebackend-apisaffaan-m
Share

What this skill does

When applied, it prepends a system prompt before your request is sent — no extra calls and no change to how you are billed beyond the added tokens.

---
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_ex

Use this skill

Per request

Add a "skill" field with the skill’s ID to your chat completion request. It is applied server-side before your prompt is sent — no extra calls.

{
  "model": "gpt-4o-mini",
  "skill": "imp-7f861957-f701-413f-8b42-d50203bd6beb",
  "messages": [{ "role": "user", "content": "…" }]
}
Always on — no field to send

Install the skill, enable it in your dashboard and (optionally) limit it to specific models. It then applies automatically to every matching request — with no "skill" field to send each time.

Set it up in your dashboard