-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAPI-RestFull.py
More file actions
64 lines (51 loc) · 1.71 KB
/
API-RestFull.py
File metadata and controls
64 lines (51 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# Developer by Anyel EC
# Whatsapp: +593 99 167 5490
# Linkedln: Anyel EC
from flask import Flask, request, jsonify
app = Flask(__name__)
# Sample data to simulate a database
todos = [
{"id": 1, "task": "Buy milk"},
{"id": 2, "task": "Exercise"},
{"id": 3, "task": "Code in Python"},
]
# Route to get all items
@app.route('/todos', methods=['GET'])
def get_todos():
return jsonify({'todos': todos})
# Route to get an item by ID
@app.route('/todos/<int:todo_id>', methods=['GET'])
def get_todo(todo_id):
todo = next((item for item in todos if item["id"] == todo_id), None)
if todo is not None:
return jsonify({'todo': todo})
else:
return jsonify({'error': 'Item not found'}), 404
# Route to create a new item
@app.route('/todos', methods=['POST'])
def create_todo():
if not request.json or 'task' not in request.json:
return jsonify({'error': 'Task is required'}), 400
new_todo = {
'id': len(todos) + 1,
'task': request.json['task']
}
todos.append(new_todo)
return jsonify({'todo': new_todo}), 201
# Route to update an item by ID
@app.route('/todos/<int:todo_id>', methods=['PUT'])
def update_todo(todo_id):
todo = next((item for item in todos if item["id"] == todo_id), None)
if todo is None:
return jsonify({'error': 'Item not found'}), 404
if 'task' in request.json:
todo['task'] = request.json['task']
return jsonify({'todo': todo})
# Route to delete an item by ID
@app.route('/todos/<int:todo_id>', methods=['DELETE'])
def delete_todo(todo_id):
global todos
todos = [item for item in todos if item["id"] != todo_id]
return jsonify({'result': True})
if __name__ == '__main__':
app.run(debug=True)