Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Routes, Article List, and Detail Page

Routes, Article List, and Detail Page

In this chapter you'll learn to split routes with APIRouter and implement the homepage article list and article detail page.


APIRouter — FastAPI's route-splitting solution

APIRouter is comparable to Flask's Blueprint and Django's include().

Example

File path: 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"

,

     

All routes automatically get the /posts prefix

    tags

=

[

"Article"

]

         

Grouping tags in the Swagger docs

)

@

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 the APIRouter in main.py:

Example

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

)


Render the article list page

Example

File path: 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

)

,

 

Query parameter: optional

    db: Session

=

Depends

(

get_db

)

)

:

   

"""Homepage: article list + category filter"""

   

Basic query

    posts_query

=

db.

query

(

Post

)

.

order_by

(

Post.

created_at

.

desc

(

)

)

   

Category filtering

   

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) is Python 3.10+'s type union syntax, equivalent to Optional[str]. Based on the type hint, FastAPI automatically: 1. makes the parameter optional; 2. marks it as optional in the Swagger docs; 3. raises no error when it's not passed.


Render the article detail page

Example

File path: append to routers/posts.py

@

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 (declare response_model) and an HTML page (return TemplateResponse). The usual approach is: API routes under the /api/ prefix, page routes under the root path.


Create the homepage and detail page templates

Example

{% extends 'base.html' %}

{% block title %}RUNOOB Blog - Home{% endblock %}

{% block content %}

Latest Articles

{% if posts %}

    {% for post in posts %}

   

       

           

               

{{ post.category.name }}

               

{{ post.title }}

               

{{ post.summary|truncate(80) }}

               

{{ post.created_at.strftime('%Y-%m-%d') }}

           

       

   

    {% endfor %}

{% else %}

No articles in this category yet.

{% endif %}

{% endblock %}

Example

{% extends 'base.html' %}

{% block title %}{{ post.title }} - RUNOOB Blog{% endblock %}

{% block content %}

   

{{ post.category.name }}

   

{{ post.title }}

   

   

{{ post.content|safe }}

   

← Back to Home

{% endblock %}


Chapter Summary

In this chapter you completed FastAPI's core routing development: APIRouter splits routes by module (prefix + tags), query parameters declared with 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.