ルーティングと記事一覧・詳細ページ

この章では、APIRouterを使ってルーティングを分割し、ホームページの記事一覧と記事詳細ページを実装します。


APIRouter — FastAPI のルーティング分割方法

APIRouter は Flask の Blueprint や Django の include() に相当します。

例

# ファイルパス: routers/posts.py
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session
from database import get_db
from models import Post, Category
from schemas import PostResponse

router = APIRouter(
    prefix="/posts",       # すべてのルートに自動的に /posts プレフィックスが付きます
    tags=["記事"]          # Swagger ドキュメント内のグループタグ
)

@router.get("/{post_id}", response_model=PostResponse, name="post_detail")
def post_detail(post_id: int, db: Session = Depends(get_db)):
    """記事詳細(JSON API)"""
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="記事が存在しません")
    return post

main.py で APIRouter をマウントします:

例

from routers.posts import router as posts_router
from routers.categories import router as categories_router

app.include_router(posts_router)
app.include_router(categories_router)

記事一覧ページのレンダリング

例

# ファイルパス: routers/posts.py
from fastapi import APIRouter, Depends, Request, Query
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from database import get_db
from models import Post, Category

router = APIRouter()
templates = Jinja2Templates(directory="templates")

@router.get("/", name="index")
def index(
    request: Request,
    category: str | None = Query(None),   # クエリパラメータ:任意
    db: Session = Depends(get_db)
):
    """ホームページ:記事一覧 + カテゴリ絞り込み"""
    # 基本クエリ
    posts_query = db.query(Post).order_by(Post.created_at.desc())

    # カテゴリによる絞り込み
    if category:
        posts_query = posts_query.join(Category).filter(Category.slug == category)

    posts = posts_query.all()
    categories = db.query(Category).all()

    return templates.TemplateResponse("index.html", {
        "request": request,
        "posts": posts,
        "categories": categories,
        "category_slug": category or ""
    })

str | None = Query(None)Python 3.10+ の型ユニオン構文であり、以下と同等です:Optional[str]FastAPI は型ヒントに基づいて自動的に:1. パラメータを任意にします;2. Swagger ドキュメントで任意としてマークします;3. 指定しない場合でもエラーになりません。


記事詳細ページのレンダリング

例

# ファイルパス: routers/posts.py に追記
@router.get("/post/{post_id}", name="post_detail")
def post_detail(request: Request, post_id: int, db: Session = Depends(get_db)):
    """記事詳細ページ"""
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="記事が存在しません")
    return templates.TemplateResponse("post_detail.html", {
        "request": request,
        "post": post
    })

注意して区別してください:同じルートで JSON API(response_model を宣言)と HTML ページ(TemplateResponse を返す)を同時に提供できます。一般的な方法は:API ルートは /api/ プレフィックスの下に置き、ページルートはルートパスの下に置くことです。


ホームページと詳細ページのテンプレートを作成

例

<!-- ファイルパス: templates/index.html -->
{% extends 'base.html' %}

{% block title %}サンプル ブログ - ホームページ{% endblock %}

{% block content %}
<h2 class="section-title">最新の記事</h2>

<div class="category-bar">
    <a href="/" class="{% if not category_slug %}active{% endif %}">すべて</a>
    {% for cat in categories %}
    <a href="/?category={{ cat.slug }}"
      class="{% if category_slug == cat.slug %}active{% endif %}">
        {{ cat.name }}
    </a>
    {% endfor %}
</div>

{% if posts %}
<div class="article-grid">
    {% for post in posts %}
    <a href="/post/{{ post.id }}" class="card-link">
        <div class="article-card">
            <div class="card-content">
                <span class="card-category">{{ post.category.name }}</span>
                <h3>{{ post.title }}</h3>
                <p>{{ post.summary|truncate(80) }}</p>
                <span class="card-date">{{ post.created_at.strftime('%Y-%m-%d') }}</span>
            </div>
        </div>
    </a>
    {% endfor %}
</div>
{% else %}
<p class="empty-tip">このカテゴリにはまだ記事がありません。</p>
{% endif %}
{% endblock %}

例

<!-- ファイルパス: templates/post_detail.html -->
{% extends 'base.html' %}

{% block title %}{{ post.title }} - サンプル ブログ{% endblock %}

{% block content %}
<article class="post-view">
    <span class="category-tag">{{ post.category.name }}</span>
    <h1>{{ post.title }}</h1>
    <time>{{ post.created_at.strftime('%Y-%m-%d') }}</time>
    <div class="content">{{ post.content|safe }}</div>
    <a href="/" class="back-link">← ホームページに戻る</a>
</article>
{% endblock %}

本章のまとめ

この章では、FastAPI のコアルーティング開発を完了しました:APIRouter によるモジュール単位のルート分割(prefix + tags)、クエリパラメータを Query() + 型ヒントで宣言、TemplateResponse によるページのレンダリング、404 例外処理。

ブログには、ホームページの記事一覧、カテゴリ絞り込み、詳細ページの3つの完全なページができました。

その他の拡張