Delete a Blog [Delete Request]

Git Commit: route to delete a blog
Just like the need to update, sometimes we write some 💩(including me). In such cases, we need to delete the blog post. To enable deleting a post, we will need to create a route and ORM queries supporting the route. Let's proceed with it.

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

router = APIRouter()

@router.delete("/delete/{id}")
def delete_a_blog(id:int, db: Session = Depends(get_db)):
    message = delete_blog(id=id,author_id=1,db=db)
    if message.get("error"):
        raise HTTPException(detail=message.get("error"), status_code= status.HTTP_400_BAD_REQUEST)
    return {"msg":f"Successfully deleted blog with id {id}"}

We also need a repository/ORM query that supports deleting the blog object. For this, we will need to create a new function in db > repository > blog.py

def delete_blog(id:int, author_id:int,db:Session):
    blog_in_db = db.query(Blog).filter(Blog.id == id)
    if not blog_in_db.first():
        return {"error":f"Could not find blog with id {id}"}
    blog_in_db.delete()
    db.commit()
    return {"msg":f"deleted blog with id {id}"}

Notice the use of .first() If we write, blog_in_db = db.query(Blog).filter(Blog.id == id).first() Then we will get an actual blog object from the database. This blog object has no delete() method defined. So, instead, we are working with the reference of the blog object and deleting it.

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