Advertisement
LuisEdu

Flask WebService Example

Jul 22nd, 2017
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. from flask import Flask
  2.  
  3. from flask import jsonify
  4.  
  5. from flask import request
  6.  
  7. app = Flask(__name__)
  8.  
  9. empDB=[
  10.  
  11.  {
  12.  
  13.  'id':'101',
  14.  
  15.  'name':'Saravanan S',
  16.  
  17.  'title':'Technical Leader'
  18.  
  19.  },
  20.  
  21.  {
  22.  
  23.  'id':'201',
  24.  
  25.  'name':'Rajkumar P',
  26.  
  27.  'title':'Sr Software Engineer'
  28.  
  29.  }
  30.  
  31.  ]
  32.  
  33. @app.route('/empdb/employee',methods=['GET'])
  34.  
  35. def getAllEmp():
  36.  
  37.     return jsonify({'emps':empDB})
  38.  
  39. @app.route('/empdb/employee/<empId>',methods=['GET'])
  40.  
  41. def getEmp(empId):
  42.  
  43.     usr = [ emp for emp in empDB if (emp['id'] == empId) ]
  44.  
  45.     return jsonify({'emp':usr})
  46.  
  47. @app.route('/empdb/employee/<empId>',methods=['PUT'])
  48.  
  49. def updateEmp(empId):
  50.  
  51.     em = [ emp for emp in empDB if (emp['id'] == empId) ]
  52.  
  53.     if 'name' in request.json :
  54.  
  55.         em[0]['name'] = request.json['name']
  56.  
  57.     if 'title' in request.json:
  58.  
  59.         em[0]['title'] = request.json['title']
  60.  
  61.     return jsonify({'emp':em[0]})
  62.  
  63. @app.route('/empdb/employee',methods=['POST'])
  64.  
  65. def createEmp():
  66.  
  67.     dat = {
  68.  
  69.     'id':request.json['id'],
  70.  
  71.     'name':request.json['name'],
  72.  
  73.     'title':request.json['title']
  74.  
  75.     }
  76.  
  77.     empDB.append(dat)
  78.  
  79.     return jsonify(dat)
  80.  
  81. @app.route('/empdb/employee/<empId>',methods=['DELETE'])
  82.  
  83. def deleteEmp(empId):
  84.  
  85.     em = [ emp for emp in empDB if (emp['id'] == empId) ]
  86.  
  87.     if len(em) == 0:
  88.  
  89.        abort(404)
  90.  
  91.     empDB.remove(em[0])
  92.  
  93.     return jsonify({'response':'Success'})
  94.  
  95. if __name__ == '__main__':
  96.  
  97.  app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement