Skip to content
Blue Unlimited Lab
Guide · Databases

Store the requests in the database from Python

Connect Python to PostgreSQL with psycopg2: create a table, insert with safe parameters, read rows back, and store each API request.

Reading time10 min
Tested on2026-10-25

Connect Python to PostgreSQL with psycopg2: create a table, insert with safe parameters, read rows back, and store each API request.

In plain words

Until now the diary was a paper file. Now every request is written into the filing clerk's cabinet, in a table with labelled columns, so you can ask "show me all the requests for the word hello".

Try it yourself

In the ~/api folder of Your first web API with Flask, with its virtual environment active, add the database library and try it in a small script db_test.py:

cd ~/api && . .venv/bin/activate
pip install psycopg2-binary
import psycopg2

conn = psycopg2.connect(host="localhost", dbname="appdb", user="app", password="app")
with conn, conn.cursor() as cur:
    cur.execute("create table if not exists requests (id serial primary key, ts timestamptz not null default now(), original text not null, upper text not null)")
    cur.execute("insert into requests (original, upper) values (%s, %s)", ("hello", "HELLO"))
    cur.execute("select id, original, upper from requests order by id desc limit 5")
    print(cur.fetchall())

Run python db_test.py, then check from the shell: PGPASSWORD=app psql -h localhost -U app -d appdb -c 'select * from requests'.

A step further

Look at %s: the values are passed separately from the SQL text. Never build SQL by pasting text together ("... values ('" + text + "')"): someone could send text that is SQL and run commands on your database. That attack is called SQL injection, and the separate parameters prevent it.

The with block saves (commits) when it ends well and rolls back when it fails.

Put the insert into your route, and create the table when the program starts (in the if __name__ block), not in a decorator: Flask 3 removed before_first_request, so old tutorials that use it fail with an AttributeError.

How it works in real projects

The application connects as its own limited role, with the password from the environment (see the secrets article), never from the code. Changes to the tables are written as numbered scripts (migrations) kept in Git, not typed by hand.

Tools in this guide

Not sure where to start? Tell us what's slowing you down. Let's chat.

Let's chat

Content CMS · 2026-11-24 13:36 UTC · App f73c8ed