fastapi_mongoDB / routes /student_routes.py
PrabhuKiranKonda's picture
Update routes/student_routes.py
f63e73c
from fastapi import APIRouter, Body, status
from fastapi.encoders import jsonable_encoder
from models.schema import (
StudentSchema,
StudentUpdateSchema,
ResponseModel,
ErrorResponseModel,
)
from database import *
router = APIRouter()
@router.post("/", response_description="Student data added into the database")
async def add_student_data(student: StudentSchema = Body(...)):
student = jsonable_encoder(student)
# if get_student_data(student["pin"]):
# return ErrorResponseModel("Student Exist", 404, f"Student with PIN: {student['pin']} already exists.")
new_student = await add(student)
return ResponseModel(new_student, "Student added successfully.")
@router.get("/all", response_description="Students Data Retrieved")
async def get_all_students():
students = await get_all()
if len(students) < 1:
return ErrorResponseModel("Empty Database", 404, "No Students data found")
if students:
return ResponseModel(students, "Retrieved all students data")
ErrorResponseModel("An Error Occurred", 404, "No Students database found")
@router.get("/{pin}", response_description="Student data retrieved")
async def get_student_data(pin):
student = await get(pin)
if student:
return ResponseModel(student, "Student data retrieved successfully")
return ErrorResponseModel("An error occurred.", 404, "Student doesn't exist.")
@router.put("/{pin}")
async def update_student_data(pin: str, data: StudentUpdateSchema = Body(...)):
data = {k: v for k, v in data.dict().items() if v is not None}
updated_student = await update(pin, data)
if updated_student:
return ResponseModel(updated_student, f"{pin} data updated")
return ErrorResponseModel("An Error occurred", 404, "Cannot update the data. Maybe pin doesn't exist")
@router.delete("/delete/{pin}", response_description="Delete student from database")
async def delete_student(pin: str):
student = await delete(pin)
if student:
return ResponseModel(f"Student with {pin} removed from the database", "Operation Success")
return ErrorResponseModel("An Error occurred", 404, f"student with PIN {pin} does not exist")