app = Flask(__name__)
employees = [
{"id": 1, "Name": "Ram", "Age": 20,"Gender":"Male"},
{"id": 2, "Name": "Sita", "Age": 25,"Gender":"Female" }
]
@app.route('/', methods=['GET'])
def get_employees():
return (employees)
@app.route('/employees/id', methods = ['GET'])
def get_employee(employee_id):
for employee in employees:
if employee['id']== employees_id:
return employee
return {'error':'Employee not found'}
I am new to Flask. I am trying to get employee by ID, but it throws 405 error. However I was able to get all the employees but not according to id.
you are missing the proper format for route passing id which would be <int:employee_id>
as well as in parameter its employee_id
from flask import Flask, jsonify, request
app = Flask(__name__)
employees = [
{"id": 1, "Name": "Ram", "Age": 20,"Gender":"Male"},
{"id": 2, "Name": "Sita", "Age": 25,"Gender":"Female" },
{"id": 3, "Name": "Mahesh", "Age":45,"Gender":"Male"},
{"id": 4, "Name": "Rita", "Age": 52,"Gender":"Female"},
]
@app.route('/', methods=['GET'])
def get_employees():
return (employees)
@app.route('/employees/<int:employee_id>', methods = ['GET'])
def get_employee(employee_id):
for employee in employees:
if employee['id']== employee_id:
return employee
return {'error':'Employee not found'}
@app.route('/', methods=['POST'])
def add_employee():
new_employee={'id':len(employees)+1, 'Name':request.json['Name'], 'Age':request.json['Age'], 'Gender':request.json['Gender']}
employees.append(new_employee)
return(new_employee)
@app.route('/employees/<int:employee_id>', methods=['PUT'])
def update_employee(employee_id):
for employee in employees:
if employee['id']== employee_id:
employee['Name']= request.json['Name']
employee['Age']=request.json['Age']
employee['Gender']=request.json['Gender']
return employee
return {'error':'Employee not found'}
@app.route('/employees/<int:employee_id>', methods=['DELETE'])
def delete_employee(employee_id):
for employee in employees:
if employee['id']== employee_id:
employees.remove(employee)
return {'data':'Employe has been removed'}
return {'error':'Employee not found'}
if __name__== "__main__":
app.run(debug = True).