Articles

Host a Python FastAPI API with Supabase Auth and Postgres

Keep Supabase Auth and data. Deploy Python separately, use the existing user access token, and verify row-level isolation with two test users.

Updated

Keep Supabase for login and data. Run Python on Gregale when you need a Python library or want to expose a FastAPI route. In this guide, FastAPI checks the existing Supabase session and reads Postgres through the Supabase Data API over HTTPS. The database still decides which rows the signed-in user may see. There’s no database password in the app and nothing to migrate from Supabase.

Get the runnable example on GitHub.

This is for a Python HTTP service alongside your existing Supabase app. Supabase Edge Functions remain a good home for Deno-compatible TypeScript; this is not a drop-in migration for those functions, triggers, or raw SQL connections.

1. Create two test users and an isolated table

Use a disposable Supabase project. Enable its Data API for the public schema. In Authentication, create or sign up two test users, A and B. Get user A’s UUID from Authentication → Users.

Run the following in Supabase’s SQL editor:

sql
-- Run only in a disposable Supabase project. Use a new table.
begin;
create table public.gregale_guide_notes (
  id bigint generated always as identity primary key,
  owner_id uuid not null references auth.users (id),
  title text not null
);
alter table public.gregale_guide_notes enable row level security;
revoke all on public.gregale_guide_notes from anon, authenticated;
grant select on public.gregale_guide_notes to authenticated;
create policy "Users read their own guide notes"
  on public.gregale_guide_notes for select to authenticated
  using ((select auth.uid()) = owner_id);
commit;

-- In the SQL editor, replace the UUID placeholder with test user A's Auth ID.
-- insert into public.gregale_guide_notes (owner_id, title)
-- values ('<USER_A_UUID>'::uuid, 'Gregale Supabase demo');

Uncomment the sample insert and use user A’s UUID. Don’t insert a row for B. The test only grants authenticated users SELECT; row-level security scopes that grant to their own rows.

2. Create the FastAPI app

Create a directory and save the following as main.py:

python
import os
from urllib.parse import urlsplit

import httpx
from fastapi import FastAPI, Header, HTTPException
from fastapi.responses import JSONResponse

app = FastAPI()
NO_STORE = {"Cache-Control": "private, no-store"}


def fail(status: int, detail: str) -> HTTPException:
    headers = dict(NO_STORE)
    if status == 401:
        headers["WWW-Authenticate"] = "Bearer"
    return HTTPException(status, detail, headers=headers)


def get_client() -> httpx.AsyncClient:
    url = os.environ.get("SUPABASE_URL", "").rstrip("/")
    key = os.environ.get("SUPABASE_PUBLISHABLE_KEY", "")
    parsed = urlsplit(url)
    if (parsed.scheme != "https" or not parsed.hostname or parsed.username
            or parsed.password or parsed.path or parsed.query or parsed.fragment
            or not key.startswith("sb_publishable_")):
        raise fail(500, "Set the Supabase HTTPS project URL and publishable key")
    return httpx.AsyncClient(
        base_url=url, headers={"apikey": key}, timeout=5.0, follow_redirects=False
    )


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


@app.get("/my-notes")
async def my_notes(authorization: str | None = Header(default=None)):
    scheme, _, token = (authorization or "").partition(" ")
    if scheme.lower() != "bearer" or not token or len(token) > 8192 or any(c.isspace() for c in token):
        raise fail(401, "A Supabase user access token is required")
    headers = {"Authorization": f"Bearer {token}"}

    try:
        async with get_client() as client:
            user = await client.get("/auth/v1/user", headers=headers)
            if user.status_code in {401, 403}:
                raise fail(401, "Invalid or expired Supabase user access token")
            if user.status_code != 200 or not isinstance(user.json().get("id"), str):
                raise fail(502, "Supabase Auth did not return a user")
            rows = await client.get(
                "/rest/v1/gregale_guide_notes",
                headers=headers,
                params={"select": "title", "order": "id.asc", "limit": "20"},
            )
            if rows.status_code != 200:
                raise fail(502, "Supabase Data API could not read the guide table")
            data = rows.json()
            if not isinstance(data, list):
                raise fail(502, "The notes query did not return a list")
    except (httpx.RequestError, ValueError, AttributeError):
        raise fail(502, "Could not read Supabase") from None

    return JSONResponse({"notes": data}, headers=NO_STORE)

Set requirements.txt to:

text
fastapi==0.141.1
httpx==0.28.1
uvicorn==0.52.1

The Procfile tells the builder how to start the service:

text
web: uvicorn main:app --host 0.0.0.0 --port 8080

Set gregale.yaml to:

yaml
hosting:
  port: 8080
  health: /healthz

The apikey header identifies your application to Supabase. The Authorization header contains the individual user’s access token from Supabase Auth, and is forwarded to both Auth and the Data API. Use your project’s publishable key, which begins with sb_publishable_. Don’t use an sb_secret_ key or the legacy service_role key here: those keys bypass RLS.

3. Deploy the Python service

Install the Gregale CLI and sign in using the quickstart. Run these commands from the directory containing main.py. Replace the project URL and key. These are the Supabase project’s public identifiers, not the user’s bearer token or the Gregale API key.

bash
APP="supabase-fastapi-demo"
gregale deploy --create-only --name "$APP"
gregale env set --app "$APP" \
  SUPABASE_URL="https://YOUR_PROJECT.supabase.co" \
  SUPABASE_PUBLISHABLE_KEY="sb_publishable_REPLACE_ME"
gregale deploy --name "$APP"
gregale app update "$APP" --visibility public --public-auth open --no-require-authn

Copy the actual HTTPS URL printed by the deployment. This recipe uses a public Gregale ingress because FastAPI validates the Supabase bearer token at the application route. It doesn’t provision Gregale-managed Postgres or connect to a raw database port.

4. Verify that two users see different results

Use short-lived access tokens from two signed-in test sessions in your existing Supabase client. For a JavaScript integration, supabase.auth.getSession() provides the current session’s access_token; never substitute the project publishable key or a refresh token for it. Test in a private terminal and don’t share point-in-time tokens.

bash
APP_URL="https://YOUR_DEPLOYED_HOST"
# A real application route must reject unauthenticated traffic.
curl -isS "$APP_URL/my-notes"
# Expected: 401 and WWW-Authenticate: Bearer.

read -r -s -p 'Test user A access token: ' TOKEN_A; printf '\n'
read -r -s -p 'Test user B access token: ' TOKEN_B; printf '\n'
curl -fsS -H "Authorization: Bearer $TOKEN_A" "$APP_URL/my-notes"
printf '\n'
# Expected: {"notes":[{"title":"Gregale Supabase demo"}]}
curl -fsS -H "Authorization: Bearer $TOKEN_B" "$APP_URL/my-notes"
printf '\n'
# Expected: {"notes":[]}
unset TOKEN_A TOKEN_B

A healthy deploy by itself does not prove the database query worked. Both signed-in requests must return HTTP 200 with the expected JSON; user B must never see A’s note. The local sample can test routing against a mock upstream, but only this two-user test against an actual Supabase project proves the table’s live policies.

Troubleshooting

  • 401: Send a current access token issued by this same Supabase project. A publishable key isn’t a user token.
  • 502 from the notes query: Check that the Data API is enabled, the public schema is exposed, the table exists, and authenticated has SELECT. Don’t fix this by disabling RLS or swapping in a secret key.
  • 200 with no notes for user A: Check the seed row’s owner_id against that test user’s UUID.
  • A browser on another origin is blocked: The curl checks don’t set CORS policy. If you call the API directly from a browser, configure the exact frontend origin and allow the Authorization header; alternatively call it through your existing frontend’s server. Don’t open CORS to all origins to fix an auth issue.

When finished, remove the disposable app and test project from their dashboards if you no longer need them. Keep real user tokens and records out of the demo.

Testing a schema change in a PR? See how to bind a FastAPI preview to an isolated Supabase branch.

Questions

Do I need to move my Supabase database?

No. This example queries the Supabase Data API over HTTPS using the signed-in user’s access token.

Should the FastAPI service use a Supabase service role key?

No. Use the project publishable key and the user access token so row-level security can enforce the user’s permissions.