-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_service.py
More file actions
79 lines (66 loc) · 2.41 KB
/
api_service.py
File metadata and controls
79 lines (66 loc) · 2.41 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
from flask import Flask, jsonify, abort, make_response, request
from time import strftime
app = Flask(__name__)
# test
nowTime = strftime("%Y-%m-%d %H:%M")
books = [
{
'id': 1,
'title': u'first',
'description': u'first element',
'create_date': nowTime
},
{
'id': 2,
'title': u'second',
'description': u'second element',
'create_date': nowTime
}
]
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}),404)
@app.route('/api/index', methods=['GET'])
def get_books():
return jsonify({'books': books})
@app.route('/api/books/<int:book_id>', methods=['GET'])
def get_book(book_id):
book = [book for book in books if book['id'] == book_id]
if len(book) == 0: abort(404)
return jsonify({'book': book[0]})
@app.route('/api/books/', methods=['POST'])
def create_book():
nowTime = strftime("%Y-%m-%d %H:%M")
if not request.json or not 'title' in request.json: abort(400)
# check if title or description we are trying to put are already present
title = request.json['title']
description = request.json['description']
if any(d['title'] == title for d in books) or any(d['description'] == description for d in books):
print("error, the given title or description is already present")
abort(400)
# check if title or description we are trying to put are already present
book = {
'id': books[-1]['id'] + 1,
'title': request.json['title'],
'description': request.json.get('description', ""),
'creation_date': nowTime
}
books.append(book)
return jsonify({'book:': book}), 201
@app.route('/api/books/<int:book_id>', methods=['PUT'])
def update_book(book_id):
book = [book for book in books if book['id'] == book_id]
if len(book) == 0: abort(404) # requested book id not found
if not request.json:
abort(400)
book[0]['title'] = request.json.get('title', book[0]['title'])
book[0]['description'] = request.json.get('description', book[0]['description'])
return jsonify({'book': book[0]})
@app.route('/api/books/<int:book_id>', methods=['DELETE'])
def delete_book(book_id):
book = [book for book in books if book['id'] == book_id]
if len(book) == 0: abort(404) # requested book id not found
books.remove(book[0])
return jsonify({'book': book[0]})
if __name__ == '__main__':
app.run(debug=True)