Completing CRUD: PUT & DELETE APIs with Flask + Oracle


In the previous articles, we created GET and POST REST APIs to read and insert employee data into Oracle Database.

Let's quickly complete our CRUD API with PUT (Update) and DELETE (Delete).

PUT API – Update Employee

The employee ID is passed in the URL:

PUT /EmployeeInsert/5

Request body:

{
    "name": "Pranay Tiwari",
    "dept": "IT",
    "salary": 75000,
    "contact": "+9195555552367"
}
@app.route('/EmployeeInsert/<int:emp_id>', methods=['PUT'])
def PutEmployeeInfo(emp_id):

    try:
        data = request.get_json()

        row = XXFlaskEmployeeInfo.query.get(emp_id)

        if not row:
            return jsonify({
                "error": "Employee Not Found"
            }), 404

        row.NAME = data.get('name', row.NAME)
        row.DEPT = data.get('dept', row.DEPT)
        row.SALARY = data.get('salary', row.SALARY)
        row.CONTACT_INFO = data.get(
            'contact',
            row.CONTACT_INFO
        )

        db.session.commit()

        return jsonify({
            "message": "Employee Updated",
            "name": row.NAME,
            "dept": row.DEPT
        })

    except Exception as e:
        return jsonify({
            "error": str(e)
        }), 500

The API updates only the values provided in the JSON request.







DELETE API – Delete Employee

The employee ID is passed in the URL:

DELETE /EmployeeDelete/5
@app.route('/EmployeeDelete/<int:emp_id>', methods=['DELETE'])
def DeleteEmployeeInfo(emp_id):

    try:
        row = XXFlaskEmployeeInfo.query.get(emp_id)

        if not row:
            return jsonify({
                "error": "Employee id does not exist"
            }), 404

        db.session.delete(row)
        db.session.commit()

        return jsonify({
            "message": "Employee Deleted",
            "id": emp_id
        }), 200

    except Exception as e:
        return jsonify({
            "error": str(e)
        }), 500

No request body is required for DELETE.



Full source code 

from flask import Flask, render_template,request,jsonify
from flask_sqlalchemy import SQLAlchemy
import oracledb
import json
from datetime import datetime
import os

BASE_DIR=os.path.dirname(os.path.abspath(__file__))
config_path=os.path.join(BASE_DIR,'json.config')

with open(config_path,'r') as c:
 DB_PARAMS= json.load(c)['params'] #Database Parms

oracledb.init_oracle_client(lib_dir=r"C:\instantclient_21_11")
app=Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']=DB_PARAMS['database_conn_link']
db=SQLAlchemy(app)

class XXFlaskEmployeeInfo(db.Model):
  __tablename__='XXFLASK_EMPLOYEE_INFO'
  XXID=db.Column("XXID",db.Integer,primary_key=True)
  NAME=db.Column("NAME",db.String)
  DEPT=db.Column("DEPT",db.String)
  SALARY=db.Column("SALARY",db.Integer)
  CONTACT_INFO=db.Column("CONTACT_INFO",db.String)
  CREATION_DATE=db.Column("CREATION_DATE",db.Date)

@app.route('/EmployeeInsert',  methods=['POST'])



def postEmployeeInfo():
   message = None
   if request.method == 'POST':
     try:
       data=request.get_json() #get json from input body params
       if not data.get("name"):
         return jsonify({"error":"Name is required"}),400
       if not data.get("dept"):
         return jsonify({"error":"Dept is required"})
       if not data.get("salary"):
         return jsonify({"error":"Salary is required"}),400
       if not data.get("contact"):
         return jsonify({"error":"Contacts are essentials"}),400
       EmployeePost= XXFlaskEmployeeInfo(NAME=data['name'],DEPT=data["dept"],SALARY=data["salary"],CONTACT_INFO=data["contact"],CREATION_DATE=datetime.utcnow())
       db.session.add(EmployeePost)
       db.session.commit()
       lSuccessMessage={"message":"Employee Successfully Created","name":EmployeePost.NAME,"dept":EmployeePost.DEPT}
       return jsonify (lSuccessMessage)
     except Exception as e:
      return jsonify({"error": str(e)}), 500
     
@app.route('/EmployeeInsert/<int:emp_id>',  methods=['PUT'])
def PutEmployeeInfo(emp_id):
     if request.method == 'PUT':
      try:
          data=request.get_json() #get json from input body params
          row=XXFlaskEmployeeInfo.query.get(emp_id)
          if not row:
            return jsonify({"error":"Employee Not Found"}), 404  # ✅ proper 404!
          row.NAME=data.get('name', row.NAME)
          row.DEPT=data.get('dept', row.DEPT)
          row.SALARY=data.get('salary', row.SALARY)
          row.CONTACT_INFO=data.get('contact', row.CONTACT_INFO)
          db .session.commit()
          return jsonify({"message":"Employee Updated","name":row.NAME,"dept":row.DEPT})
      except Exception as e:
        return jsonify({"error":str(e)}), 500  # ✅ proper 500!  
     
@app.route('/EmployeeDelete/<int:emp_id>',methods=['DELETE'])

def DeleteEmployeeInfo(emp_id):
  try:
   
    row=XXFlaskEmployeeInfo.query.get(emp_id)
    if not row:
      return jsonify({"error":"Employee id does not exist"}),400
    db.session.delete(row)
    db.session.commit()
    return jsonify({"message":"Employee Deleted","id":emp_id}),200

  except Exception as e:
    return jsonify({"error":str(e)}),500

if __name__=="__main__":
   app.run(debug=True)





Our CRUD APIs

We now have all four basic operations:

GET     → Read
POST    → Create
PUT     → Update
DELETE  → Delete

Oracle Database → Flask → REST API → JSON

With this, our basic Flask + Oracle CRUD REST API is complete.

Post a Comment

0 Comments