import os import psycopg2 from flask import Flask, jsonify, request, abort app = Flask(__name__) def get_conn(): return psycopg2.connect(os.environ["DATABASE_URL"]) @app.route("/api/notes", methods=["GET"]) def get_notes(): with get_conn() as conn, conn.cursor() as cur: cur.execute("SELECT id, content, created_at FROM notes ORDER BY created_at DESC") rows = cur.fetchall() return jsonify([{"id": r[0], "content": r[1], "created_at": r[2].isoformat()} for r in rows]) @app.route("/api/notes", methods=["POST"]) def add_note(): data = request.get_json() content = (data or {}).get("content", "").strip() if not content: abort(400, "content required") with get_conn() as conn, conn.cursor() as cur: cur.execute("INSERT INTO notes (content) VALUES (%s) RETURNING id, content, created_at", (content,)) row = cur.fetchone() conn.commit() return jsonify({"id": row[0], "content": row[1], "created_at": row[2].isoformat()}), 201 @app.route("/api/notes/", methods=["DELETE"]) def delete_note(note_id): with get_conn() as conn, conn.cursor() as cur: cur.execute("DELETE FROM notes WHERE id = %s", (note_id,)) conn.commit() return "", 204 if __name__ == "__main__": app.run(host="0.0.0.0", port=5000)