List of Blogs as Cards

Git Commit: serve blog list in the homepage
Currently, We just have a navbar, and we are able to serve templates and static files as discussed in the previous tutorial.

That's all !, we do have an API but the reality is most of our users want to visit a site e.g. www.example.com, and want to see a list of available blogs. I have never seen my friends firing up Postman and making a get request to API to fetch a list of blogs😆!
That's why we want to convert our project to have a web app version as well.

There are several architectures for creating a web app. Some people use MVT(Model-View-Template), some use View-Model architecture, and there are hundreds of different architectures. Since we are familiar with the routing method that we were using to build APIs, I will stick to the same routing structure.

Currently, this homepage is served by apps > v1 > route_blog.py. So, in order to serve list of blogs, we will need to modify it a bit.

from fastapi import APIRouter
from fastapi import Request
from fastapi.templating import Jinja2Templates
from fastapi import Depends    #new
from sqlalchemy.orm import Session
from db.repository.blog import list_blogs   
from db.session import get_db

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


@router.get("/")
def home(request: Request, db: Session = Depends(get_db)):
    blogs = list_blogs(db=db)
    return templates.TemplateResponse(
        "blog/home.html", {"request": request, "blogs": blogs}
    )

Since It is not an API, It does not make much sense to see the result of this router in the OpenAPI documentation. That's why we have made include_in_schema = False. This home route makes use of our pre-existing repository to fetch a list of blogs from the database. It could have been better, If we were able to use the JSON response only to make the homepage because this route is a duplication of our pre-existing API route to fetch a list of blogs.

Now, let's modify the file templates  > blog > home.html to incorporate the blog list in the form of bootstrap cards.

{% extends "base.html" %}


{% block title %}
<title>Algoholic</title>
{% endblock %}


{% block content %}
<div class="container">
    <h2 class="text-muted">All Blogs</h1>
    <div class="row justify-content-center">

        {% for blog in blogs %}
        <div class="col-sm-4 mb-4">
          <div class="card">
            <div class="card-header">
                <h5 class="card-text">{{ blog.title }}</h5>
            </div>
            <div class="card-body">
              <p class="card-text">First Published : {{blog.created_at.strftime('%Y-%m-%d')}}</p>
              <small class="card-text text-muted">Content : {{blog.content[:60]}}...</small>
              <br>
              <a href="/app/blog/{{blog.id}}" class="btn btn-outline-success">Read more</a>
            </div>
          </div>
        </div>
        {% endfor %}

    </div>
</div>

{% endblock %}

Done, now you should be a list of blogs, make sure, you create some blogs and make them active using psql or pgadmin or dbeaver.

update blog set is_active=True where id=3;

FastAPITutorial

Brige the gap between Tutorial hell and Industry. We want to bring in the culture of Clean Code, Test Driven Development.

We know, we might make it hard for you but definitely worth the efforts.

Contacts

Refunds:

Refund Policy
Social

Follow us on our social media channels to stay updated.

© Copyright 2022-23 Team FastAPITutorial