-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathapp.py
More file actions
101 lines (78 loc) · 2.21 KB
/
app.py
File metadata and controls
101 lines (78 loc) · 2.21 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from flask import Flask, jsonify, abort, make_response, request
NOT_FOUND = 'Not found'
BAD_REQUEST = 'Bad request'
app = Flask(__name__)
items = [
{
'id': 1,
'name': 'laptop',
'value': 1000
},
{
'id': 2,
'name': 'chair',
'value': 300,
},
{
'id': 3,
'name': 'book',
'value': 20,
},
]
def _get_item(id):
return [item for item in items if item['id'] == id]
def _record_exists(name):
return [item for item in items if item["name"] == name]
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': NOT_FOUND}), 404)
@app.errorhandler(400)
def bad_request(error):
return make_response(jsonify({'error': BAD_REQUEST}), 400)
@app.route('/api/v1.0/items', methods=['GET'])
def get_items():
return jsonify({'items': items})
@app.route('/api/v1.0/items/<int:id>', methods=['GET'])
def get_item(id):
item = _get_item(id)
if not item:
abort(404)
return jsonify({'items': item})
@app.route('/api/v1.0/items', methods=['POST'])
def create_item():
if not request.json or 'name' not in request.json or 'value' not in request.json:
abort(400)
item_id = items[-1].get("id") + 1
name = request.json.get('name')
if _record_exists(name):
abort(400)
value = request.json.get('value')
if type(value) is not int:
abort(400)
item = {"id": item_id, "name": name,
"value": value}
items.append(item)
return jsonify({'item': item}), 201
@app.route('/api/v1.0/items/<int:id>', methods=['PUT'])
def update_item(id):
item = _get_item(id)
if len(item) == 0:
abort(404)
if not request.json:
abort(400)
name = request.json.get('name', item[0]['name'])
value = request.json.get('value', item[0]['value'])
if type(value) is not int:
abort(400)
item[0]['name'] = name
item[0]['value'] = value
return jsonify({'item': item[0]}), 200
@app.route('/api/v1.0/items/<int:id>', methods=['DELETE'])
def delete_item(id):
item = _get_item(id)
if len(item) == 0:
abort(404)
items.remove(item[0])
return jsonify({}), 204
if __name__ == '__main__':
app.run(debug=True)