-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
86 lines (73 loc) · 2.43 KB
/
api.py
File metadata and controls
86 lines (73 loc) · 2.43 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
from flask import Flask, request, jsonify
import psycopg2, time
app = Flask(__name__)
def get_connection():
for _ in range(15):
try:
return psycopg2.connect(
dbname="facts-db", user="postgres", password="postgres", host="db", port="5432"
)
except psycopg2.OperationalError:
time.sleep(3)
raise Exception("Couldn't connect to the database!")
def create_table():
connection = get_connection()
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS facts (id SERIAL PRIMARY KEY, content TEXT NOT NULL);")
connection.commit()
cursor.close()
connection.close()
@app.route("/")
def home():
return "Welcome to Facts API!"
@app.route("/facts", methods=["GET"])
def list_facts():
connection = get_connection()
cursor = connection.cursor()
cursor.execute("SELECT * FROM facts ORDER BY id")
rows = cursor.fetchall()
cursor.close()
connection.close()
res = []
for row in rows:
res.append({"id": row[0], "content": row[1]})
return jsonify(res)
@app.route("/facts", methods=["POST"])
def add_fact():
data = request.get_json()
content = data.get("content")
if not content:
return jsonify("Content missing")
connection = get_connection()
cursor = connection.cursor()
cursor.execute("INSERT INTO facts (content) VALUES (%s) RETURNING id", (content,))
id = cursor.fetchone()[0]
connection.commit()
cursor.close()
connection.close()
return jsonify({"id": id, "content": content})
@app.route("/facts/<int:id>", methods=["DELETE"])
def delete_fact(id):
connection = get_connection()
cursor = connection.cursor()
cursor.execute("DELETE FROM facts WHERE id = %s RETURNING id", (id,))
deleted = cursor.fetchone()
connection.commit()
cursor.close()
connection.close()
if deleted:
return jsonify(f"Deleted fact with id: {id}")
else:
return jsonify("Fact not found")
@app.route("/facts/stats", methods=["GET"])
def stats():
connection = get_connection()
cursor = connection.cursor()
cursor.execute("SELECT COUNT(*), MAX(id), MIN(id) FROM facts")
count, max_id, min_id = cursor.fetchone()
cursor.close()
connection.close()
return jsonify({"number_facts": count, "highest_id": max_id, "lowest_id": min_id})
if __name__ == "__main__":
create_table();
app.run(host="0.0.0.0", port="5000")