Connecting to PostgreSQL / Supabase
Two ways to use Supabase from Python
- supabase-py (
pip install supabase): the official client. It talks to Supabase's REST API, respects Row Level Security, and is easiest for scripts and apps. - Direct PostgreSQL with
psycopg(pip install "psycopg[binary]"): full SQL power, used by backends and data scripts. Get the connection string from the Supabase dashboard (Connect button).
Keep secrets out of code 🔐
Never write passwords or keys in source files. Put them in environment variables or a .env file (with python-dotenv) and add .env to .gitignore.
- Use the anon key in apps. It's limited by Row Level Security.
- The service_role key bypasses all security: use it only on servers, never in an app.
Good habits
- Always use parameters (
%sin psycopg) instead of f-strings in SQL. - Use
withblocks so connections close and transactions commit or roll back. - Add
LIMITwhile exploring big tables.
💻 Needs internet access and your own Supabase project, so run it on a computer.
Example
import os
# ── Option 1: Supabase client (pip install supabase) ──
from supabase import create_client
supabase = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_ANON_KEY"])
rows = (
supabase.table("python_course")
.select("module_title, topic")
.order("id")
.limit(5)
.execute()
)
print(rows.data)
# ── Option 2: direct SQL (pip install "psycopg[binary]") ──
import psycopg
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT topic FROM python_course WHERE module_id = %s ORDER BY id",
(1,),
)
for (topic,) in cur.fetchall():
print(topic)