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()
update_employee
delete_employee
db.query
delete
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)