Get List of all Blogs

Git Commit: list active blogs
In a typical blog list, we are more concerned about rendering a list of blogs instead of just fetching one single blog. This is generally called a list view. It's not necessary that you always show a list of cards. It could be a list of rows in tables or even a list of items in raw format!

In general, we have 5 types of operations in any API :

  • List 
  • Retrieve (get one record from DB)
  • Post  (create a new record in DB)
  • Put/Patch  (Update a record)
  • Delete    (Delete a record from DB)

In this post, we are going to implement this listview. We have to add a new route in APIs > v1  > route_blog.py
 

from typing import List
###
from db.repository.blog import create_new_blog, retreive_blog, list_blogs

router = APIRouter()

###

@router.get("/blogs", response_model=List[ShowBlog])
def get_all_blogs(db: Session = Depends(get_db)):
    blogs = list_blogs(db=db)
    return blogs

Since we don't need any id or any data to retrieve we are simply making use of the db session. Notice that we are using Dependency Injection instead of hardcoding db. It will help us in overriding db during our tests. We need to create a function list_blogs in db > repository > blog.py which will actually extract all blogs from db and return the result to our route. Finally, we are returning all blogs from route to the client/browser and during this process, we are making sure we filter the attributes using ShowBlog schema. Since, In reality, we are returning a list [ ]  of blogs of ShowBlog schema so we used List[ShowBlog]. Let's implement the list_blogs function in db > repository > blog.py

from sqlalchemy.orm import Session 
from schemas.blog import CreateBlog
from db.models.blog import Blog

###

def list_blogs(db : Session):
    blogs = db.query(Blog).filter(Blog.is_active==True).all()
    return blogs

Done, Now, all we need is to make at least 1 or 2 blogs active. We can open up PgAdmin, go to the table named blog, right-click it and click on Query Tool and execute the below query to make a blog active.

update blog set is_active=true where id=2;

Time to test our API using docs. Navigate to the API docs and you should get a list of blogs when you click execute.

200	
Response body
Download

[
  {
    "title": "Awesome FastAPI",
    "content": "Everyone knows FastAPI is awesome. No need to write more about it.",
    "created_at": "2023-06-17"
  }
]

 

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