---
title: "Store the requests in the database from Python"
summary: "Connect Python to PostgreSQL with psycopg2: create a table, insert with safe parameters, read rows back, and store each API request."
url: "https://lab.blue-unlimited.com/en/learn/postgresql-from-python"
language: en
updated: "2026-10-25"
---

[Home](https://lab.blue-unlimited.com/en) / [Learn](https://lab.blue-unlimited.com/en/learn) / Store the requests in the database from Python

**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 time**: 10 min
- **Tested on**: 2026-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](https://lab.blue-unlimited.com/en/learn/first-web-api-with-flask), with its virtual environment active, add the database library and try it in a small script `db_test.py`:

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

```python
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

- [AI Workshops](https://lab.blue-unlimited.com/en/ai-workshops) (More time, Internal): AI agents and skills built around your processes and your voice, and your team trained to work with them safely.

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

[Let's chat](https://lab.blue-unlimited.com/en/contact?cta=chat&item=postgresql-from-python)
