Metadata-Version: 2.4
Name: supabase
Version: 3.0.0a2
Summary: Supabase client for Python.
Author: Joel Lee, Leon Fedden, Daniel Reinón García, Leynier Gutiérrez González, Anand, Andrew Smith
Author-email: Joel Lee <joel@joellee.org>, Leon Fedden <leonfedden@gmail.com>, Daniel Reinón García <danielreinon@outlook.com>, Leynier Gutiérrez González <leynier41@gmail.com>, Andrew Smith <a.smith@silentworks.co.uk>
License-Expression: MIT
License-File: LICENSE
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Operating System :: OS Independent
Requires-Dist: realtime==3.0.0a2
Requires-Dist: supabase-functions==3.0.0a2
Requires-Dist: storage3==3.0.0a2
Requires-Dist: supabase-auth==3.0.0a2
Requires-Dist: supabase-utils[httpx]==3.0.0a2
Requires-Dist: postgrest==3.0.0a2
Requires-Dist: yarl>=1.22.0
Requires-Dist: supabase-utils[aiohttp] ; extra == 'aiohttp'
Requires-Dist: storage3[iceberg]==3.0.0a2 ; extra == 'iceberg'
Maintainer: Leonardo Santiago
Maintainer-email: Leonardo Santiago <leonardo.santiago@supabase.io>
Requires-Python: >=3.12
Project-URL: homepage, https://github.com/supabase/supabase-py
Project-URL: repository, https://github.com/supabase/supabase-py
Project-URL: documentation, https://supabase.com/docs/reference/python/introduction
Project-URL: changelog, https://github.com/supabase/supabase-py/tree/main/CHANGELOG.md
Provides-Extra: aiohttp
Provides-Extra: iceberg
Description-Content-Type: text/markdown

# `supabase-py`

Python client for [Supabase](https://supabase.com).

Documentation:
[supabase.com/docs](https://supabase.com/docs/reference/python/introduction)

## Installation

Requires Python 3.12 or newer.

```bash
pip install supabase
# or
uv add supabase
# or
conda install -c conda-forge supabase
```

Requests go through httpx. For aiohttp, install `supabase[aiohttp]` and use
`create_async_client` from `supabase.aiohttp`.

## Supabase Service Compatibility

The SDK supports the latest release of each Supabase service, unless a lowest
version is listed below. Older releases work on a best-effort basis. When you
self-host, upgrade your services along with the SDK.

| Service                                                        | Package                                                             | Lowest supported version |
| -------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------ |
| [Auth](https://github.com/supabase/auth/releases)              | [`supabase_auth`](https://pypi.org/project/supabase_auth)           | Latest release           |
| [Storage](https://github.com/supabase/storage/releases)        | [`storage3`](https://pypi.org/project/storage3)                     | Latest release           |
| [Functions](https://github.com/supabase/edge-runtime/releases) | [`supabase_functions`](https://pypi.org/project/supabase_functions) | Latest release           |
| [PostgREST](https://github.com/PostgREST/postgrest/releases)   | [`postgrest`](https://pypi.org/project/postgrest)                   | Latest release           |
| [Realtime](https://github.com/supabase/realtime/releases)      | [`realtime`](https://pypi.org/project/realtime)                     | Latest release           |

Storage `list()` needs Storage v1.19.0 or newer.

## Create a client

```python
import os

from supabase import create_client

supabase = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"])
```

The URL must use `https`. Plain `http` is only allowed for `localhost`,
`127.0.0.0/8` and `::1`, since it sends keys and sessions in clear text. For any
other host, pass `allow_insecure_http=True`.

Use `create_async_client` for an `AsyncClient`:

```python
import os

from supabase import create_async_client

async with create_async_client(
    os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"]
) as client:
    response = await client.table("countries").select("*").execute()
```

### Options

Settings are keyword arguments. The options class of a service overrides the
global settings for that service. `request_timeout` is in seconds and defaults
to 60.

```python
import os

from supabase import (
    PostgrestClientOptions,
    RetryPolicy,
    StorageClientOptions,
    create_client,
)

supabase = create_client(
    os.environ["SUPABASE_URL"],
    os.environ["SUPABASE_KEY"],
    headers={"x-app": "my-app"},
    request_timeout=30,
    retry=RetryPolicy(max_retries=5),
    postgrest=PostgrestClientOptions(schema="private"),
    storage=StorageClientOptions(request_timeout=120),
)
```

Each service retries failed reads as it specifies. Writes are never retried.

- Database: `PostgrestClientOptions(retry=False)` turns retries off, and
  `.retry(False)` does so for one query.
- Storage: `StorageClientOptions(max_attempts=1)` turns retries off.
- Auth and edge functions: the global `retry` sets the `RetryPolicy`, and
  `RetryPolicy(max_retries=0)` turns retries off.

### Secret keys

A client with a secret key (`sb_secret_...`) or a `service_role` key bypasses
row level security, even after a sign-in. Do not sign users in on it. Use a
client with the publishable key instead.

### Servers

On a server, create one client at startup and call `with_token()` with the JWT
of each request, so row level security applies to that user. It is cheap, does
no I/O and shares the connections of the first client.

```python
import os

from supabase import create_async_client

shared = create_async_client(
    os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"]
)


async def list_todos(access_token: str) -> object:
    client = shared.with_token(access_token)
    response = await client.table("todos").select("*").execute()
    return response.data
```

To verify the token, use `await shared.auth.get_claims(access_token)`.

## Auth

```python
from supabase_auth import SignInWithPassword, SignUpWithPassword

supabase.auth.sign_up(
    SignUpWithPassword.email("someone@example.com", "a-strong-password")
)
supabase.auth.sign_in_with_password(
    SignInWithPassword.email("someone@example.com", "a-strong-password")
)
```

OAuth, SSO, magic links and password resets redirect back to your app with a
`code`. Pass the callback URL to `initialize_from_url` to finish the sign-in:

```python
def callback(url: str) -> None:
    supabase.auth.initialize_from_url(url)
```

## Database

```python
countries = supabase.table("countries")

countries.insert({"name": "Germany"}).execute()
countries.upsert({"name": "Germany", "capital": "Berlin"}).execute()
response = countries.select("*").eq("continent", "Europe").execute()
countries.update({"capital": "Berlin"}).eq("id", 1).execute()
countries.delete().eq("id", 1).execute()
```

Each builder method returns a new query, so a base query can be reused. An
update or delete without a filter raises `ValueError`. Call `all()` to affect
every row on purpose.

### Typed queries

Describe a table with a `Table` subclass to get queries checked by your type
checker and rows decoded into your model:

```python
from typing import NotRequired, TypedDict

from pydantic import BaseModel

from supabase import Column, Table


class CountriesRow(BaseModel):
    id: int
    name: str
    population: int


class CountriesInsert(TypedDict):
    name: str
    population: NotRequired[int]


class CountriesUpdate(TypedDict, total=False):
    name: str
    population: int


class Countries(Table[CountriesRow, CountriesInsert, CountriesUpdate]):
    __tablename__ = "countries"
    id = Column[CountriesRow, int]("id")
    name = Column[CountriesRow, str]("name")
    population = Column[CountriesRow, int]("population")


large: list[CountriesRow] = (
    supabase.select(Countries)
    .where(Countries.population >= 100_000_000)
    .order(Countries.name)
    .execute()
)
ids: list[int] = supabase.select(Countries.id).scalars().execute()
supabase.insert(Countries).values({"name": "Germany"}).execute()
(
    supabase.update(Countries)
    .values({"population": 84_500_000})
    .where(Countries.name == "Germany")
    .execute()
)
supabase.delete(Countries).where(Countries.name == "Germany").execute()
```

`Projection` selects a subset of columns, and `FunctionCall` does the same for
database functions called with `rpc()`.

## Edge Functions

```python
from supabase import FunctionsHttpError

try:
    response = supabase.functions.invoke("hello", body={"name": "World"})
    print(response.json())
except FunctionsHttpError as error:
    print(error.status_code, error.message)
```

`invoke_stream()` reads a streaming response, such as server-sent events, as it
arrives.

## Storage

```python
from pathlib import Path

photos = supabase.storage.from_("photos")

photos.upload("user1/profile.png", Path("profile.png"))
data = photos.download("user1/profile.png")
photos.move("user1/profile.png", "user1/avatar.png")
photos.remove(["user1/avatar.png"])
for page in photos.pages("user1/", with_delimiter=True):
    print(page.folders, page.objects)
```

## Realtime

Only `AsyncClient` has realtime. It connects on the first subscription and keeps
the channels authorized as the session changes.

```python
import os

from supabase import BroadcastMessage, create_async_client

async with create_async_client(
    os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"]
) as client:
    async with client.realtime.channel("room") as channel:
        async for message in channel.messages:
            if isinstance(message, BroadcastMessage):
                print(message.payload)
```

## Errors

Every error inherits from `SupabaseError`:

```python
from supabase import SupabaseAPIError, SupabaseError, SupabaseTransportError

try:
    supabase.table("countries").select("*").execute()
except SupabaseAPIError as error:
    print(error.status_code, error.code, error.message)
except SupabaseTransportError as error:
    print("No response:", error.__cause__)
except SupabaseError as error:
    print(error.message)
```

- `SupabaseAPIError`: the service answered with an error. Its `response` headers
  hold the `sb-request-id` to quote to support.
- `SupabaseTransportError`: no response, for example a timeout. The request may
  still have reached the service.
- Invalid arguments raise the built-in `ValueError` or `TypeError`.

## Logging

All packages log under the `supabase` logger and print nothing until you
configure logging. Logs never contain keys, tokens or bodies.

```python
import logging

logging.basicConfig()
logging.getLogger("supabase").setLevel(logging.DEBUG)
```

Or set `SUPABASE_LOG=debug`. The `httpx` logger logs full URLs at `INFO`, so
raise its level if you log at `INFO` or below.

## Closing the client

Close the client to stop the session refresh and close its connections. An
`http_client` you passed in stays yours to close.

```python
import os

from supabase import create_client

with create_client(
    os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"]
) as supabase:
    supabase.table("countries").select("*").execute()
```

`AsyncClient` works the same with `async with` or `await client.aclose()`.
