Update a blog : PUT Request

Git Commit: update a blog
We all make mistakes. Even if we are super careful, technology upgrades, and tools upgrade, so the blog posts also need an update.  So, In this post, we are going to see how we can update our database records.

First, let's create a schema. Since we need the same information as creating a blog post, we can simply inherit the CreateBlog schema. Let's do this in schemas > blog.py

from typing import Optional
from pydantic import BaseModel, validator
from datetime import date

class CreateBlog(BaseModel):
    title: str 
    slug: str
    content: Optional[str] = None 
    
    @validator('slug', pre=True)
    def generate_slug(cls, slug, values):
        title = values.get('title')
        slug = None
        if title:
            slug = title.replace(" ","-").lower()
        return slug
        
#new addition
class UpdateBlog(CreateBlog):    
    pass

##

Let's implement this route at apis > v1 > route_blog.py

from typing import List
from fastapi import APIRouter
from sqlalchemy.orm import Session
from fastapi import Depends
from fastapi import HTTPException, status

from db.session import get_db
from schemas.blog import ShowBlog, CreateBlog, UpdateBlog   #new
from db.repository.blog import create_new_blog, retreive_blog, list_blogs, update_blog  #new

router = APIRouter()

@router.put("/blog/{id}", response_model=ShowBlog)
def update_a_blog(id:int, blog: UpdateBlog, db:Session = Depends(get_db)):
    blog = update_blog(id=id, blog=blog, author_id=1, db=db)
    if not blog:
        raise HTTPException(detail=f"Blog with id {id} does not exist")
    return blog

The router accepts an id in the path parameter and validates if the right blog schema is being passed in the request body by using the UpdateBlog schema. This route is depending on a repository at db > repository > blog.py

from sqlalchemy.orm import Session 
from schemas.blog import CreateBlog, UpdateBlog  #new
from db.models.blog import Blog


def update_blog(id:int, blog: UpdateBlog, author_id: int, db: Session):
    blog_in_db = db.query(Blog).filter(Blog.id == id).first()
    if not blog_in_db:
        return 
    blog_in_db.title = blog.title
    blog_in_db.content = blog.content
    db.add(blog_in_db)
    db.commit()
    return blog_in_db

The  update_blog function is self-explanatory, We are just searching if the blog with the given id exists in the database. If the blog exists, we update the title and content with that of the title and content provided in the request body.

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