Skip to content

FastAPI チートシート

API 構築のためのモダンで高速な Python Web フレームワーク。

01

はじめに

最初の API

FastAPI は Starlette と Pydantic の上に構築されています。uvicorn が ASGI サーバーで、--reload が開発中の自動リロードを有効にします。

fastapi
# install FastAPI and uvicorn
pip install fastapi uvicorn

# main.py
from fastapi import FastAPI

app = FastAPI()

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

# run: uvicorn main:app --reload

Uvicorn での実行

app インスタンス 'main:app' はモジュール 'main' の変数 'app' を意味します。--reload は開発時だけに使うこと。本番では付けずに実行し、プロセスマネージャーを使いましょう。

fastapi
# development with auto-reload
uvicorn main:app --reload

# specify host and port
uvicorn main:app --host 0.0.0.0 --port 8000

# run programmatically
import uvicorn
if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, reload=True)

非同期のパス操作

パス操作は 'def'(スレッドプールで実行)でも 'async def' でも宣言できます。関数が非同期ライブラリ経由で I/O を行うなら async def を使いましょう。async def 内でブロッキング呼び出しを混ぜるとイベントループが塞がります。

fastapi
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "hello"}

@app.get("/sync")
def read_sync():
    return {"message": "sync also works"}

# use async when calling async libs (httpx, databases)
@app.get("/data")
async def fetch_data():
    import httpx
    async with httpx.AsyncClient() as client:
        r = await client.get("https://api.example.com")
    return r.json()

パス操作のデコレータ

FastAPI はすべての HTTP メソッドに対応します:GET、POST、PUT、PATCH、DELETE、OPTIONS、HEAD。各メソッドがデコレータに対応します。デフォルトの成功ステータスを上書きするには、デコレータに status_code= を付けます。

fastapi
from fastapi import FastAPI

app = FastAPI()

@app.get("/items")
def list_items(): ...

@app.post("/items")
def create_item(): ...

@app.put("/items/{item_id}")
def replace_item(item_id: int): ...

@app.patch("/items/{item_id}")
def update_item(item_id: int): ...

@app.delete("/items/{item_id}")
def delete_item(item_id: int): ...

@app.options("/items")
def options_items(): ...

@app.head("/items")
def head_items(): ...

JSON レスポンスとステータス

dict/list を返すと、200(または指定した status_code)で自動的に JSON へ変換されます。ステータス、ヘッダー、コンテンツを完全に制御したい場合は、JSONResponse や Response を直接返しましょう。

fastapi
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/plain")
def plain():
    return {"key": "value"}  # auto JSON, 200 OK

@app.post("/created", status_code=status.HTTP_201_CREATED)
def created():
    return {"id": 1}

@app.get("/custom")
def custom():
    return JSONResponse(
        status_code=418,
        content={"error": "I'm a teapot"},
        headers={"X-Custom": "yes"},
    )

プロジェクト構成

成長するアプリは APIRouter でモジュールに分割し、app.include_router() で登録します。保守性のため、Pydantic スキーマ、DB セットアップ、依存関係は別ファイルに保ちましょう。

fastapi
myapp/
  main.py              # creates the FastAPI app
  routers/
    users.py           # APIRouter for /users
    items.py           # APIRouter for /items
  models/
    schemas.py         # Pydantic models
    database.py        # DB engine & session
  dependencies.py      # shared Depends functions
  tests/
    test_main.py

# main.py
from fastapi import FastAPI
from routers import users, items
app = FastAPI()
app.include_router(users.router)
app.include_router(items.router, prefix="/items")
02

パスパラメータ

基本のパスパラメータ

パスから取り込まれる値は、型アノテーションを付けない限り文字列です。パス内のパラメータ名は関数の引数名と正確に一致させる必要があります。

fastapi
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id):
    return {"item_id": item_id}

# GET /items/42 -> {"item_id": "42"}  (string by default)

型変換

型アノテーション(int、float、bool、str、Enum)を付けると、FastAPI がパスの値を検証・変換します。無効な値は明確なエラーメッセージ付きの 422 レスポンスを返します。

fastapi
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

# GET /items/3   -> {"item_id": 3}
# GET /items/abc -> 422 Validation Error (not an integer)

パスのバリデーション

Path() がパスパラメータにメタデータと制約を加えます。数値の制約:ge(>=)、gt(>)、le(<=)、lt(<)。パスパラメータは常に必須のため、Path() ではデフォルト値を設定できません。

fastapi
from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(
    item_id: int = Path(
        title="The ID of the item",
        description="Must be a positive integer",
        ge=1,
        le=1000,
    ),
):
    return {"item_id": item_id}

数値の制約

int や float のパスパラメータに ge/gt/le/lt を使うと数値の範囲が強制されます。制約を組み合わせれば、自動 422 エラー付きの正確な境界バリデーションが得られます。

fastapi
from fastapi import FastAPI, Path

app = FastAPI()

@app.get("/ratio/{value}")
def ratio(
    value: float = Path(gt=0, lt=1),  # 0 < value < 1
):
    return {"value": value}

@app.get("/page/{page}")
def page(
    page: int = Path(ge=1),       # >= 1
    size: int = Path(le=100),     # <= 100
):
    return {"page": page, "size": size}

ルートの順序が重要

ルートは宣言順にマッチします。/users/{user_id} のような動的パターンの前に、/users/me のような具体的なパスを宣言しましょう — さもないと動的ルートが具体ルートを覆い隠します。

fastapi
from fastapi import FastAPI

app = FastAPI()

@app.get("/users/me")
def read_current_user():
    return {"user": "me"}

@app.get("/users/{user_id}")
def read_user(user_id: str):
    return {"user_id": user_id}

# /users/me MUST be declared before /users/{user_id}
# otherwise 'me' would match the {user_id} pattern

Enum のパスパラメータ

パスパラメータに Enum 型を使うと、定義済みの値に制限され、OpenAPI ドキュメントに enum スキーマが生成されます。値が文字列としてシリアライズされるよう (str, Enum) を継承しましょう。

fastapi
from enum import Enum
from fastapi import FastAPI

class ModelName(str, Enum):
    alexnet = "alexnet"
    resnet = "resnet"
    lenet = "lenet"

app = FastAPI()

@app.get("/models/{model_name}")
def get_model(model_name: ModelName):
    if model_name is ModelName.alexnet:
        return {"model": model_name, "layers": 5}
    return {"model": model_name}

# GET /models/resnet -> {"model": "resnet"}
03

クエリパラメータ

基本のクエリパラメータ

パスに含まれない関数のパラメータがクエリパラメータになります。デフォルトを与えると省略可能になり、クエリキーが無いときにデフォルトが使われます。

fastapi
from fastapi import FastAPI

app = FastAPI()

fake_items = [{"item": "a"}, {"item": "b"}, {"item": "c"}]

@app.get("/items")
def list_items(skip: int = 0, limit: int = 10):
    return fake_items[skip : skip + limit]

# GET /items?skip=0&limit=2
# GET /items                -> skip=0, limit=10

省略可能なクエリパラメータ

省略可能なクエリパラメータには Optional[str] = None(Python 3.10+ では str | None = None)を使いましょう。必須のパラメータは単にデフォルト値を持ちません。

fastapi
from typing import Optional
from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: str, q: Optional[str] = None):
    if q:
        return {"item_id": item_id, "q": q}
    return {"item_id": item_id}

# GET /items/1?q=hello
# GET /items/1            (q is None)

クエリのバリデーション

Query() がバリデーションを加えます:文字列には min_length/max_length、数値には ge/gt/le/lt、文字列の形式には pattern(正規表現)。制約を適用しつつ値を設定するには default= を使います。

fastapi
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/search")
def search(q: str = Query(min_length=3, max_length=50, pattern="^[a-zA-Z]+$")):
    return {"q": q}

@app.get("/page")
def page(limit: int = Query(default=10, ge=1, le=100)):
    return {"limit": limit}

真偽値の変換

Bool のクエリパラメータは多くの真値を受け付けます:true、1、yes、on(大文字小文字を区別しない)。それ以外は false と解釈されます。?active=maybe のような無効な型は 422 を返します。

fastapi
from fastapi import FastAPI

app = FastAPI()

@app.get("/flags")
def flags(active: bool = False):
    return {"active": active}

# GET /flags?active=true   -> {"active": true}
# GET /flags?active=1      -> {"active": true}
# GET /flags?active=yes    -> {"active": true}
# GET /flags?active=off    -> {"active": false}

リストのクエリパラメータ

List[str] のパラメータは、クエリ文字列で同じキーの繰り返しを受け付けます。デフォルトの空リストには Query(default=[])、欠落を許すには Query(default=None) を使いましょう。

fastapi
from typing import List
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items")
def list_items(q: List[str] = Query(default=[])):
    return {"q": q}

# GET /items?q=a&q=b&q=c  -> {"q": ["a", "b", "c"]}
# declare default=None to accept a list or null

必須のクエリパラメータ

バリデーションメタデータを持つ必須のクエリパラメータの宣言には Query(...)(Ellipsis)を使います。デフォルトがなく Query(...) もない素のアノテーション付きパラメータも必須になります。

fastapi
from fastapi import FastAPI, Query

app = FastAPI()

@app.get("/items")
def read_item(q: str = Query(...)):
    return {"q": q}

# GET /items?q=hello   -> ok
# GET /items           -> 422 (q is required)
# Query(...) (Ellipsis) marks a parameter as required
04

リクエストボディ(Pydantic)

BaseModel の基本

関数パラメータとして宣言された Pydantic の BaseModel が JSON リクエストボディになります。FastAPI がペイロードを検証し、型を変換し、無効なデータには 422 を返します。デフォルトを持つフィールドは省略可能です。

fastapi
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    in_stock: bool = True

app = FastAPI()

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

# POST /items  body: {"name": "Apple", "price": 0.5}
# -> {"name": "Apple", "price": 0.5, "in_stock": true}

フィールドタイプと制約

Field() がモデル属性に制約とメタデータを加えます:文字列には min_length/max_length、数値には gt/ge/lt/le、可変のデフォルトには default_factory。json_schema_extra 付きの model_config がドキュメントへ例を加えます。

fastapi
from pydantic import BaseModel, Field
from typing import Optional

class Item(BaseModel):
    name: str = Field(min_length=1, max_length=100)
    price: float = Field(gt=0, description="must be positive")
    tax: Optional[float] = None
    tags: list[str] = Field(default_factory=list)

    model_config = {
        "json_schema_extra": {
            "examples": [{"name": "Apple", "price": 0.5, "tags": ["fruit"]}]
        }
    }

ネストしたモデル

モデルはネストできます:別の BaseModel をフィールド型として宣言します。FastAPI はネストした構造全体を再帰的に検証し、生成された OpenAPI スキーマはネストしたオブジェクトを反映します。

fastapi
from pydantic import BaseModel
from typing import Optional

class Image(BaseModel):
    url: str
    name: str

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    image: Optional[Image] = None
    images: list[Image] = []

# valid body:
# {"name": "Phone", "image": {"url": "http://x/a.png", "name": "a"}}

フィールドのバリデーション

フィールドごとのカスタムバリデーションロジックには @field_validator(Pydantic v2)を使います。入力を拒否するには ValueError を発生させます(FastAPI がそれを 422 として表に出します)。値を保持するには(変換後の)値を返します。

fastapi
from pydantic import BaseModel, field_validator

class User(BaseModel):
    name: str
    email: str

    @field_validator("email")
    @classmethod
    def email_must_contain_at(cls, v: str) -> str:
        if "@" not in v:
            raise ValueError("must contain @")
        return v.lower()

    @field_validator("name")
    @classmethod
    def name_stripped(cls, v: str) -> str:
        return v.strip()

省略可能とデフォルトのフィールド

フィールドが必須になるのは、デフォルトがなく Optional でもないときだけです。省略可能な nullable フィールドの標準パターンは Optional[str] = None で、0.0 のような素のデフォルトはその値を持つ省略可能なフィールドになります。

fastapi
from pydantic import BaseModel
from typing import Optional

class Item(BaseModel):
    name: str                       # required
    description: Optional[str] = None  # optional, defaults to None
    price: float = 0.0              # optional, defaults to 0.0
    tags: list[str] = []            # optional, defaults to empty list

# All of these are valid:
# {"name": "X"}
# {"name": "X", "price": 9.99, "tags": ["a"]}

パス・クエリと共に使う Body

パス、クエリ、ボディのパラメータは 1 つの操作に共存できます。FastAPI の判断基準:パスにあればパスパラメータ、ボディは Pydantic モデル(または Body())、それ以外はクエリです。省略可能なボディにはデフォルト None が必要です。

fastapi
from fastapi import FastAPI, Path, Query
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

app = FastAPI()

@app.put("/items/{item_id}")
def update_item(
    item_id: int = Path(ge=1),
    q: Optional[str] = Query(default=None),
    item: Item = None,
):
    result = {"item_id": item_id, **item.model_dump()}
    if q:
        result["q"] = q
    return result
05

Response Model

response_model の基本

response_model は返却データをモデルで定義されたフィールドだけに絞り込みます — 余分なフィールドを持つオブジェクトを返してもです。パスワードのような機密フィールドを隠す標準的な方法です。

fastapi
from fastapi import FastAPI
from pydantic import BaseModel

class User(BaseModel):
    username: str
    email: str
    hashed_password: str

class UserOut(BaseModel):
    username: str
    email: str

app = FastAPI()

@app.get("/users/me", response_model=UserOut)
def read_user():
    return User(username="bob", email="[email protected]", hashed_password="secret")

# response: {"username": "bob", "email": "[email protected]"}  (no password)

フィールドの除外

response_model_include と response_model_exclude は、新しいモデルを定義せずにルートごとにフィールドをホワイト/ブラックリストできます。フィールド名のセットを渡します。これらは response_model に加えて適用されます。

fastapi
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    secret: str

app = FastAPI()

@app.get("/items/{id}", response_model=Item, response_model_exclude={"secret"})
def read_item(id: int):
    return {"name": "Apple", "price": 0.5, "secret": "hidden"}

@app.get("/items", response_model=list[Item], response_model_include={"name", "price"})
def list_items():
    return [{"name": "Apple", "price": 0.5, "secret": "x"}]

リストのレスポンス

エンドポイントがオブジェクトの配列を返すことを宣言するには response_model=list[Model](または List[Model])を使います。FastAPI がリストの各アイテムを検証・シリアライズします。

fastapi
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

app = FastAPI()

@app.get("/items", response_model=list[Item])
def list_items():
    return [
        {"name": "Apple", "price": 0.5},
        {"name": "Banana", "price": 0.3},
    ]

# response: [{"name": "Apple", "price": 0.5}, {"name": "Banana", "price": 0.3}]

未設定/デフォルトの除外

exclude_unset はクライアントが送らなかったフィールドを省きます(明示的に設定されたものだけが現れる)。exclude_defaults はデフォルトと等しいフィールドを省き、exclude_none は None のフィールドを省きます。疎なレスポンスに有用です。

fastapi
from fastapi import FastAPI
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str | None = None
    price: float = 0.0
    tax: float = 0.0

app = FastAPI()

@app.get("/items/{id}", response_model=Item, response_model_exclude_unset=True)
def read_item(id: int):
    return {"name": "Apple", "price": 0.5}
# -> {"name": "Apple", "price": 0.5}   (description, tax omitted)

# also: response_model_exclude_defaults=True
#       response_model_exclude_none=True

別名によるレスポンス

Field(alias=...) で、入力の JSON が Python 属性名と異なるキー名を使えます。response_model_by_alias=True で出力も別名を使います。populate_by_name=True なら入力で元の属性名も受け付けます。

fastapi
from fastapi import FastAPI
from pydantic import BaseModel, ConfigDict, Field

class Item(BaseModel):
    model_config = ConfigDict(populate_by_name=True)
    name: str = Field(alias="itemName")
    price: float

app = FastAPI()

@app.post("/items", response_model=Item, response_model_by_alias=True)
def create(item: Item):
    return item

# input:  {"itemName": "Apple", "price": 0.5}
# output: {"itemName": "Apple", "price": 0.5}

素の Dict のレスポンス

dict/list を返すと自動で JSON へシリアライズされます。デフォルトのレスポンス型を変えるには response_class を使います(HTMLResponse、PlainTextResponse)。完全な制御には Response のサブクラスを直接返します。

fastapi
from fastapi import FastAPI
from fastapi.responses import JSONResponse, PlainTextResponse

app = FastAPI()

@app.get("/dict")
def dict_resp():
    return {"a": 1, "b": 2}      # auto JSON

@app.get("/text", response_class=PlainTextResponse)
def text_resp():
    return "plain text response"

@app.get("/raw")
def raw_resp():
    return JSONResponse(content={"a": 1}, status_code=200)
06

フォームと UploadFile

フォームデータ

Form() は application/x-www-form-urlencoded か multipart のフォームデータからパースされるパラメータを宣言します。同じ操作で Form() と JSON ボディ(BaseModel)は混在できません — コンテンツタイプは 1 つ選びましょう。

fastapi
from fastapi import FastAPI, Form

app = FastAPI()

@app.post("/login")
def login(username: str = Form(), password: str = Form()):
    return {"username": username}

# Content-Type: application/x-www-form-urlencoded
# body: username=bob&password=secret

UploadFile の基本

UploadFile は .filename、.content_type、.read()、.write()、.close() を持つストリーミングのファイル表現です。async def 内では 'await file.read()' を使います。大きなファイルでは、すべてをメモリにロードしないために file.file(SpooledTemporaryFile)を推奨します。

fastapi
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    return {
        "filename": file.filename,
        "size": len(contents),
        "content_type": file.content_type,
    }

複数のファイル

list[UploadFile] を宣言すると、1 つのリクエストで複数のファイルを受け付けられます。各ファイルは同じフィールド名で送られます。リスト内のファイルの順序は送信順と一致します。

fastapi
from fastapi import FastAPI, UploadFile

app = FastAPI()

@app.post("/uploads")
async def upload_many(files: list[UploadFile]):
    return [
        {"filename": f.filename, "size": len(await f.read())}
        for f in files
    ]

# curl: curl -F "[email protected]" -F "[email protected]" http://localhost:8000/uploads

ファイルとフォームの併用

Form() と UploadFile(File())は同じエンドポイントで組み合わせられます — どちらも multipart/form-data を使うためです。ただし JSON の BaseModel ボディとは依然組み合わせられません。

fastapi
from fastapi import FastAPI, UploadFile, File, Form

app = FastAPI()

@app.post("/items")
async def create_item(
    name: str = Form(),
    description: str = Form(),
    file: UploadFile = File(),
):
    return {
        "name": name,
        "description": description,
        "file": file.filename,
    }

アップロードファイルの保存

小さなファイルには、shutil.copyfileobj が SpooledTemporaryFile を効率的にディスクへストリーミングします。非常に大きなファイルには、メモリを低く保つためチャンクで読み込みましょう(例:1MB)。パストラバーサルを避けるため、file.filename は必ず無害化しましょう。

fastapi
import shutil
from pathlib import Path
from fastapi import FastAPI, UploadFile

app = FastAPI()

@app.post("/save")
async def save_file(file: UploadFile):
    dest = Path("uploads") / file.filename
    dest.parent.mkdir(exist_ok=True)
    with dest.open("wb") as buf:
        shutil.copyfileobj(file.file, buf)
    return {"saved_to": str(dest)}

# async alternative for large files:
# async with dest.open("wb") as buf:
#     while chunk := await file.read(1024 * 1024):
#         buf.write(chunk)

ファイルのメタデータとサイズ

処理の前に file.content_type とサイズを検証しましょう。read() 後、カーソルは末尾にあります。もう一度読む必要があるなら 'await file.seek(0)' で巻き戻します。本物のタイプ検査は、ヘッダーだけでなくマジックバイトを検査すべきです。

fastapi
from fastapi import FastAPI, UploadFile, File

app = FastAPI()

@app.post("/validate")
async def validate(file: UploadFile = File(...)):
    # allowed types
    allowed = {"image/png", "image/jpeg"}
    if file.content_type not in allowed:
        return {"error": "unsupported type"}

    contents = await file.read()
    max_size = 5 * 1024 * 1024  # 5 MB
    if len(contents) > max_size:
        return {"error": "file too large"}

    await file.seek(0)  # rewind so later reads work
    return {"filename": file.filename, "size": len(contents)}
07

ヘッダーと Cookie

ヘッダーのパラメータ

Header() はリクエストヘッダーから読まれるパラメータを宣言します。FastAPI は Python 名のアンダースコアをハイフンへ変換します(x_token -> X-Token)。この挙動を無効化するには convert_underscores=False を設定します。

fastapi
from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/items")
def read_items(user_agent: str | None = Header(default=None)):
    return {"User-Agent": user_agent}

# Header names are case-insensitive; an underscore in the
# parameter (x_token) is converted to a hyphen (X-Token) automatically.
@app.get("/secure")
def secure(x_token: str = Header()):
    return {"x-token": x_token}

Cookie のパラメータ

Cookie() はリクエストの Cookie ヘッダーから値を読みます。クエリパラメータと同様、デフォルトのない Cookie は必須になり、バリデーション(min_length、max_length など)も適用できます。

fastapi
from fastapi import FastAPI, Cookie

app = FastAPI()

@app.get("/session")
def read_session(session_id: str | None = Cookie(default=None)):
    if session_id:
        return {"session_id": session_id}
    return {"message": "no session"}

# Reads the 'session_id' cookie from the Cookie header.

レスポンスへの Cookie 設定

Response を注入して set_cookie() を呼べば、外向きのレスポンスへ Cookie が書き込まれます。CSRF を緩和するには httponly=True(JS アクセスをブロック)、secure=True(HTTPS のみ)、samesite='lax'/'strict' を使いましょう。レスポンスボディは通常どおり返されます。

fastapi
from fastapi import FastAPI, Response

app = FastAPI()

@app.post("/login")
def login(response: Response):
    response.set_cookie(
        key="session_id",
        value="abc123",
        httponly=True,
        max_age=1800,
        secure=True,
        samesite="lax",
    )
    return {"message": "logged in"}

@app.post("/logout")
def logout(response: Response):
    response.delete_cookie("session_id")
    return {"message": "logged out"}

カスタムのレスポンスヘッダー

注入された Response にヘッダーを設定すれば、FastAPI が組み立てる JSON レスポンスに加わります。あるいは Response のサブクラスを返すときに headers= を渡します。カスタムヘッダーはレート制限情報や処理時間によく使われます。

fastapi
from fastapi import FastAPI, Response
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/data")
def get_data(response: Response):
    response.headers["X-Process-Time"] = "0.05"
    response.headers["X-Custom-Header"] = "hello"
    return {"data": 1}

@app.get("/direct")
def direct():
    return JSONResponse(
        content={"data": 1},
        headers={"X-Source": "direct"},
    )

標準ヘッダー

Host、Accept、Authorization、If-None-Match などのよくあるヘッダーは Header() 経由でアクセスできます。Authorization には、パースと OpenAPI ドキュメントを処理してくれる組み込みのセキュリティユーティリティ(HTTPBearer、OAuth2)を推奨します。

fastapi
from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/info")
def info(
    host: str | None = Header(default=None),
    accept: str | None = Header(default=None),
    authorization: str | None = Header(default=None),
    if_none_match: str | None = Header(default=None),
):
    return {"host": host, "accept": accept}

重複するヘッダー値

Header パラメータをリスト型で宣言すると、繰り返されたすべてのヘッダー値がリストへ収集されます。Set-Cookie(レスポンス)のようなヘッダーや、複数回現れ得る任意のカスタムヘッダーに有用です。

fastapi
from fastapi import FastAPI, Header

app = FastAPI()

@app.get("/multi")
def multi(x_token: list[str] | None = Header(default=None)):
    return {"x_token": x_token}

# Request with:
#   X-Token: a
#   X-Token: b
# -> {"x_token": ["a", "b"]}
08

依存性注入

基本の Depends

Depends() が関数の戻り値をパス操作へ注入します。共有ロジック(ページネーション、パース、DB セッション)は 1 箇所に置かれ、エンドポイント間で再利用されます。依存関係のパラメータも OpenAPI に文書化されます。

fastapi
from fastapi import FastAPI, Depends

app = FastAPI()

def common_params(q: str | None = None, skip: int = 0, limit: int = 10):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items")
def list_items(commons: dict = Depends(common_params)):
    return commons

@app.get("/users")
def list_users(commons: dict = Depends(common_params)):
    return commons

クラスの依存関係

__init__ を持つクラスは依存関係になれます。FastAPI が関数のように呼びます。Depends(CommonQueryParams) か、パラメータがそのクラスでアノテーションされている場合の省略形 Depends() を使いましょう。インスタンスが注入されます。

fastapi
from fastapi import FastAPI, Depends

class CommonQueryParams:
    def __init__(self, q: str | None = None, skip: int = 0, limit: int = 10):
        self.q = q
        self.skip = skip
        self.limit = limit

app = FastAPI()

@app.get("/items")
def list_items(commons: CommonQueryParams = Depends(CommonQueryParams)):
    return {"q": commons.q, "skip": commons.skip, "limit": commons.limit}

# shorthand: commons = Depends() infers the type

ネストした依存関係

依存関係は他の依存関係に依存でき、グラフを形成します。FastAPI がツリー全体を解決し、各結果をリクエストごとにキャッシュし、例外を伝播させます。階層化された認証(トークン → ユーザー → 権限)に最適です。

fastapi
from fastapi import FastAPI, Depends, Header, HTTPException

def get_token(authorization: str = Header()):
    if not authorization.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="invalid header")
    return authorization.removeprefix("Bearer ")

def get_current_user(token: str = Depends(get_token)):
    if token != "admin-token":
        raise HTTPException(status_code=403, detail="forbidden")
    return {"username": "admin"}

app = FastAPI()

@app.get("/me")
def me(user: dict = Depends(get_current_user)):
    return user

Yield 依存関係(後始末)

yield を使う依存関係のジェネレータは、後始末が必要なリソースに最適です:DB セッション、ファイルハンドル、トランザクション。yield 以降のコードはファイナライザとして動き、ルートが例外を投げても実行されます。依存関係の yield は 1 つだけにしましょう。

fastapi
from fastapi import FastAPI, Depends

def get_db():
    db = open_db_session()       # acquire resource
    try:
        yield db                 # injected into the route
    finally:
        db.close()               # always runs after the request

app = FastAPI()

@app.get("/items")
def list_items(db = Depends(get_db)):
    return db.query("SELECT * FROM items")

グローバル依存関係

FastAPI()(または APIRouter)に dependencies=[...] を渡すと、戻り値を注入せずにすべてのルートで強制されます。グローバルな認証、レート制限、リクエストロギングに有用です。

fastapi
from fastapi import FastAPI, Depends, Header, HTTPException

def verify_token(x_token: str = Header()):
    if x_token != "supersecret":
        raise HTTPException(status_code=400, detail="X-Token missing")

def verify_key(x_key: str = Header()):
    if x_key != "realkey":
        raise HTTPException(status_code=400, detail="X-Key missing")

# applied to every route in the app
app = FastAPI(dependencies=[Depends(verify_token), Depends(verify_key)])

@app.get("/items")
def list_items():
    return [{"item": "a"}]   # token & key already checked

ルートごとの依存関係

デコレータ(または APIRouter)に dependencies=[Depends(...)] を付けると、戻り値を使わずに特定のルートへ依存関係を要求できます。これでルートのシグネチャがきれいなまま、チェックが強制されます。

fastapi
from fastapi import FastAPI, Depends, Header, HTTPException

def verify_token(x_token: str = Header()):
    if x_token != "secret":
        raise HTTPException(status_code=401, detail="bad token")

app = FastAPI()

@app.get("/public")
def public():
    return {"open": True}

@app.get("/private", dependencies=[Depends(verify_token)])
def private():
    return {"secret": "data"}
09

セキュリティ(HTTPBasic / OAuth2 / JWT)

HTTP Basic 認証

HTTPBasic は Authorization: Basic ヘッダーを username/password へパースします。タイミング攻撃を防ぐため secrets.compare_digest(== ではない)を使いましょう。ブラウザに認証情報を求めさせるため、常に WWW-Authenticate: Basic 付きの 401 を返しましょう。

fastapi
import secrets
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials

security = HTTPBasic()
app = FastAPI()

def get_current_user(credentials: HTTPBasicCredentials = Depends(security)):
    correct_user = secrets.compare_digest(credentials.username, "admin")
    correct_pass = secrets.compare_digest(credentials.password, "secret")
    if not (correct_user and correct_pass):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid credentials",
            headers={"WWW-Authenticate": "Basic"},
        )
    return credentials.username

@app.get("/profile")
def profile(user: str = Depends(get_current_user)):
    return {"user": user}

OAuth2 Password Bearer

OAuth2PasswordBearer はルートが Bearer トークンを期待することを宣言し、依存関係が Authorization ヘッダーからトークンを取り出します。tokenUrl が、ドキュメント UI が認証情報を送る場所を伝えます。トークン自体は、検証するまでは単なる文字列です。

fastapi
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordBearer

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
app = FastAPI()

@app.get("/me")
def me(token: str = Depends(oauth2_scheme)):
    return {"token": token}

# client POSTs username+password to /token, receives an access token,
# then sends it as: Authorization: Bearer <token>

JWT トークンの作成

トークンの署名には python-jose(または PyJWT)を使います。慣例として 'sub'(subject)クレームがユーザー名かユーザー ID を保持し、'exp' が有効期限を設定します。SECRET_KEY は長くランダムに、環境から読み込みましょう — コミットしてはいけません。

fastapi
from datetime import datetime, timedelta, timezone
from jose import jwt

SECRET_KEY = "keep-this-secret"
ALGORITHM = "HS256"

def create_access_token(data: dict, expires_minutes: int = 30) -> str:
    to_encode = data.copy()
    expire = datetime.now(timezone.utc) + timedelta(minutes=expires_minutes)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

# token = create_access_token({"sub": "alice"})
# -> eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

JWT トークンのデコード

jwt.decode は署名と 'exp' クレームを自動的に検証し、失敗すると JWTError を発生させます。クライアントが有効なトークンを提供するよう知るため、依存関係を WWW-Authenticate: Bearer 付きの 401 へマッピングしましょう。

fastapi
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
SECRET_KEY = "keep-this-secret"
ALGORITHM = "HS256"

def get_current_user(token: str = Depends(oauth2_scheme)) -> str:
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username: str | None = payload.get("sub")
        if username is None:
            raise credentials_exception
        return username
    except JWTError:
        raise credentials_exception

credentials_exception = HTTPException(
    status_code=status.HTTP_401_UNAUTHORIZED,
    detail="Could not validate credentials",
    headers={"WWW-Authenticate": "Bearer"},
)

パスワードのハッシュ化

平文のパスワードを保存してはいけません。bcrypt(または argon2)を使う passlib がソルトとハッシュ化を処理します。verify() が平文の入力を保存されたハッシュと比較します。bcrypt バックエンドの取得には pip install passlib[bcrypt] です。

fastapi
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def hash_password(plain: str) -> str:
    return pwd_context.hash(plain)

def verify_password(plain: str, hashed: str) -> bool:
    return pwd_context.verify(plain, hashed)

# usage when issuing tokens:
def authenticate_user(username: str, password: str):
    user = fake_db.get(username)
    if not user or not verify_password(password, user.hashed_password):
        return False
    return user

OAuth2 ログインフロー

OAuth2PasswordRequestForm は、フォームエンコードされた POST(標準の OAuth2 パスワードフロー)から username/password を読みます。access_token と token_type: 'bearer' を返しましょう。このエンドポイントが、OAuth2PasswordBearer の tokenUrl が指す場所です。

fastapi
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm

app = FastAPI()

@app.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(form.username, form.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
        )
    token = create_access_token({"sub": user.username})
    return {"access_token": token, "token_type": "bearer"}

# OAuth2PasswordRequestForm parses username+password from form data
# and powers the 'Authorize' button in the Swagger UI.
10

ミドルウェア

ミドルウェアの追加

@app.middleware('http') がすべてのリクエストを包む関数を登録します。レスポンスを得るには await call_next(request) しなければならず、その後、返す前に検査や修正ができます。ミドルウェアはすべてのルートで動きます。

fastapi
import time
from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_process_time(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    duration = time.perf_counter() - start
    response.headers["X-Process-Time"] = f"{duration:.4f}"
    return response

カスタムヘッダーのミドルウェア

すべてのレスポンスに付けるべきヘッダー(セキュリティヘッダー、サーバーバナー、トレーシング ID)はミドルウェアが適切な場所です。call_next を await した後にレスポンスオブジェクトを書き換えましょう。

fastapi
from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_banner(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Powered-By"] = "FastAPI"
    response.headers["X-Frame-Options"] = "DENY"
    return response

# every response now carries these headers

BaseHTTPMiddleware

再利用可能で設定可能なミドルウェアには、BaseHTTPMiddleware を継承し app.add_middleware(MyMiddleware, **options) で登録しましょう。組み込みの CORS、GZip、TrustedHost ミドルウェアもこの方法で追加されます。

fastapi
from starlette.middleware.base import BaseHTTPMiddleware
from fastapi import FastAPI, Request

class TimingMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        start = time.perf_counter()
        response = await call_next(request)
        response.headers["X-Duration"] = str(time.perf_counter() - start)
        return response

app = FastAPI()
app.add_middleware(TimingMiddleware)

# class-based middleware is reusable and configurable

HTTPS リダイレクト

HTTPSRedirectMiddleware は、HTTP のリクエストすべてを HTTPS 版へ 308 リダイレクトします。TLS を終端するロードバランサーの後ろで使えば、クライアントが安全な接続へアップグレードすることが保証されます。

fastapi
from fastapi import FastAPI
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware

app = FastAPI()
app.add_middleware(HTTPSRedirectMiddleware)

# all HTTP requests are redirected to HTTPS (308)

Trusted Host

TrustedHostMiddleware は Host ヘッダーが許可リストにないリクエストを拒否し、Host ヘッダーインジェクション攻撃を防ぎます。'*.example.com' のようなワイルドカードに対応しています。ローカル開発のため 'localhost' は常に含めましょう。

fastapi
from fastapi import FastAPI
from fastapi.middleware.trustedhost import TrustedHostMiddleware

app = FastAPI()
app.add_middleware(
    TrustedHostMiddleware,
    allowed_hosts=["example.com", "*.example.com", "localhost"],
)

# requests with a disallowed Host header get a 400 response

ミドルウェアの順序

Starlette は入ってくるリクエストに対してミドルウェアを LIFO で実行します:最後に追加されたものが最初に動きます。CORS は早めに(プリフライトが機能するように)加え、GZip はその後に。あるミドルウェアが設定したヘッダーが別のミドルウェアから見えない理由のデバッグ時に思い出しましょう。

fastapi
from fastapi import FastAPI
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# Middleware runs in REVERSE order of registration for requests,
# and in registration order for responses.
app.add_middleware(GZipMiddleware, minimum_size=1000)
app.add_middleware(CORSMiddleware, allow_origins=["*"])

# request flow:  CORS -> GZip -> route
# response flow: route -> GZip -> CORS
11

CORS

CORSMiddleware の設定

CORSMiddleware が CORS プリフライト(OPTIONS)を処理し、Access-Control-* ヘッダーを加えます。allow_origins には許可する正確なオリジンを列挙しましょう。本番では ['*'] ではなく具体的な URL のリストを使います。

fastapi
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://example.com", "https://www.example.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/api/data")
def data():
    return {"data": 1}

全オリジン許可(開発専用)

allow_origins=['*'] は任意のオリジンを許しますが、allow_credentials=True とは組み合わせられません(ブラウザが拒否します)。これは開発中の完全に公開された API だけに使い、本番では実際のオリジンを列挙しましょう。

fastapi
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
    # allow_credentials=True CANNOT be combined with allow_origins=["*"]
)

資格情報の許可

allow_credentials=True で、ブラウザがクロスオリジンで Cookie と Authorization ヘッダーを送れるようになります。具体的なオリジンが必須です(決して '*' ではない)。ブラウザがレスポンスに Access-Control-Allow-Credentials: true を設定します。

fastapi
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_credentials=True,    # send cookies / Authorization
    allow_methods=["GET", "POST"],
    allow_headers=["Authorization", "Content-Type"],
)

# needed when the frontend sends cookies or credentials with requests

許可メソッドとヘッダー

allow_methods/allow_headers がブラウザが送れるものを制限します。expose_headers は、フロントエンドの JavaScript が読めるレスポンスヘッダーを列挙します(そうしないとブラウザがカスタムヘッダーを隠します)。プリフライトレスポンスはブラウザがキャッシュします。

fastapi
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type", "X-Request-ID"],
    expose_headers=["X-Total-Count", "X-Process-Time"],
)

# expose_headers lets the frontend JS read these response headers

プリフライトリクエスト

「単純でない」リクエスト(カスタムヘッダー、PUT/DELETE、JSON コンテンツタイプなど)では、ブラウザが OPTIONS のプリフライトを送ります。CORSMiddleware が OPTIONS を横取りし、許可されたメソッド/ヘッダーで応答します。max_age がブラウザがその答えをキャッシュする時間を制御します。

fastapi
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com"],
    allow_methods=["*"],
    allow_headers=["*"],
    max_age=600,   # browser caches preflight result for 600s
)

# Browser sends OPTIONS preflight for non-simple requests;
# CORSMiddleware answers automatically with the right headers.

動的なオリジン検証

動的な許可リストには、静的リストの代わりに allow_origin_regex(リクエストの Origin に照合)を使いましょう。有効なオリジンがパターンに従うとき(example.com の任意のサブドメインなど)に便利です。

fastapi
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

VALID_DOMAINS = {"example.com", "staging.example.com"}

def origin_check(origin: str) -> str | None:
    if origin and origin.replace("https://", "").replace("http://", "") in VALID_DOMAINS:
        return origin
    return None

app.add_middleware(
    CORSMiddleware,
    allow_origin_regex=r"https://.*\.example\.com",
    allow_methods=["*"],
    allow_headers=["*"],
)
12

例外処理

HTTPException の発生

ルートや依存関係のどこでも raise HTTPException すれば短絡してエラーレスポンスを返せます。detail は文字列、辞書、リストにできます — JSON の 'detail' フィールドになります。headers で省略可能にレスポンスヘッダーを加えられます。

fastapi
from fastapi import FastAPI, HTTPException, status

app = FastAPI()

items = {1: "Apple", 2: "Banana"}

@app.get("/items/{item_id}")
def read_item(item_id: int):
    if item_id not in items:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Item not found",
            headers={"X-Error": "missing"},
        )
    return {"item": items[item_id]}

カスタム例外

@app.exception_handler(MyException) でハンドラを登録すると、任意のカスタム例外を HTTP レスポンスへ変換できます。ハンドラはリクエストと例外を受け取ります。アプリのドメインエラーの整形を一元化できます。

fastapi
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

class UnicornException(Exception):
    def __init__(self, name: str):
        self.name = name

app = FastAPI()

@app.exception_handler(UnicornException)
async def unicorn_handler(request: Request, exc: UnicornException):
    return JSONResponse(
        status_code=418,
        content={"message": f"Oops, {exc.name} did it again"},
    )

@app.get("/unicorns/{name}")
def read_unicorn(name: str):
    if name == "yolo":
        raise UnicornException(name=name)
    return {"name": name}

検証エラーの上書き

RequestValidationError は入力が Pydantic の検証に失敗したときに発生します。@app.exception_handler(RequestValidationError) でハンドラを上書きし、422 レスポンスの形状をカスタマイズしましょう(会社全体のエラーエンベロープに合わせるなど)。

fastapi
from fastapi import FastAPI, Request, status
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def validation_handler(request: Request, exc: RequestValidationError):
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content={
            "success": False,
            "errors": exc.errors(),
            "body": exc.body,
        },
    )

HTTPException ハンドラの上書き

デフォルトの HTTPException ハンドラを上書きすれば、発生するすべての HTTPException で一貫したエラー JSON 形状が強制されます。ハンドラを再束縛するときは、クラスを fastapi.exceptions.HTTPException(raise で使うものと同じ)としてインポートしましょう。

fastapi
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.exceptions import HTTPException as FastAPIHTTPException

app = FastAPI()

@app.exception_handler(FastAPIHTTPException)
async def custom_http_handler(request, exc: FastAPIHTTPException):
    return JSONResponse(
        status_code=exc.status_code,
        content={
            "success": False,
            "status": exc.status_code,
            "message": exc.detail,
        },
        headers=exc.headers,
    )

よく使うステータスコード

status モジュールがすべての HTTP ステータスコードの名前付き定数を提供し、マジックナンバーを避けられます。FastAPI アプリで最もよくあるのは 200(GET のデフォルト)、201(作成)、204(コンテンツなし)、422(検証)です。

fastapi
from fastapi import FastAPI, status

app = FastAPI()

@app.get("/ok", status_code=status.HTTP_200_OK)
def ok(): return {"ok": True}

@app.post("/create", status_code=status.HTTP_201_CREATED)
def create(): return {"id": 1}

@app.get("/no-content", status_code=status.HTTP_204_NO_CONTENT)
def no_content(): return None

@app.get("/not-found")
def missing():
    # raise HTTPException(status.HTTP_404_NOT_FOUND, "nope")
    ...

# Other common: 400 BAD_REQUEST, 401 UNAUTHORIZED,
# 403 FORBIDDEN, 409 CONFLICT, 422 UNPROCESSABLE_ENTITY, 500 INTERNAL_SERVER_ERROR

汎用例外ハンドラ

基底の Exception に対するハンドラを登録すると、まだ処理されていないものをすべて捉え、スタックトレースがクライアントへ漏れるのを防ぎます。完全なトレースバックはサーバー側で必ず記録し、クライアントには汎用的な 500 を返しましょう。

fastapi
import logging
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

logger = logging.getLogger("uvicorn.error")
app = FastAPI()

@app.exception_handler(Exception)
async def unhandled(request: Request, exc: Exception):
    logger.exception("Unhandled error on %s", request.url.path)
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal Server Error"},
    )

@app.get("/boom")
def boom():
    raise RuntimeError("something exploded")
13

バックグラウンドタスク

基本の BackgroundTasks

BackgroundTasks はレスポンス送信後に関数を実行します — ロギング、メール送信、キャッシュ無効化のような発火後放置の作業に最適です。add_task が関数(と引数)を、レスポンスをブロックせずにスケジュールします。

fastapi
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(message: str):
    with open("log.txt", "a") as f:
        f.write(message + "\n")

@app.post("/send")
def send_notification(background_tasks: BackgroundTasks):
    background_tasks.add_task(write_log, "notification sent")
    return {"message": "notification queued"}

複数のタスク

タスクはいくつでも追加できます。追加された順に、レスポンスが返された後に逐次実行されます。同じプロセスで動くため、速くノンブロッキングに保つか、本物のキュー(Celery、RQ、Dramatiq)へ移しましょう。

fastapi
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def send_email(to: str, subject: str): ...
def update_cache(key: str): ...
def notify_slack(msg: str): ...

@app.post("/signup")
def signup(background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email, "[email protected]", "Welcome")
    background_tasks.add_task(update_cache, "user_count")
    background_tasks.add_task(notify_slack, "new signup")
    return {"status": "ok"}

依存関係付きのタスク

BackgroundTasks は他の依存関係と同じように注入されます。タスク関数は、リクエスト時に取り込まれた値(DB セッションなど)を受け取れます。タスクはリクエストライフサイクルのスコープ内で動くため、依存関係から得られた/yield されたリソースはタスク終了後に閉じることに注意しましょう。

fastapi
from fastapi import FastAPI, BackgroundTasks, Depends

app = FastAPI()

def get_db_session():
    db = "session"
    yield db

def write_log(db, message: str):
    print(db, message)

@app.get("/items")
def list_items(background_tasks: BackgroundTasks, db = Depends(get_db_session)):
    background_tasks.add_task(write_log, db, "list called")
    return {"items": []}

非同期タスク関数

バックグラウンドタスクの関数は、同期(スレッドプールで実行)でも非同期(イベントループで await)でも構いません。非同期ライブラリを自身で使う I/O バウンドの作業には非同期タスクを、CPU/ブロッキング作業には同期タスクを使いましょう。

fastapi
from fastapi import FastAPI, BackgroundTasks
import httpx

app = FastAPI()

async def fetch_url(url: str):
    async with httpx.AsyncClient() as client:
        r = await client.get(url)
        return r.status_code

@app.post("/webhook")
def webhook(url: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(fetch_url, url)
    return {"queued": url}

Background と Celery の使い分け

BackgroundTasks は、再起動で失われても問題ない軽量で非重要な作業に使いましょう。クラッシュに耐え、再試行し、マシンをまたいでスケールすべきジョブには、Redis や RabbitMQ のようなブローカーと共に本物のタスクキュー(Celery、RQ、Dramatiq、Arq)を使います。

fastapi
# BackgroundTasks: in-process, no broker, lost if process crashes
@app.post("/quick")
def quick(tasks: BackgroundTasks):
    tasks.add_task(small_job)
    return {"ok": True}

# Celery/RQ/Dramatiq: separate workers, persistent, retryable
# from celery import Celery
# @celery.task
# def big_job(payload): ...
#
# @app.post("/heavy")
# def heavy(payload: dict):
#     big_job.delay(payload)
#     return {"queued": True}

メール送信の例

メール送信は BackgroundTasks の定番のユースケースです:遅く、ユーザーは待つべきではありません。レスポンスは即座に返り、メールはその後に送られます。大量送信には、再試行付きのキューとメールサービスの SDK を推奨します。

fastapi
from fastapi import FastAPI, BackgroundTasks
from pydantic import BaseModel, EmailStr

class Message(BaseModel):
    to: EmailStr
    subject: str
    body: str

app = FastAPI()

def send_email(to: str, subject: str, body: str):
    # smtplib or your provider's SDK
    import smtplib
    with smtplib.SMTP("localhost") as s:
        s.sendmail("[email protected]", to, f"Subject: {subject}\n\n{body}")

@app.post("/contact")
def contact(msg: Message, tasks: BackgroundTasks):
    tasks.add_task(send_email, msg.to, msg.subject, msg.body)
    return {"status": "queued", "to": msg.to}
14

WebSocket

WebSocket の基本

WebSocket のエンドポイントには @app.websocket() を使います。送受信の前に accept() で接続を受け入れなければなりません。関数は通常、メッセージを読むループになります。receive_text/receive_bytes/receive_json はすべてクライアントからデータを await します。

fastapi
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
    await ws.accept()
    while True:
        data = await ws.receive_text()
        await ws.send_text(f"echo: {data}")

# client (browser):
# const ws = new WebSocket("ws://localhost:8000/ws");
# ws.onmessage = (e) => console.log(e.data);

JSON の送信

send_json() と receive_json() がシリアライズを処理し、ソケット上で JSON オブジェクトを交換します。バイナリデータには send_bytes/receive_bytes を使いましょう。各 send/receive が WebSocket 上の独立したフレームです。

fastapi
import json
from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def ws_endpoint(ws: WebSocket):
    await ws.accept()
    while True:
        msg = await ws.receive_json()
        await ws.send_json({"reply": msg.get("text", "").upper()})

# send_text / send_bytes / send_json helpers are available

WebSocket の切断

クライアントが接続を閉じると WebSocketDisconnect が発生します — 後始末のため捉えましょう。通常の切断には ws.close(code=1000) を呼びます。よくあるコード:1000(通常)、1008(ポリシー違反)、1011(サーバーエラー)。

fastapi
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

app = FastAPI()

@app.websocket("/ws")
async def ws_endpoint(ws: WebSocket):
    await ws.accept()
    try:
        while True:
            data = await ws.receive_text()
            if data == "quit":
                await ws.close(code=1000)
                break
            await ws.send_text(data)
    except WebSocketDisconnect:
        print("client disconnected")

コネクションマネージャー

ConnectionManager がアクティブなソケットを追跡し、接続中の全クライアントへブロードキャストできます(チャットルームなど)。閉じた接続への送信を避け、メモリを有限に保つため、切断時には必ずソケットを取り除きましょう。

fastapi
from fastapi import FastAPI, WebSocket, WebSocketDisconnect

class ConnectionManager:
    def __init__(self):
        self.active: list[WebSocket] = []

    async def connect(self, ws: WebSocket):
        await ws.accept()
        self.active.append(ws)

    def disconnect(self, ws: WebSocket):
        self.active.remove(ws)

    async def broadcast(self, message: str):
        for ws in self.active:
            await ws.send_text(message)

manager = ConnectionManager()
app = FastAPI()

@app.websocket("/chat")
async def chat(ws: WebSocket):
    await manager.connect(ws)
    try:
        while True:
            msg = await ws.receive_text()
            await manager.broadcast(msg)
    except WebSocketDisconnect:
        manager.disconnect(ws)

クエリパラメータ経由の WebSocket 認証

ブラウザは WebSocket 接続にカスタムヘッダーを設定できないため、認証トークンは通常クエリパラメータ(または Cookie)で渡されます。accept() を呼ぶ前に検証し、未認証ならコード 1008(ポリシー違反)で閉じましょう。

fastapi
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, HTTPException

app = FastAPI()

async def authenticate(token: str) -> str:
    if token != "secret":
        raise HTTPException(status_code=401)
    return "alice"

@app.websocket("/ws")
async def ws_endpoint(ws: WebSocket):
    token = ws.query_params.get("token")
    if not token:
        await ws.close(code=1008)
        return
    user = await authenticate(token)
    await ws.accept()
    try:
        while True:
            data = await ws.receive_text()
            await ws.send_text(f"{user}: {data}")
    except WebSocketDisconnect:
        pass

依存関係付き WebSocket

依存関係は、HTTP ルートと同様に WebSocket エンドポイントでも使えますが、意味があるのは初期ハンドシェイク(ヘッダー、クエリパラメータ、Cookie)から読む依存関係だけです — ボディはありません。通常どおり Depends() 経由で注入します。

fastapi
from fastapi import FastAPI, WebSocket, Depends, Header

app = FastAPI()

def token_validator(token: str = Header(default="")):
    # for WS, headers come from the initial HTTP handshake
    return token == "valid"

@app.websocket("/ws")
async def ws_endpoint(ws: WebSocket, valid: bool = Depends(token_validator)):
    if not valid:
        await ws.close(code=1008)
        return
    await ws.accept()
    while True:
        msg = await ws.receive_text()
        await ws.send_text(msg)
15

データベース(SQLAlchemy)

SQLAlchemy のセットアップ

create_engine が DB 接続プールを用意し、SessionLocal がセッションのファクトリで、Base がモデルの宣言的基底クラスです。FastAPI での SQLite では、リクエストが別スレッドで動き得るため check_same_thread=False を設定しましょう。

fastapi
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base

SQLALCHEMY_DATABASE_URL = "sqlite:///./app.db"
# postgresql: "postgresql://user:pass@localhost:5432/dbname"

engine = create_engine(
    SQLALCHEMY_DATABASE_URL,
    connect_args={"check_same_thread": False},  # sqlite only
)
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
Base = declarative_base()

セッションの依存関係

DB セッションを提供する正統な方法は yield 依存関係です:各リクエストが新しいセッションを受け取り、finally ブロックで閉じられます。ルートが例外を投げても後始末が保証されます。

fastapi
from fastapi import Depends
from sqlalchemy.orm import Session

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

@app.get("/items")
def list_items(db: Session = Depends(get_db)):
    return db.query(Item).all()

# each request gets its own session, closed automatically afterward

モデル定義

テーブルは Base を継承する SQLAlchemy ORM モデルとして定義します。本番のスキーマ移行には create_all() ではなく Alembic を使いましょう。列はインデックス、nullable、DB か Python レベルのデフォルトを持てます。

fastapi
from sqlalchemy import Column, Integer, String, Boolean
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class Item(Base):
    __tablename__ = "items"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True, nullable=False)
    price = Column(Integer, default=0)
    in_stock = Column(Boolean, default=True)

# create tables (for dev; use Alembic migrations in prod)
Base.metadata.create_all(bind=engine)

レコードの作成

add() が新しい行をステージングし、commit() が DB へ書き込み、refresh() がサーバー生成の値(自動増分の id など)でインスタンスを再読み込みします。複数の書き込みはトランザクションで包み、最後に 1 回 commit しましょう。

fastapi
from fastapi import FastAPI, Depends
from sqlalchemy.orm import Session

app = FastAPI()

@app.post("/items", status_code=201)
def create_item(payload: ItemCreate, db: Session = Depends(get_db)):
    item = Item(name=payload.name, price=payload.price)
    db.add(item)
    db.commit()
    db.refresh(item)        # load generated id
    return item

レコードのクエリ

db.query(Model) がクエリを開始し、.filter() が WHERE 条件を適用し、.offset()/.limit() がページネーションし、.first() が 1 行か None を返し、.all() がリストを返します。単純な等価条件には .filter_by(name=x) を使います。

fastapi
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

app = FastAPI()

@app.get("/items")
def list_items(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    return db.query(Item).offset(skip).limit(limit).all()

@app.get("/items/{item_id}")
def get_item(item_id: int, db: Session = Depends(get_db)):
    item = db.query(Item).filter(Item.id == item_id).first()
    if not item:
        raise HTTPException(status_code=404, detail="not found")
    return item

更新と削除

部分的な更新には、提供されたフィールドだけが変わるよう model_dump(exclude_unset=True) を反復します。delete() が削除をステージングし、commit() が確定します。DELETE の成功には 204 No Content を返しましょう。

fastapi
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

app = FastAPI()

@app.put("/items/{item_id}")
def update_item(item_id: int, payload: ItemUpdate, db: Session = Depends(get_db)):
    item = db.query(Item).filter(Item.id == item_id).first()
    if not item:
        raise HTTPException(status_code=404, detail="not found")
    for k, v in payload.model_dump(exclude_unset=True).items():
        setattr(item, k, v)
    db.commit()
    db.refresh(item)
    return item

@app.delete("/items/{item_id}", status_code=204)
def delete_item(item_id: int, db: Session = Depends(get_db)):
    item = db.query(Item).filter(Item.id == item_id).first()
    if item:
        db.delete(item)
        db.commit()
16

データベース(Tortoise ORM)

Tortoise のセットアップ

Tortoise ORM は非同期ネイティブで、FastAPI と相性が良いです。起動時に db_url と、モデルを含むモジュールで初期化します。dev では generate_schemas() で十分です。本番の移行には Aerich を使いましょう。新しいコードでは on_event の代わりに lifespan ハンドラを使います。

fastapi
from fastapi import FastAPI
from tortoise import Tortoise

app = FastAPI()

async def init():
    await Tortoise.init(
        db_url="sqlite://db.sqlite3",
        modules={"models": ["app.models"]},
    )
    await Tortoise.generate_schemas()

@app.on_event("startup")
async def startup():
    await init()

@app.on_event("shutdown")
async def shutdown():
    await Tortoise.close_connections()

モデル定義

Tortoise のモデルは Model を継承し、tortoise.fields 経由でフィールドを宣言します。フィールドタイプが DB の列タイプへ対応します。テーブル名は内側の Meta クラスで設定します。リレーションは ForeignKeyField、ManyToManyField などを使います。

fastapi
from tortoise import fields
from tortoise.models import Model

class Item(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=100)
    price = fields.FloatField(default=0.0)
    created_at = fields.DatetimeField(auto_now_add=True)

    class Meta:
        table = "items"

    def __str__(self):
        return self.name

レコードの作成

Item.create() は挿入して新しい行を返すコルーチンです。Pydantic のレスポンスを返すには、from_tortoise_orm()(tortoise.contrib.pydantic 経由)で BaseModel を組み立てましょう — Tortoise が非同期でロードしたリレーションを正しくシリアライズします。

fastapi
from fastapi import FastAPI
from pydantic import BaseModel
from .models import Item

app = FastAPI()

class ItemIn(BaseModel):
    name: str
    price: float

@app.post("/items", response_model=ItemOut, status_code=201)
async def create_item(payload: ItemIn):
    item = await Item.create(name=payload.name, price=payload.price)
    return await ItemOut.from_tortoise_orm(item)

非同期クエリ

Tortoise のクエリは await されます:.all() がクエリセットを返し、.filter() が条件を加え、.get_or_none() が 1 行か None を取得し、.first() が最初の一致を返します。.get() はちょうど 1 行を期待する場合だけにしましょう(見つからないと発生します)。

fastapi
from fastapi import FastAPI, HTTPException
from .models import Item

app = FastAPI()

@app.get("/items")
async def list_items(skip: int = 0, limit: int = 10):
    return await Item.all().offset(skip).limit(limit)

@app.get("/items/{item_id}")
async def get_item(item_id: int):
    item = await Item.get_or_none(id=item_id)
    if not item:
        raise HTTPException(status_code=404, detail="not found")
    return item

更新と削除

モデル属性を変更して await save() すれば行が更新され、一括更新には await Item.filter(id=...).update(name=x) を使います。await item.delete() が行を削除します。各メソッドはコルーチンであり、await する必要があります。

fastapi
from fastapi import FastAPI, HTTPException
from .models import Item

app = FastAPI()

@app.put("/items/{item_id}")
async def update_item(item_id: int, name: str):
    item = await Item.get_or_none(id=item_id)
    if not item:
        raise HTTPException(status_code=404, detail="not found")
    item.name = name
    await item.save()
    return item

@app.delete("/items/{item_id}", status_code=204)
async def delete_item(item_id: int):
    item = await Item.get_or_none(id=item_id)
    if item:
        await item.delete()

Tortoise の Pydantic スキーマ

tortoise.contrib.pydantic が Tortoise モデルから直接 Pydantic モデルを生成するため、2 つのスキーマを維持する必要がありません。単一オブジェクトには pydantic_model_creator を、リストレスポンスには pydantic_queryset_creator を使いましょう。

fastapi
from tortoise.contrib.pydantic import pydantic_model_creator, pydantic_queryset_creator
from .models import Item

ItemOut = pydantic_model_creator(Item, name="ItemOut")
ItemList = pydantic_queryset_creator(Item)

@app.get("/items", response_model=ItemList)
async def list_items():
    return await Item.all()

# auto-generates a Pydantic model from the Tortoise model,
# including types and docstrings.
17

テスト(TestClient)

TestClient の基本

TestClient がアプリを包み、プロセス内でリクエストを送れます(実ソケットなし)。httpx ベースで、pytest とそのまま動きます。本番で実行しているのと同じ app インスタンスをインポートしましょう。

fastapi
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

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

# TestClient is based on httpx; no network is involved —
# it calls the ASGI app directly in-process.

GET と POST のテスト

JSON ボディには json=、クエリパラメータには params=、ヘッダーには headers=、マルチパートのアップロードには files= を渡します。検証の失敗は 422 を返します — status_code とエラーの 'detail' の構造を assert しましょう。

fastapi
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_create_item():
    response = client.post(
        "/items",
        json={"name": "Apple", "price": 0.5},
    )
    assert response.status_code == 201
    assert response.json()["name"] == "Apple"

def test_validation_error():
    response = client.post("/items", json={"name": "Apple"})  # missing price
    assert response.status_code == 422

Pytest の Fixture

TestClient を返す pytest の fixture がテストを DRY にし、各テストが新しいクライアントを得られます。DB ベースのテストでは、テーブルを作成/削除するか、テストごとにトランザクションのロールバックを使う fixture を加えて、隔離を保ちましょう。

fastapi
import pytest
from fastapi.testclient import TestClient
from main import app

@pytest.fixture
def client():
    return TestClient(app)

def test_read(client):
    r = client.get("/items")
    assert r.status_code == 200

def test_create(client):
    r = client.post("/items", json={"name": "X"})
    assert r.status_code == 201

# run: pytest -v

依存関係のオーバーライド

app.dependency_overrides が、テスト中の依存関係(本物の DB セッションや認証など)をモック/フェイクへ差し替えます。ルートを変えずに。これが、外部サービスから分離してエンドポイントをテストする正統な方法です。テスト後にはクリアしましょう。

fastapi
from fastapi.testclient import TestClient
from main import app, get_db

def get_test_db():
    # return a test session or mock
    yield FakeSession()

app.dependency_overrides[get_db] = get_test_db

client = TestClient(app)

def test_items():
    r = client.get("/items")
    assert r.status_code == 200

# restore afterwards:
app.dependency_overrides.clear()

認証のテスト

OAuth2PasswordRequestForm はフォームエンコードされたデータを期待します(json= ではなく data=)。後続の保護されたリクエストでは、返されたトークンを Authorization: Bearer ヘッダーで使います。認証を完全にバイパスしたいなら、代わりに get_current_user の依存関係をオーバーライドしましょう。

fastapi
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def get_token():
    r = client.post(
        "/token",
        data={"username": "admin", "password": "secret"},
    )
    return r.json()["access_token"]

def test_protected():
    token = get_token()
    r = client.get(
        "/me",
        headers={"Authorization": f"Bearer {token}"},
    )
    assert r.status_code == 200
    assert r.json()["username"] == "admin"

WebSocket のテスト

TestClient.websocket_connect() がコンテキストマネージャー内で WebSocket を開きます。メッセージの交換には send_text/receive_text(と json/bytes 版)を使いましょう。閉じた接続での受信は WebSocketDisconnect を発生させます。

fastapi
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_websocket():
    with client.websocket_connect("/ws") as ws:
        ws.send_text("hello")
        data = ws.receive_text()
        assert data == "echo: hello"

def test_websocket_close():
    with client.websocket_connect("/ws") as ws:
        ws.send_text("quit")
        # the server closes the connection
18

OpenAPI ドキュメント

Swagger UI

FastAPI は、ルート、型、docstring から /docs でインタラクティブな Swagger UI を自動生成します。アプリに title/description/version を設定し、UI を充実させるため各ルートに docstring か summary/description を加えましょう。

fastapi
from fastapi import FastAPI

app = FastAPI(
    title="My API",
    description="Sample API with auto docs",
    version="1.0.0",
)

@app.get("/items", summary="List items", description="Returns all items")
def list_items():
    """Get every item in the catalog."""
    return [{"id": 1}]

# interactive docs at: http://localhost:8000/docs

ReDoc

/redoc の ReDoc は、読み取り専用でドキュメント重視の Swagger の代替です。生の OpenAPI スキーマは /openapi.json にあり、他のツールへ渡せます。ドキュメントの無効化には docs_url=None、redoc_url=None、openapi_url=None を使います(本番など)。

fastapi
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def root():
    return {"hello": "world"}

# ReDoc (alternative docs UI) at: http://localhost:8000/redoc
# raw OpenAPI JSON at: http://localhost:8000/openapi.json

# disable docs entirely:
# app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)

Tags とグループ化

Tags がドキュメント UI のルートをグループ化します。openapi_tags でタグのメタデータ(name、description、externalDocs)を事前宣言すれば、ルートが使う前でもグループが現れます。エンドポイントをドキュメントで非推奨とするには deprecated=True を設定します。

fastapi
from fastapi import FastAPI

app = FastAPI(openapi_tags=[
    {"name": "users", "description": "User management"},
    {"name": "items", "description": "Item operations"},
])

@app.get("/users", tags=["users"])
def list_users(): ...

@app.post("/items", tags=["items"])
def create_item(): ...

@app.get("/items/{id}", tags=["items"], deprecated=True)
def get_item(id: int): ...

ルートのメタデータ

デコレータは OpenAPI へ流れるメタデータを受け付けます:summary(短いタイトル)、description(長文)、response_description、tags、deprecated、status_code。明示的に渡さなければ、docstring が description として使われます。

fastapi
from fastapi import FastAPI, status
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

app = FastAPI()

@app.post(
    "/items",
    response_model=Item,
    status_code=status.HTTP_201_CREATED,
    summary="Create an item",
    description="Creates a new item and returns it.",
    tags=["items"],
    response_description="The created item",
)
def create_item(item: Item):
    """Create endpoint docstring — also shown in docs."""
    return item

フィールドの例

Field(examples=[...]) と Body(examples=[...]) が、Swagger UI の「Try it out」と例のドロップダウンへ例のペイロードを加えます。Body の例は、有効な入力と無効な入力を示すため、サマリー付きの複数ケースを含められます。

fastapi
from pydantic import BaseModel, Field
from fastapi import FastAPI, Body

class Item(BaseModel):
    name: str = Field(examples=["Apple"])
    price: float = Field(examples=[0.5], gt=0)

app = FastAPI()

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

@app.post("/manual")
def manual(
    item: Item = Body(
        examples=[
            {"summary": "valid", "value": {"name": "Apple", "price": 0.5}},
            {"summary": "invalid", "value": {"name": "Apple", "price": -1}},
        ],
    ),
):
    return item

カスタム OpenAPI スキーマ

生成されるスキーマをカスタマイズするには app.openapi をオーバーライドします — ロゴ、追加メタデータの追加、操作の除去/変換。結果は 1 回だけ生成されるよう app.openapi_schema にキャッシュしましょう。このスキーマが /openapi.json で提供されるものです。

fastapi
from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

app = FastAPI()

def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    schema = get_openapi(
        title="Custom API",
        version="2.0.0",
        routes=app.routes,
    )
    schema["info"]["x-logo"] = {"url": "https://example.com/logo.png"}
    app.openapi_schema = schema
    return schema

app.openapi = custom_openapi
19

デプロイ(Uvicorn / Gunicorn)

本番での Uvicorn

本番では、リバースプロキシ(Nginx、Caddy、クラウドのロードバランサー)の後ろで Uvicorn を実行しましょう。--proxy-headers を使えば、アプリが X-Forwarded-For/X-Forwarded-Proto からクライアントの実際の IP/host を見ます。本番で --reload は避けましょう。

fastapi
# Run directly with uvicorn (single worker)
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 1

# Recommended: behind a reverse proxy (nginx) on port 8000
# Use --proxy-headers so X-Forwarded-* is trusted
uvicorn main:app --host 0.0.0.0 --port 8000 --proxy-headers --forwarded-allow-ips='*'

Uvicorn ワーカー付き Gunicorn

Gunicorn が複数の Uvicorn ワーカープロセスを管理し、優雅なリロード、クラッシュ時の再起動、pre-fork のスケーリングを提供します。UvicornWorker クラスを使いましょう。workers は出発点として (2 * CPU コア数 + 1) に設定し、その後ベンチマークしましょう。

fastapi
# install the uvicorn worker class
pip install "uvicorn[standard]" gunicorn

# run 4 worker processes managed by gunicorn
gunicorn main:app \
    -w 4 \
    -k uvicorn.workers.UvicornWorker \
    -b 0.0.0.0:8000 \
    --timeout 120

# -w workers (commonly 2*CPU+1), -k worker class

Docker デプロイ

スリムな Python ベースイメージがイメージを小さく保ちます。Docker のレイヤーキャッシュを活用するため、コードのコピー前に依存をインストールしましょう。コンテナ内では gunicorn+uvicorn ワーカーで実行し、ポート 8000 をホストかオーケストレーターへ公開します。

fastapi
# Dockerfile
FROM python:3.12-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .
CMD ["gunicorn", "main:app", "-w", "4", \
     "-k", "uvicorn.workers.UvicornWorker", \
     "-b", "0.0.0.0:8000"]

# build & run:
# docker build -t myapi .
# docker run -p 8000:8000 myapi

環境設定

pydantic-settings(旧 pydantic.BaseSettings)が、型検証付きで環境変数と .env ファイルから設定を読み込みます。これで、環境変数を変えるだけで同じイメージが異なる環境(dev/staging/prod)で動きます。

fastapi
import os
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str = "sqlite:///./app.db"
    secret_key: str = "change-me"
    debug: bool = False
    allowed_origins: list[str] = ["http://localhost:3000"]

    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"

settings = Settings()

# .env file:
# DATABASE_URL=postgresql://user:pass@db:5432/app
# SECRET_KEY=long-random-string
# DEBUG=false

Nginx リバースプロキシ

Nginx が HTTP(S) を終端し、localhost:8000 の Uvicorn へ転送します。アプリが実際のクライアント IP とスキームを見られるよう X-Forwarded-* ヘッダーを設定しましょう(Uvicorn 側は --proxy-headers)。Upgrade/Connection の行が WebSocket の対応を有効にします。

fastapi
# /etc/nginx/conf.d/api.conf
server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;

        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

スケーリングと同時実行

スケールの方法は 2 つです:マシンごとに Uvicorn ワーカープロセスを増やす(CPU バウンド)、ロードバランサーの後ろでマシンを増やす(水平)。非同期アプリでは、イベントループが 1 ワーカーあたり多くの同時 I/O リクエストを処理します。オーケストレーター(k8s、ECS)が生存性を確認できるよう /health エンドポイントを加えましょう。

fastapi
# Workers = process count (vertical scaling); pick ~2*CPU
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker

# Inside async app: concurrency is cooperative via the event loop.
# CPU-bound work blocks it — offload to a threadpool or task queue.

# Horizontal scaling: run several containers behind a load balancer.
# Use a shared store (Redis) for session state and rate limits.

# Health check endpoint for the balancer:
@app.get("/health")
def health():
    return {"status": "ok"}
20

応用トピック

Lifespan イベント

lifespan コンテキストマネージャーが非推奨になった on_event('startup'/'shutdown') ハンドラを置き換えます。yield 前のコードが起動時に、yield 後のコードがシャットダウン時に動きます(起動が失敗しても)。DB 接続、ML モデル、キャッシュの初期化に使いましょう。

fastapi
from contextlib import asynccontextmanager
from fastapi import FastAPI

@asynccontextmanager
async def lifespan(app: FastAPI):
    # runs at startup
    print("starting up")
    app.state.cache = {}
    yield
    # runs at shutdown
    print("shutting down")
    await app.state.cache.clear()

app = FastAPI(lifespan=lifespan)

# the old @app.on_event("startup") / "shutdown" are deprecated
# in favor of the lifespan handler above.

サブアプリケーション(Mount)

app.mount() がパスの接頭辞の下にサブアプリケーションを取り付けます。バージョン管理された API や複数アプリの組み合わせに有用です。各サブアプリは独自のルートと OpenAPI スキーマを持ちます。親のドキュメントには、デフォルトでは子のルートは含まれません。

fastapi
from fastapi import FastAPI

app = FastAPI()

api_v1 = FastAPI()
api_v2 = FastAPI()

@api_v1.get("/items")
def v1_items():
    return {"version": 1}

@api_v2.get("/items")
def v2_items():
    return {"version": 2}

app.mount("/v1", api_v1)
app.mount("/v2", api_v2)

# GET /v1/items -> {"version": 1}
# GET /v2/items -> {"version": 2}

APIRouter

APIRouter が関連するルートを、共有の prefix、tags、dependencies、responses を持つモジュールへグループ化します。app.include_router(router) で取り込みます(独自の prefix や tags を付けられます)。複雑なアプリを構成する標準的なパターンです。

fastapi
from fastapi import APIRouter, Depends

router = APIRouter(
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(verify_token)],
    responses={404: {"description": "Not found"}},
)

@router.get("/")
def list_items():
    return []

@router.get("/{item_id}")
def get_item(item_id: int):
    return {"id": item_id}

# in main.py: app.include_router(router)

静的ファイル

StaticFiles が静的アセット(画像、CSS、JS)のディレクトリを URL 接頭辞で提供します。ディレクトリごとに 1 回マウントしましょう。SPA フロントエンドには、index.html を指す最後の catch-all ルートをマウントします。静的ファイルは速さのためルーティングシステムをバイパスします。

fastapi
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

app = FastAPI()

# serve files from ./static at /static
app.mount("/static", StaticFiles(directory="static"), name="static")

# /static/logo.png -> ./static/logo.png
# /static/css/app.css -> ./static/css/app.css

ストリーミングレスポンス

StreamingResponse は、ボディ全体をメモリで組み立てる代わりに、チャンクで生成される(ジェネレータ/イテレータ)レスポンスを送ります — 大きな CSV エクスポート、ファイルのストリーミング、SSE に理想的です。クライアントがストリームを正しく扱えるよう media_type を適切に設定しましょう。

fastapi
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import csv, io

app = FastAPI()

def iter_csv():
    output = io.StringIO()
    writer = csv.writer(output)
    writer.writerow(["id", "name"])
    for i in range(1000):
        writer.writerow([i, f"name-{i}"])
        yield output.getvalue()
        output.seek(0)
        output.truncate(0)

@app.get("/export.csv")
def export():
    return StreamingResponse(
        iter_csv(),
        media_type="text/csv",
        headers={"Content-Disposition": "attachment; filename=export.csv"},
    )

カスタムルートクラス

APIRoute を継承すれば、各エンドポイントに触れずにすべてのルートハンドラをカスタムロジック(ロギング、トレーシング、タイミング)で包めます。app.router.route_class を設定するか、APIRouter に route_class を渡しましょう。ハンドラはマッチした各リクエストに対して動きます。

fastapi
from fastapi import FastAPI, Request, Response
from fastapi.routing import APIRoute
from typing import Callable

class LoggingRoute(APIRoute):
    def get_route_handler(self) -> Callable:
        original = super().get_route_handler()
        async def handler(request: Request) -> Response:
            print(f"-> {request.method} {request.url.path}")
            response = await original(request)
            print(f"<- {response.status_code}")
            return response
        return handler

app = FastAPI()
app.router.route_class = LoggingRoute

@app.get("/items")
def items():
    return {"items": []}

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.