C
Python/Web/Lesson 25

FastAPI をはじめよう

1時間·theory
Python

FastAPI をはじめよう

🎯 このレッスンを読み終えたら

このレッスンを読み終えると、以下の3つを自信を持って行えるようになります。

  • ✅ Python が なぜ AI/データの標準言語になったのか
  • ✅ Python 3.x 基準での venv + requirements.txt のセットアップ
  • ✅ print / input / type / dir の4つの組み込み関数

学習目標を チェックリストとして手元に置き、すべて答えられるようになったらレッスンを閉じてください。

FastAPI — コード + 実行結果

FastAPI = Python モダン Web フレームワーク。型ヒントの自動検証 + Swagger UI の自動生成。非同期標準。

1. インストール + Hello World

bash
$ pip install fastapi uvicorn
python
# main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def index():
    return {"message": "こんにちは!"}
bash
$ uvicorn main:app --reload
# http://localhost:8000 → {"message": "こんにちは!"}
# http://localhost:8000/docs → Swagger UI 自動

2. パスパラメータ

python
@app.get("/items/{id}")              # /items/42 → id=42
def item(id: int):                 # タイプヒント = 自動変換
    return {"id": id, "name": f"アイテム {id}"}

# /items/abc → 422 エラー (自動検証)

3. クエリパラメータ

python
@app.get("/search")                 # /search?q=python&limit=10
def search(q: str, limit: int = 5):
    return {"検索語": q, "個数": limit}

4. POST + リクエストボディ (Pydantic)

python
from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int
    email: str | None = None

@app.post("/users")
def create(u: User):                # JSON → 自動検証
    return {"作成済み": u.name}

# リクエスト: POST /users {"name": "山田太郎", "age": 28}
# レスポンス: {"作成済み": "山田太郎"}
# 不正なJSON → 422 エラー自動

5. 非同期 + DB 呼び出し

python
@app.get("/users/{id}")
async def get(id: int):
    user = await db.fetch_one("SELECT * FROM users WHERE id = $1", id)
    if not user:
        raise HTTPException(404, "なし")
    return user

一言まとめ

@app.get/post + 型ヒント + Pydantic モデル の3つで REST API は完成です。

💻 FastAPI 基本サンプル
# pip install fastapi uvicorn
from fastapi import FastAPI, Query, Path
from typing import Optional

app = FastAPI(title="My API", version="1.0.0")

# 基本エンドポイント
@app.get("/")
def read_root():
    return {"message": "Hello, FastAPI!"}

# パスパラメータ
@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

# クエリパラメータ
@app.get("/search/")
def search(
    q: str,
    skip: int = 0,
    limit: int = Query(default=10, le=100)
):
    return {"q": q, "skip": skip, "limit": limit}

# 非同期エンドポイント
@app.get("/async/")
async def async_endpoint():
    return {"message": "Async response"}

# 実行: uvicorn main:app --reload
# ドキュメント: http://localhost:8000/docs (Swagger UI)
# ドキュメント: http://localhost:8000/redoc (ReDoc)

💡 重要ポイント

1. API ドキュメント自動生成: /docs, /redoc
2. 型ヒント → 自動バリデーション
3. uvicorn: ASGI サーバー

Python は簡潔で読みやすい構文を持ち、さまざまな分野で活用されています。インタープリター言語であり、REPL 環境で即時実行が可能です。PEP 8 コーディングスタイルガイドに従い、Black/autopep8 で自動フォーマットします。型ヒント (type hints) によりコードの可読性と IDE サポートが向上します。pip でパッケージを管理し、venv/conda で仮想環境を構築します。

🐍 実際に試してみよう — FastAPI をはじめよう

上記の概念を実際のコードで動かしてみてください。値を変えながら動作を直接確認することが、最も速い学習方法です。
✏️ Python 코드
📟 コンソール出力
▶ 実行ボタンを押してください
🐍 Pyodideで実際のPythonを実行 — 初回は読み込みに3〜5秒

🤖 AI にこう聞いてみよう

このレッスンの概念を理解すると、AI に 具体的に 指示できるようになります。漠然とした「直して」ではなく、語彙を持ったリクエスト — それがトークン節約の出発点です。

  • 「この Flask コードを FastAPI に移行して」
  • 「この FastAPI エンドポイントに Pydantic モデル + 依存性注入を追加して」

なぜこれがトークンを減らすのか

概念を知らないと、AI の回答を受け取っても 「それは何ですか?」 とまた聞き直すことになります。その「聞き直し」がトークンを消費します。概念を一度しっかり理解しておけば、会話が一回で終わります

次のおすすめ: NumPy入門
FastAPI入門 - Python