API Request Method - PUT (Update the table)

 API Request Method - PUT (Update the table)

code:
Path parameter validation variable must be last entry in method else it will cause error for other variable.
# This file it to perform all the activity which we required for Todo application.
# Depends means dependency injection
from fastapi import FastAPI, Depends, HTTPException, Path
import models
from models import Todos
from database import engine, SessionLocal
from typing import Annotated
from sqlalchemy.orm import Session
from starlette import status
from TodoValidator import TodoRequest

app = FastAPI()

# it will execute only when todos.db is not existing.
# side effect if you enhance the table in model file then it will not update
# it in database automatically.
models.Base.metadata.create_all(bind=engine)
 
# creating db dependency
def get_db():
    # We need to fetch this SessionLocal before each request made to database.
    db = SessionLocal()
    try:
        # Only the code prio to and including the
        # yield statement will execute before sending the response.
        yield db
    finally:
        # It will be executed after sending the response.
        # It makes fastAPI quicker as we can fetch information
        # from the database and return it to client
        # and then can close the db connection.
        # It makes the connection extreamly safe.
        # As it will open the database connect only at the time of usage.
        db.close()

db_dependency = Annotated[Session, Depends(get_db)]
# Creating asynchronous API Endpoint for database interaction.
@app.get("/", status_code=status.HTTP_200_OK)
#async def read_all(db: Annotated[Session, Depends(get_db)]):
async def read_all(db: db_dependency):
    return db.query(Todos).all()

@app.get("/todo/{todo_id}", status_code=status.HTTP_200_OK)
async def read_todo_by_id(db: db_dependency, todo_id: int = Path(gt=0)):
    todo_model= db.query(Todos).filter(Todos.id == todo_id).first()
    if todo_model is not None:
        return todo_model
    raise HTTPException(status_code=404, detail="id not found in table Todo")

@app.post("/todo",status_code=status.HTTP_201_CREATED)
async def create_todo(db: db_dependency, todo_request: TodoRequest):
    todo_model = Todos(**todo_request.model_dump())
    db.add(todo_model)
    db.commit()

@app.put("/todo/{todo_id}", status_code=status.HTTP_204_NO_CONTENT)
async def update_todo(db: db_dependency,
                      todo_request: TodoRequest,
                      todo_id: int = Path(gt=0)
                      ):
    todo_model = db.query(Todos).filter(Todos.id == todo_id).first()
    if todo_model is None:
        raise HTTPException(status_code=404, detail='Id not found in Todo table')
   
    # todo_model must be the same which we are creating above in this method
    # As sqlalchemy will use it to update the table.
    # As if we are using the same model then it will think it as a new record
    # will try to insert it with new id as autoincremented one.
    # or might create an identical record with same id.
    todo_model.title = todo_request.title
    todo_model.description = todo_request.description
    todo_model.priority = todo_request.priority
    todo_model.complete = todo_request.complete

    #  As a result we are modifying the todo_model value before adding to todo table.
    db.add(todo_model)
    db.commit()

Result:





Comments

Popular posts from this blog

Path Parameter Data Validation | Query Parameter Data Validation

CRUD Assignment

Python Variables