|
| 1 | +### Put and Delete-HTTP Verbs |
| 2 | +### Working With API's--Json |
| 3 | + |
| 4 | +from flask import Flask, jsonify, request |
| 5 | + |
| 6 | +app = Flask(__name__) |
| 7 | + |
| 8 | +##Initial Data in my to do list |
| 9 | +items = [ |
| 10 | + {"id": 1, "name": "Item 1", "description": "This is item 1"}, |
| 11 | + {"id": 2, "name": "Item 2", "description": "This is item 2"} |
| 12 | +] |
| 13 | + |
| 14 | +@app.route('/') |
| 15 | +def home(): |
| 16 | + return "Welcome To The Sample To DO List App" |
| 17 | + |
| 18 | +## Get: Retrieve all the items |
| 19 | + |
| 20 | +@app.route('/items',methods=['GET']) |
| 21 | +def get_items(): |
| 22 | + return jsonify(items) |
| 23 | + |
| 24 | +## get: Retireve a specific item by Id |
| 25 | +@app.route('/items/<int:item_id>',methods=['GET']) |
| 26 | +def get_item(item_id): |
| 27 | + item=next((item for item in items if item["id"]==item_id),None) |
| 28 | + if item is None: |
| 29 | + return jsonify({"error":"item not found"}) |
| 30 | + return jsonify(item) |
| 31 | + |
| 32 | +## Post :create a new task- API |
| 33 | +@app.route('/items',methods=['POST']) |
| 34 | +def create_item(): |
| 35 | + if not request.json or not 'name' in request.json: |
| 36 | + return jsonify({"error":"item not found"}) |
| 37 | + new_item={ |
| 38 | + "id": items[-1]["id"] + 1 if items else 1, |
| 39 | + "name":request.json['name'], |
| 40 | + "description":request.json["description"] |
| 41 | + |
| 42 | + |
| 43 | + } |
| 44 | + items.append(new_item) |
| 45 | + return jsonify(new_item) |
| 46 | + |
| 47 | +# Put: Update an existing item |
| 48 | +@app.route('/items/<int:item_id>',methods=['PUT']) |
| 49 | +def update_item(item_id): |
| 50 | + item = next((item for item in items if item["id"] == item_id), None) |
| 51 | + if item is None: |
| 52 | + return jsonify({"error": "Item not found"}) |
| 53 | + item['name'] = request.json.get('name', item['name']) |
| 54 | + item['description'] = request.json.get('description', item['description']) |
| 55 | + return jsonify(item) |
| 56 | + |
| 57 | +# DELETE: Delete an item |
| 58 | +@app.route('/items/<int:item_id>', methods=['DELETE']) |
| 59 | +def delete_item(item_id): |
| 60 | + global items |
| 61 | + items = [item for item in items if item["id"] != item_id] |
| 62 | + return jsonify({"result": "Item deleted"}) |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == '__main__': |
| 68 | + app.run(debug=True) |
0 commit comments