fastapi-expert
FastAPIに関する幅広い知識を活用し、REST API構築からデータベース連携、認証、Docker/Kubernetesへのデプロイ、セキュリティ、性能最適化まで、実用的なAPI開発を支援するSkill。
📜 元の英語説明(参考)
Comprehensive FastAPI knowledge for building production-ready APIs from basic to planet-scale. Use when building FastAPI applications, implementing REST APIs, setting up database operations with SQLModel, implementing authentication (OAuth2/JWT), deploying to Docker/Kubernetes, or needing guidance on middleware, WebSockets, background tasks, dependency injection, security, scalability, or performance optimization. Triggers include "FastAPI", "build API", "REST endpoint", "SQLModel", "OAuth2", "JWT", "deploy FastAPI", "Docker FastAPI", "Kubernetes", "API security", or questions about Python web frameworks.
🇯🇵 日本人クリエイター向け解説
FastAPIに関する幅広い知識を活用し、REST API構築からデータベース連携、認証、Docker/Kubernetesへのデプロイ、セキュリティ、性能最適化まで、実用的なAPI開発を支援するSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o fastapi-expert.zip https://jpskill.com/download/23592.zip && unzip -o fastapi-expert.zip && rm fastapi-expert.zip
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/23592.zip -OutFile "$d\fastapi-expert.zip"; Expand-Archive "$d\fastapi-expert.zip" -DestinationPath $d -Force; ri "$d\fastapi-expert.zip"
完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。
💾 手動でダウンロードしたい(コマンドが難しい人向け)
- 1. 下の青いボタンを押して
fastapi-expert.zipをダウンロード - 2. ZIPファイルをダブルクリックで解凍 →
fastapi-expertフォルダができる - 3. そのフォルダを
C:\Users\あなたの名前\.claude\skills\(Win)または~/.claude/skills/(Mac)へ移動 - 4. Claude Code を再起動
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-18
- 取得日時
- 2026-05-18
- 同梱ファイル
- 12
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
FastAPI Expert
基本的なAPI開発から惑星規模のデプロイメントまでを網羅する、本番環境に対応したFastAPIの知識です。
クイックスタート
基本的なFastAPIアプリケーションを作成します。
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
# Run with: uvicorn main:app --reload
主要トピック
1. データベース操作
- SQLModelの統合(推奨ORM)
- 依存性注入によるCRUD操作
- 非同期データベース操作
- コネクションプーリング
- Alembicによるマイグレーション
- Neon Serverless PostgreSQLのセットアップ
2. セキュリティと認証
- パスワードフローによるOAuth2
- JWTトークンベースの認証
- Argon2によるパスワードハッシュ化
- 権限のためのOAuth2スコープ
- CORS設定
- レート制限
- APIキー認証
- セキュリティのベストプラクティス
3. デプロイメントとスケーラビリティ
- Dockerコンテナ化
- Kubernetesデプロイメント
- 本番サーバー構成(Uvicorn + Gunicorn)
- 水平ポッドオートスケーリング
- Prometheusによるパフォーマンス監視
- Redisによるキャッシング戦略
- プラットフォーム固有のガイド(Vercel、AWS、GCP)
4. 高度な機能
- 依存性注入パターン
- カスタムミドルウェア
- WebSocketサポート
- バックグラウンドタスク
- バリデーション付きリクエスト/レスポンスモデル
- ストリーミングレスポンス
- ファイルアップロード
- テスト戦略
- イベントハンドラ
プロジェクトテンプレート
assets/に用意されている本番環境対応テンプレートを使用してください。
FastAPIプロジェクト構造
assets/project-template/
├── main.py # Application entry point
├── config.py # Settings management
├── database.py # Database setup
├── models.py # SQLModel models
└── auth.py # Authentication logic
新しいプロジェクトを開始するためにテンプレートをコピーします。
cp -r assets/project-template/* your-project/
Dockerデプロイメント
マルチステージビルドとセキュリティのベストプラクティスを用いてアプリケーションをコンテナ化するには、assets/Dockerfileを使用してください。
Kubernetesデプロイメント
以下を含むKubernetesへのデプロイには、assets/kubernetes-deployment.yamlを使用してください。
- 3つのレプリカを持つデプロイメント
- LoadBalancerを持つサービス
- Horizontal Pod Autoscaler
- ヘルスプローブとレディネスプローブ
一般的なパターン
セッション依存性を持つデータベースCRUD
from typing import Annotated
from fastapi import Depends
from sqlmodel import Session, select
SessionDep = Annotated[Session, Depends(get_session)]
@app.get("/users/{user_id}")
def get_user(user_id: int, session: SessionDep):
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
認証で保護されたルート
from typing import Annotated
from fastapi import Depends
CurrentUser = Annotated[User, Depends(get_current_active_user)]
@app.get("/users/me")
async def read_users_me(current_user: CurrentUser):
return current_user
バックグラウンドタスク
from fastapi import BackgroundTasks
@app.post("/send-email/")
async def send_email(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email_task, email)
return {"message": "Email queued"}
ベストプラクティスチェックリスト
開発
- [ ] あらゆる場所で型ヒントを使用する
- [ ] Pydanticでリクエスト/レスポンスモデルを実装する
- [ ] 共有ロジックに依存性注入を使用する
- [ ] HTTPExceptionで適切なエラーハンドリングを追加する
- [ ] I/O操作にasync/awaitを使用する
セキュリティ
- [ ] Argon2でパスワードをハッシュ化する
- [ ] 認証にJWTを使用する
- [ ] 認可にOAuth2スコープを実装する
- [ ] CORSを適切に設定する
- [ ] シークレットを環境変数に保存する
- [ ] 本番環境でHTTPSを有効にする
データベース
- [ ] ORMにSQLModelを使用する
- [ ] コネクションプーリングを実装する
- [ ] マイグレーション(Alembic)を使用する
- [ ] セッションに依存性注入を活用する
- [ ] パフォーマンスのためにデータベースインデックスを追加する
デプロイメント
- [ ] マルチステージDockerfile
- [ ] 非rootコンテナユーザー
- [ ] ヘルスチェックエンドポイント
- [ ] Kubernetesでのリソース制限
- [ ] 水平ポッドオートスケーリング
- [ ] Prometheusメトリクス
- [ ] 構造化ロギング
スケーラビリティ戦略
非同期操作
I/Oを実行するエンドポイントには常にasync defを使用します。
@app.get("/users/")
async def get_users():
users = await fetch_from_db()
return users
キャッシング
頻繁にアクセスされるデータにはRedisキャッシングを実装します。
@cache(expire=600)
async def expensive_operation():
# Heavy computation
return result
バックグラウンド処理
時間のかかるタスクをオフロードします。
background_tasks.add_task(process_data, data)
コネクションプーリング
データベースコネクションプールを設定します。
engine = create_engine(
DATABASE_URL,
pool_size=20,
max_overflow=10,
pool_timeout=30
)
トラブルシューティング
パフォーマンスの問題
- Prometheusメトリクスを有効にしてボトルネックを特定する
- すべてのI/Oに非同期操作を使用する
- Redisでキャッシングを実装する
- データベースクエリを最適化する(インデックス、Eager Loading)
- GZip圧縮を有効にする
認証エラー
- JWTシークレットキーが一致していることを確認する
- トークンの有効期限を確認する
- パスワードハッシュ化が一貫していることを確認する
- CORS設定を検証する
データベース接続の問題
- 接続文字列の形式を確認する
- コネクションプール設定を確認する
- データベースの到達可能性をテストする
- ファイアウォールルールを確認する
本番デプロイメントフロー
- ローカルで自動リロードを使用して開発する
- TestClientとpytestでテストする
- Dockerイメージをビルドする
- コンテナレジストリにプッシュする
- Kubernetesクラスターにデプロイする
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
FastAPI Expert
Production-ready FastAPI knowledge covering basic API development to planet-scale deployment.
Quick Start
Create a basic FastAPI application:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
# Run with: uvicorn main:app --reload
Core Topics
1. Database Operations
- SQLModel integration (recommended ORM)
- CRUD operations with dependency injection
- Async database operations
- Connection pooling
- Migrations with Alembic
- Neon Serverless PostgreSQL setup
2. Security & Authentication
- OAuth2 with password flow
- JWT token-based authentication
- Password hashing with Argon2
- OAuth2 scopes for permissions
- CORS configuration
- Rate limiting
- API key authentication
- Security best practices
3. Deployment & Scalability
- Docker containerization
- Kubernetes deployment
- Production server configuration (Uvicorn + Gunicorn)
- Horizontal pod autoscaling
- Performance monitoring with Prometheus
- Caching strategies with Redis
- Platform-specific guides (Vercel, AWS, GCP)
4. Advanced Features
- Dependency injection patterns
- Custom middleware
- WebSocket support
- Background tasks
- Request/response models with validation
- Streaming responses
- File uploads
- Testing strategies
- Event handlers
Project Templates
Use the provided production-ready templates in assets/:
FastAPI Project Structure
assets/project-template/
├── main.py # Application entry point
├── config.py # Settings management
├── database.py # Database setup
├── models.py # SQLModel models
└── auth.py # Authentication logic
Copy the template to start a new project:
cp -r assets/project-template/* your-project/
Docker Deployment
Use assets/Dockerfile for containerizing your application with multi-stage builds and security best practices.
Kubernetes Deployment
Use assets/kubernetes-deployment.yaml for deploying to Kubernetes with:
- Deployment with 3 replicas
- Service with LoadBalancer
- Horizontal Pod Autoscaler
- Health and readiness probes
Common Patterns
Database CRUD with Session Dependency
from typing import Annotated
from fastapi import Depends
from sqlmodel import Session, select
SessionDep = Annotated[Session, Depends(get_session)]
@app.get("/users/{user_id}")
def get_user(user_id: int, session: SessionDep):
user = session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
Protected Routes with Authentication
from typing import Annotated
from fastapi import Depends
CurrentUser = Annotated[User, Depends(get_current_active_user)]
@app.get("/users/me")
async def read_users_me(current_user: CurrentUser):
return current_user
Background Tasks
from fastapi import BackgroundTasks
@app.post("/send-email/")
async def send_email(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_email_task, email)
return {"message": "Email queued"}
Best Practices Checklist
Development
- [ ] Use type hints everywhere
- [ ] Implement request/response models with Pydantic
- [ ] Use dependency injection for shared logic
- [ ] Add proper error handling with HTTPException
- [ ] Use async/await for I/O operations
Security
- [ ] Hash passwords with Argon2
- [ ] Use JWT for authentication
- [ ] Implement OAuth2 scopes for authorization
- [ ] Configure CORS properly
- [ ] Store secrets in environment variables
- [ ] Enable HTTPS in production
Database
- [ ] Use SQLModel for ORM
- [ ] Implement connection pooling
- [ ] Use migrations (Alembic)
- [ ] Leverage dependency injection for sessions
- [ ] Add database indexes for performance
Deployment
- [ ] Multi-stage Dockerfile
- [ ] Non-root container user
- [ ] Health check endpoints
- [ ] Resource limits in Kubernetes
- [ ] Horizontal pod autoscaling
- [ ] Prometheus metrics
- [ ] Structured logging
Scalability Strategies
Async Operations
Always use async def for endpoints that perform I/O:
@app.get("/users/")
async def get_users():
users = await fetch_from_db()
return users
Caching
Implement Redis caching for frequently accessed data:
@cache(expire=600)
async def expensive_operation():
# Heavy computation
return result
Background Processing
Offload long-running tasks:
background_tasks.add_task(process_data, data)
Connection Pooling
Configure database connection pools:
engine = create_engine(
DATABASE_URL,
pool_size=20,
max_overflow=10,
pool_timeout=30
)
Troubleshooting
Performance Issues
- Enable Prometheus metrics to identify bottlenecks
- Use async operations for all I/O
- Implement caching with Redis
- Optimize database queries (indexes, eager loading)
- Enable GZip compression
Authentication Errors
- Verify JWT secret key matches
- Check token expiration time
- Ensure password hashing is consistent
- Validate CORS configuration
Database Connection Issues
- Check connection string format
- Verify connection pool settings
- Test database reachability
- Review firewall rules
Production Deployment Flow
- Develop locally with auto-reload
- Test with TestClient and pytest
- Build Docker image
- Push to container registry
- Deploy to Kubernetes cluster
- Monitor with Prometheus/Grafana
- Scale with HPA based on metrics
Example: Complete CRUD API
from fastapi import FastAPI, Depends, HTTPException
from sqlmodel import Field, Session, SQLModel, create_engine, select
from typing import Annotated
# Database setup
engine = create_engine("sqlite:///database.db")
def get_session():
with Session(engine) as session:
yield session
SessionDep = Annotated[Session, Depends(get_session)]
# Model
class Item(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
title: str
description: str | None = None
# App
app = FastAPI()
@app.on_event("startup")
def on_startup():
SQLModel.metadata.create_all(engine)
# CRUD endpoints
@app.post("/items/", response_model=Item)
def create_item(item: Item, session: SessionDep):
session.add(item)
session.commit()
session.refresh(item)
return item
@app.get("/items/", response_model=list[Item])
def read_items(session: SessionDep, skip: int = 0, limit: int = 100):
items = session.exec(select(Item).offset(skip).limit(limit)).all()
return items
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int, session: SessionDep):
item = session.get(Item, item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@app.patch("/items/{item_id}", response_model=Item)
def update_item(item_id: int, item_update: Item, session: SessionDep):
db_item = session.get(Item, item_id)
if not db_item:
raise HTTPException(status_code=404, detail="Item not found")
item_data = item_update.model_dump(exclude_unset=True)
for key, value in item_data.items():
setattr(db_item, key, value)
session.add(db_item)
session.commit()
session.refresh(db_item)
return db_item
@app.delete("/items/{item_id}")
def delete_item(item_id: int, session: SessionDep):
item = session.get(Item, item_id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
session.delete(item)
session.commit()
return {"ok": True}
This skill provides everything needed to build production-ready FastAPI applications from basic CRUD to planet-scale deployments.
同梱ファイル
※ ZIPに含まれるファイル一覧。`SKILL.md` 本体に加え、参考資料・サンプル・スクリプトが入っている場合があります。
- 📄 SKILL.md (9,048 bytes)
- 📎 assets/Dockerfile (828 bytes)
- 📎 assets/kubernetes-deployment.yaml (2,074 bytes)
- 📎 assets/project-template/auth.py (2,406 bytes)
- 📎 assets/project-template/config.py (784 bytes)
- 📎 assets/project-template/database.py (590 bytes)
- 📎 assets/project-template/main.py (2,142 bytes)
- 📎 assets/project-template/models.py (909 bytes)
- 📎 references/advanced.md (12,064 bytes)
- 📎 references/database.md (6,562 bytes)
- 📎 references/deployment.md (10,644 bytes)
- 📎 references/security.md (8,997 bytes)