Click here to Skip to main content
16,015,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In the following code the Get & Post method is working fine but in put & delete method it throws internal server error, I can't find what is wrong in my code .
How to solve this?

What I have tried:

from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field
import models
from database import engine, SessionLocal
from sqlalchemy.orm import Session

app = FastAPI()

models.Base.metadata.create_all(bind=engine)


def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()


class Employee(BaseModel):
    first_name: str = Field(min_length=1)
    last_name: str = Field(min_length=1, max_length=100)
    city: str = Field(min_length=1, max_length=100)
    experience: int = Field(gt=-1, lt=101)
    ctc: int = Field()
    age: int = Field(gt=-1, lt=101)
    contact: str = Field(min_length=1, max_length=100)

EMPLOYEE = []

@app.get('/')
async def root():
    return {'message': 'Hello World!'}

@app.get("/read_api")
def read_api(db: Session = Depends(get_db)):
    return db.query(models.Employees).all()


@app.post("/")
def create_book(employee: Employee, db: Session = Depends(get_db)):

    employee_model = models.Employees()
    employee_model.first_name = employee.first_name
    employee_model.last_name = employee.last_name
    employee_model.city = employee.city
    employee_model.experience = employee.experience
    employee_model.ctc = employee.ctc
    employee_model.age = employee.age
    employee_model.contact = employee.contact

    db.add(employee_model)
    db.commit()

    return employee


@app.put("/{emp_id}")
def update_employee(emp_id: int, employee: Employee, db: Session = Depends(get_db)):

    employee_model = db.query(models.Employees).filter(models.Employees.id == emp_id).first()

    if employee_model is None:
        raise HTTPException(
            status_code=404,
            detail=f"ID {emp_id} : Does not exist"
        )

    employee_model.first_name = employee.first_name
    employee_model.last_name = employee.last_name
    employee_model.city = employee.city
    employee_model.experience = employee.experience
    employee_model.ctc = employee.ctc
    employee_model.age = employee.age
    employee_model.contact = employee.contact

    db.add(employee_model)
    db.commit()

    return employee


@app.delete("/{emp_id}")
def delete_employee(emp_id: int, db: Session = Depends(get_db)):

    employee_model = db.query(models.Employees).filter(models.Employees.id == emp_id).first()

    if employee_model is None:
        raise HTTPException(
            status_code=404,
            detail=f"ID {emp_id} : Does not exist"
        )

    db.query(models.Employees).filter(models.Employees.id == emp_id).delete()

    db.commit()
Posted
Updated 7-Jul-22 6:24am

1 solution

As far as I can see:
- in update_employee you are not updating a record, but trying to add a new one. Which suggests that the database is rejecting it.
- in delete_employee you should first check that the call to db.query actually returns a valid record. As it stands you could be calling delete on a null reference.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900