-
Notifications
You must be signed in to change notification settings - Fork 9
/
api.py
56 lines (43 loc) · 1.19 KB
/
api.py
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
from flask import Flask, jsonify, abort, make_response
app = Flask(__name__)
# An array that will hold books
books = [
{
"id": 1,
"title": "CS50",
"description": "Intro to CS and art of programming!",
"author": "Harvard",
"borrowed": False
},
{
"id": 2,
"title": "Python 101",
"description": "little python code book.",
"author": "Will",
"borrowed": False
}
]
@app.route("/")
def index():
return "Testing, Flask!"
# get and jsonify the data
@app.route("/bookapi/books")
def get_books():
""" function to get all books """
return jsonify({"Books": books})
# get book by provided 'id'
@app.route("/bookapi/books/<int:book_id>", methods=['GET'])
def get_by_id(book_id):
book = [book for book in books if book['id'] == book_id]
if len(book) == 0:
abort(404)
return jsonify({"Book": books[0]})
#error handling
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({"error": "Not found!"}), 404)
@app.errorhandler(400)
def not_found(error):
return make_response(jsonify({"error": "Bad request!"}), 400)
if __name__ == '__main__':
app.run(debug=True)