Get Request to Retreive a Blog

Git Commit: get a blog
I believe you still remember the very first post, where I told you the difference between get, post, put, patch, and delete requests. In this post, we are going to explore GET requests. First, we will implement a route that gives back data of a blog post given its id. This time we already have all the files existing. Just add the following code in apis > versions > route_blog.py

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
from db.repository.blog import create_new_blog, retreive_blog

router = APIRouter()


@router.post("/blogs",response_model=ShowBlog)
def create_blog(blog: CreateBlog, db: Session= Depends(get_db)):
    #....


@router.get("/blog/{id}", response_model=ShowBlog)
def get_blog(id: int, db: Session= Depends(get_db)):
    blog = retreive_blog(id=id, db=db)
    if not blog:
        raise HTTPException(detail=f"Blog with ID {id} does not exist.", status_code=status.HTTP_404_NOT_FOUND)
    return blog

Since our database and orm logic will be in the repository folder. So, let's add the following lines in file db > repository > blog.py

def retreive_blog(id: int, db: Session):
    blog = db.query(Blog).filter(Blog.id == id).first()
    return blog
  • This query is powered by Sqlalchemy.
  • It is equivalent to : select * from blog where id = 1;  #id = given_id
  • The database will find the blog and will return the result. We are verifying that this returned item is not none, In case it is none, we are raising an HTTPException to inform our users about the issue.

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