Routing and Article List & Detail Page
In this chapter, you will learn to use APIRouter to split routes, implementing the homepage article list and article detail page.
APIRouter — FastAPI's route splitting solution
APIRouter is analogous to Flask's Blueprint and Django's include().
Example
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", # All routes automatically have /posts prefix
tags=["Article"] # Group tags in Swagger documentation
)
@router.get("/{post_id}", response_model=PostResponse, name="post_detail")
def post_detail(post_id: int, db: Session = Depends(get_db)):
"""Article detail (JSON API)"""
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail=“Article does not exist”)
return post
Mount APIRouter in main.py:
Example
from routers.categories import router as categories_router
app.include_router(posts_router)
app.include_router(categories_router)
Render article list page
Example
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), # Query parameters: optional
db: Session = Depends(get_db)
):
"""Home page: article list + category filter"""
# Basic query
posts_query = db.query(Post).order_by(Post.created_at.desc())
# Category filter
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)This is the type union syntax of Python 3.10+, equivalent toOptional[str]. FastAPI will automatically, based on type hints: 1. make the parameter optional; 2. mark it as optional in Swagger docs; 3. not raise an error when it is not provided.
Render article detail page
Example
@router.get("/post/{post_id}", name="post_detail")
def post_detail(request: Request, post_id: int, db: Session = Depends(get_db)):
"""Article detail page"""
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail=“Article does not exist”)
return templates.TemplateResponse("post_detail.html", {
"request": request,
"post": post
})
Note the distinction: the same route can provide both a JSON API (declaring response_model) and an HTML page (returning TemplateResponse). The common practice is: API routes are placed under the /api/ prefix, while page routes are placed at the root path.
Create homepage and detail page templates
Example
{% extends 'base.html' %}
{% block title %}EXAMPLE Blog - Home{% endblock %}
{% block content %}
<h2 class="section-title">Latest Articles</h2>
<div class="category-bar">
<a href="/" class="{% if not category_slug %}active{% endif %}">All</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">No articles yet in this category.</p>
{% endif %}
{% endblock %}
Example
{% extends 'base.html' %}
{% block title %}{{ post.title }} - EXAMPLE Blog{% 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">← Back to Home</a>
</article>
{% endblock %}
Chapter summary
In this chapter, you completed FastAPI's core routing development: APIRouter splits routes by module (prefix + tags), query parameters are declared using Query() + type hints, TemplateResponse renders pages, and 404 exception handling.
The blog now has three complete pages: homepage article list, category filtering, and detail page.
other extensions