Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 37 ยท Projects and Practice

Project: Flask API with Postgres

Build and deploy a small Flask notes API on Heroku with gunicorn, a Procfile, Postgres via DATABASE_URL, a release-phase migration and a smoke test. Runs locally with SQLite stand-ins.

In this project you take a tiny Flask API from an empty folder to a running Heroku app with a database. You will write the code, the Procfile and the dependency files, then walk through the deploy commands. The Heroku part cannot run on this site, so the deploy steps are read-only; the application logic is real Python that you can run in the editor, using SQLite in memory as a stand-in for Postgres, and a fake request object instead of a web server.

The plan

flowchart LR
    A["Write app.py"] --> B["Procfile + requirements.txt"]
    B --> C["git init, commit"]
    C --> D["heroku create"]
    D --> E["addons:create postgres"]
    E --> F["git push heroku main"]
    F --> G["release phase: migrate"]
    G --> H["smoke test with curl"]

Each step is small; the order matters because the database must exist before the release phase runs.

Project layout

TEXT
notes-api/
  app.py
  schema.sql
  requirements.txt
  Procfile
  .gitignore

requirements.txt:

TEXT
Flask>=3.0
gunicorn>=22.0
psycopg[binary]>=3.1

Heroku's Python buildpack detects the project from this file, installs the dependencies and picks a Python version (set it in a .python-version file, for example 3.13, or follow the current buildpack docs; older projects used runtime.txt).

Procfile (no file extension, capital P):

TEXT
web: gunicorn app:app --bind 0.0.0.0:$PORT --workers 2
release: python migrate.py

web is the process that gets HTTP traffic. release runs before each new release goes live (pipelines explained why that matters). Add .gitignore with __pycache__/, .venv/ and .env.

The application logic

A real app.py reads DATABASE_URL, connects with psycopg, and defines routes with Flask. To keep this lesson runnable we separate the logic into small functions over a generic DB-API connection, which works with SQLite here and Postgres on Heroku (placeholders differ: SQLite uses ?, psycopg uses %s; a thin helper hides this).

Python Notes API logic on SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Expected behavior: two notes are created (statuses 201), the empty title is rejected with 400, listing shows 2 notes, and unknown ids return 404. The functions return (status, body) pairs; the Flask routes would simply call them:

Python
from flask import Flask, request, jsonify
import os

app = Flask(__name__)

@app.get("/health")
def health():
    return {"status": "ok"}

@app.post("/notes")
def post_note():
    status, body = create_note(get_conn(), request.get_json(silent=True) or {})
    return jsonify(body), status

get_conn() would open a connection using os.environ["DATABASE_URL"] (connections). A /health route gives the router and your uptime checker a cheap target.

The migration script

migrate.py runs in the release phase. It reads schema.sql and applies it. Keep it idempotent (safe to run repeatedly) with CREATE TABLE IF NOT EXISTS, and backward compatible with the previous release.

Python Idempotent migrations with a version table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first run applies versions 1, 2 and 3; the second applies nothing. Every release runs the script, so it must be safe to repeat. For a bigger project use a migration tool (Alembic, Flask-Migrate) instead of hand-rolled lists.

Deploy commands

Terminal
git init
git add .
git commit -m "Notes API"
heroku create notes-api-demo
heroku addons:create heroku-postgresql:essential-0
git push heroku main
heroku ps
heroku logs --tail

(The app name must be globally unique, so choose your own. If your default branch is called something other than main, push with git push heroku your-branch:main.) During the push, the Python buildpack installs requirements, the release phase runs migrate.py, and the web dyno starts. Open the app with heroku open, or test from a terminal:

Terminal
curl -s https://notes-api-demo.herokuapp.com/health
curl -s -X POST https://notes-api-demo.herokuapp.com/notes -H "Content-Type: application/json" -d '{"title":"First"}'
curl -s https://notes-api-demo.herokuapp.com/notes

Use the URL that heroku create printed; modern apps have a random suffix in the host name.

SQLAlchemy note

If you use SQLAlchemy instead of raw psycopg, rewrite the scheme as shown in the connections lesson, and keep the pool small.

Smoke test as code

After each deploy, a tiny script can check the app with a few requests. Here is the logic, run against a fake client (a stand-in for requests calling your URL).

Python Smoke test against a fake client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Extensions to try

  • Add authentication with a token read from a config var.
  • Add a GET /notes?q= search using ILIKE in Postgres.
  • Put the project into a pipeline with staging and production and add Heroku CI (CI).
  • Add a custom domain with automated certificates (domains).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the purpose of the release process type in the Procfile?

    The release phase runs on every release; if it fails, the release is not created.
  2. 2. Why must migration scripts be idempotent?

    The release command runs each time, so already applied changes must be skipped.
  3. 3. Which part of the gunicorn command makes the app listen on the right port?

    Heroku assigns the port in the PORT environment variable; the server must bind to it.
  4. 4. Where does the app get its database URL?

    The Postgres add-on sets DATABASE_URL, which the code reads at start-up.

Summary

  • A Heroku Python app needs requirements.txt, a Procfile with web (and optionally release), and port binding to $PORT.
  • Keep logic in testable functions; read DATABASE_URL from the environment.
  • Use idempotent, backward-compatible migrations in the release phase.
  • Finish every deploy with a smoke test.

Next: Project: Node App with a Pipeline