jpskill.com
🛠️ 開発・MCP コミュニティ

fastapi-development

Build async APIs with FastAPI, including endpoints, dependency injection, validation, and testing. Use when creating REST APIs, web backends, or microservices.

⚡ おすすめ: コマンド1行でインストール(60秒)

下記のコマンドをコピーしてターミナル(Mac/Linux)または PowerShell(Windows)に貼り付けてください。 ダウンロード → 解凍 → 配置まで全自動。

🍎 Mac / 🐧 Linux
mkdir -p ~/.claude/skills && cd ~/.claude/skills && curl -L -o fastapi-development.zip https://jpskill.com/download/17565.zip && unzip -o fastapi-development.zip && rm fastapi-development.zip
🪟 Windows (PowerShell)
$d = "$env:USERPROFILE\.claude\skills"; ni -Force -ItemType Directory $d | Out-Null; iwr https://jpskill.com/download/17565.zip -OutFile "$d\fastapi-development.zip"; Expand-Archive "$d\fastapi-development.zip" -DestinationPath $d -Force; ri "$d\fastapi-development.zip"

完了後、Claude Code を再起動 → 普通に「動画プロンプト作って」のように話しかけるだけで自動発動します。

💾 手動でダウンロードしたい(コマンドが難しい人向け)
  1. 1. 下の青いボタンを押して fastapi-development.zip をダウンロード
  2. 2. ZIPファイルをダブルクリックで解凍 → fastapi-development フォルダができる
  3. 3. そのフォルダを C:\Users\あなたの名前\.claude\skills\(Win)または ~/.claude/skills/(Mac)へ移動
  4. 4. Claude Code を再起動

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-18
取得日時
2026-05-18
同梱ファイル
1

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

FastAPI 開発

クイックスタート

基本的な FastAPI アプリケーションを作成します。

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

以下を実行します。

uv run uvicorn main:app --reload

一般的なパターン

バリデーションのための Pydantic モデル

from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

@app.post("/items/")
async def create_item(item: Item):
    return item

依存性注入

from typing import Annotated
from fastapi import Depends

async def common_parameters(
    q: str | None = None,
    skip: int = 0,
    limit: int = 100
):
    return {"q": q, "skip": skip, "limit": limit}

CommonsDep = Annotated[dict, Depends(common_parameters)]

@app.get("/items/")
async def read_items(commons: CommonsDep):
    return commons

クリーンアップ付きのデータベース依存性

async def get_db():
    db = connect_to_database()
    try:
        yield db
    finally:
        db.close()

@app.get("/query/")
async def query_data(db: Annotated[dict, Depends(get_db)]):
    return {"data": "query results"}

エラー処理

from fastapi import HTTPException

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id < 1:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

パスとクエリのバリデーション

from typing import Annotated
from fastapi import Path, Query

@app.get("/items/{item_id}")
async def read_item(
    item_id: Annotated[int, Path(gt=0, le=1000)],
    q: Annotated[str, Query(max_length=50)] = None
):
    return {"item_id": item_id, "q": q}

レスポンスモデル

from pydantic import BaseModel

class ItemPublic(BaseModel):
    id: int
    name: str
    price: float

@app.get("/items/{item_id}", response_model=ItemPublic)
async def read_item(item_id: int):
    return ItemPublic(id=item_id, name="Laptop", price=999.99)

TestClient を使ったテスト

from fastapi.testclient import TestClient

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"Hello": "World"}

def test_read_item():
    response = client.get("/items/42?q=test")
    assert response.status_code == 200
    assert response.json() == {"item_id": 42, "q": "test"}

必要条件

uv add fastapi uvicorn
uv add "fastapi[all]"  # すべてのオプションの依存関係を含みます

主要な概念

  • Async/await: I/O 操作には async def を使用します
  • 自動バリデーション: Pydantic によるリクエスト/レスポンスのバリデーション
  • 依存性注入: Depends を使用してエンドポイント間でロジックを共有します
  • 型ヒント: 完全なエディターサポートとバリデーション
  • インタラクティブドキュメント: /docs で自動生成される Swagger/OpenAPI
  • バックグラウンドタスク: BackgroundTasks を使用してレスポンス後にタスクを実行します
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

FastAPI Development

Quick start

Create a basic FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

Run with:

uv run uvicorn main:app --reload

Common patterns

Pydantic models for validation

from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

@app.post("/items/")
async def create_item(item: Item):
    return item

Dependency injection

from typing import Annotated
from fastapi import Depends

async def common_parameters(
    q: str | None = None,
    skip: int = 0,
    limit: int = 100
):
    return {"q": q, "skip": skip, "limit": limit}

CommonsDep = Annotated[dict, Depends(common_parameters)]

@app.get("/items/")
async def read_items(commons: CommonsDep):
    return commons

Database dependencies with cleanup

async def get_db():
    db = connect_to_database()
    try:
        yield db
    finally:
        db.close()

@app.get("/query/")
async def query_data(db: Annotated[dict, Depends(get_db)]):
    return {"data": "query results"}

Error handling

from fastapi import HTTPException

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id < 1:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item_id": item_id}

Path and query validation

from typing import Annotated
from fastapi import Path, Query

@app.get("/items/{item_id}")
async def read_item(
    item_id: Annotated[int, Path(gt=0, le=1000)],
    q: Annotated[str, Query(max_length=50)] = None
):
    return {"item_id": item_id, "q": q}

Response models

from pydantic import BaseModel

class ItemPublic(BaseModel):
    id: int
    name: str
    price: float

@app.get("/items/{item_id}", response_model=ItemPublic)
async def read_item(item_id: int):
    return ItemPublic(id=item_id, name="Laptop", price=999.99)

Testing with TestClient

from fastapi.testclient import TestClient

client = TestClient(app)

def test_read_root():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"Hello": "World"}

def test_read_item():
    response = client.get("/items/42?q=test")
    assert response.status_code == 200
    assert response.json() == {"item_id": 42, "q": "test"}

Requirements

uv add fastapi uvicorn
uv add "fastapi[all]"  # Includes all optional dependencies

Key concepts

  • Async/await: Use async def for I/O operations
  • Automatic validation: Request/response validation with Pydantic
  • Dependency injection: Share logic across endpoints with Depends
  • Type hints: Full editor support and validation
  • Interactive docs: Auto-generated Swagger/OpenAPI at /docs
  • Background tasks: Run tasks after response using BackgroundTasks