From eed87fc7d6eb738496d2c6c4d5786fbb6afb7049 Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Wed, 11 Nov 2026 10:38:21 +0100 Subject: [PATCH 1/3] docs: update the READMEs to the v3 API and type-check their snippets in CI --- .github/scripts/check_markdown_snippets.py | 198 +++++++++++++++++++++ .github/workflows/ci.yml | 24 ++- AGENTS.md | 1 + MIGRATION.md | 3 + Makefile | 7 +- README.md | 3 +- src/auth/README.md | 181 +++++++++++-------- src/functions/README.md | 82 +++++---- src/postgrest/README.md | 34 ++-- src/realtime/README.md | 35 +++- src/storage/README.md | 53 ++++-- src/supabase/README.md | 72 ++++++-- 12 files changed, 522 insertions(+), 171 deletions(-) create mode 100644 .github/scripts/check_markdown_snippets.py diff --git a/.github/scripts/check_markdown_snippets.py b/.github/scripts/check_markdown_snippets.py new file mode 100644 index 000000000..c5ca621f0 --- /dev/null +++ b/.github/scripts/check_markdown_snippets.py @@ -0,0 +1,198 @@ +"""Type-check the Python snippets of the Markdown files with pyrefly. + +Every ```python block in a Markdown file tracked by git, apart from the +changelogs, is checked against the installed workspace packages, so the READMEs +and MIGRATION.md cannot show code that does not match the API. + +A block is the body of an async function, so it can use `await` and +`async with`. It imports what it uses, as the code a user copies has to. The +names a file's snippets share, such as the client its README creates once, are +declared in PRELUDES. A block fenced as ```python skip is not checked, for +example v2 code shown as "before" or a fragment that only shows a shape. + +Run it from the repository root in an environment with every package and extra +installed: + + uv sync --all-packages --all-extras + uv run python .github/scripts/check_markdown_snippets.py +""" + +import json +import os +import re +import subprocess +import sys +import tempfile +from dataclasses import dataclass +from pathlib import Path + +LANGUAGES = {"python", "py", "python3"} +FENCE = re.compile(r"^(?P\s*)(?P`{3,}|~{3,})(?P.*)$") + +PRELUDES = { + "MIGRATION.md": [ + "from supabase import Client", + "from supabase_auth import SyncSupportedStorage", + "client: Client", + "url: str", + "key: str", + "my_storage: SyncSupportedStorage", + "account_id: str", + ], + "src/supabase/README.md": [ + "from supabase import Client", + "supabase: Client", + ], + "src/auth/README.md": [ + "from supabase_auth import SyncSupabaseAuthClient", + "client: SyncSupabaseAuthClient", + ], + "src/postgrest/README.md": [ + "from postgrest import AsyncPostgrestClient", + "client: AsyncPostgrestClient", + ], + "src/realtime/README.md": [ + "from realtime import RealtimeClient", + "client: RealtimeClient", + ], + "src/storage/README.md": [ + "from storage3 import AsyncStorageClient", + "storage_client: AsyncStorageClient", + ], +} + +PYREFLY_CONFIG = """\ +python-version = "3.12" + +[errors] +deprecated = "error" +""" + + +@dataclass(frozen=True) +class Snippet: + markdown: str + first_line: int + lines: list[str] + + +def markdown_files() -> list[str]: + output = subprocess.run( + ["git", "ls-files", "--cached", "--others", "--exclude-standard", "*.md"], + check=True, + capture_output=True, + text=True, + ).stdout + return sorted( + path + for path in output.splitlines() + if Path(path).name != "CHANGELOG.md" and not Path(path).is_symlink() + ) + + +def python_snippets(markdown: str) -> list[Snippet]: + snippets: list[Snippet] = [] + lines = Path(markdown).read_text(encoding="utf-8").splitlines() + index = 0 + while index < len(lines): + opening = FENCE.match(lines[index]) + index += 1 + if opening is None: + continue + fence = opening["fence"] + indent = len(opening["indent"]) + words = opening["info"].split() + first_line = index + 1 + body: list[str] = [] + while index < len(lines): + closing = FENCE.match(lines[index]) + index += 1 + if ( + closing is not None + and closing["fence"].startswith(fence) + and not closing["info"].strip() + ): + break + body.append(lines[index - 1][indent:]) + if words and words[0] in LANGUAGES and "skip" not in words[1:]: + snippets.append(Snippet(markdown, first_line, body)) + return snippets + + +def module_source(snippet: Snippet) -> tuple[str, int]: + """Return the module that wraps the snippet and the number of lines before + the snippet's first line.""" + header = [ + *PRELUDES.get(snippet.markdown, []), + "", + "", + "async def _snippet() -> None:", + ] + body = [f" {line}" if line.strip() else "" for line in snippet.lines] + if not any(line.strip() for line in body): + body = [" pass"] + return "\n".join([*header, *body, ""]), len(header) + + +def main() -> int: + snippets = [ + snippet + for markdown in markdown_files() + for snippet in python_snippets(markdown) + ] + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "pyrefly.toml").write_text(PYREFLY_CONFIG, encoding="utf-8") + modules: dict[str, tuple[Snippet, int]] = {} + for number, snippet in enumerate(snippets): + source, header_lines = module_source(snippet) + module = root / f"snippet_{number}.py" + module.write_text(source, encoding="utf-8") + modules[module.name] = (snippet, header_lines) + + result = subprocess.run( + [ + sys.executable, + "-m", + "pyrefly", + "check", + "--config", + str(root / "pyrefly.toml"), + "--output-format", + "json", + *(str(root / name) for name in modules), + ], + check=False, + capture_output=True, + text=True, + ) + try: + errors = json.loads(result.stdout)["errors"] + except (json.JSONDecodeError, KeyError): + sys.stderr.write(result.stdout + result.stderr) + return result.returncode or 1 + + located: list[tuple[str, int, str]] = [] + for error in errors: + snippet, header_lines = modules[Path(error["path"]).name] + line = snippet.first_line + error["line"] - header_lines - 1 + located.append( + (snippet.markdown, line, f"{error['description']} [{error['name']}]") + ) + + annotate = os.environ.get("GITHUB_ACTIONS") == "true" + for markdown, line, message in sorted(located): + if annotate: + print(f"::error file={markdown},line={line}::{message}") + else: + print(f"{markdown}:{line}: {message}") + + if errors: + print(f"{len(errors)} errors in {len(snippets)} Python snippets.") + return 1 + print(f"All {len(snippets)} Python snippets type-check.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5b25e481a..028519bf4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,6 +91,24 @@ jobs: done check supabase --extra aiohttp + markdown-snippets: + name: Markdown snippets + runs-on: ubuntu-latest + steps: + - name: Clone Repository + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + + - name: Install uv + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + python-version: "3.12" + + - name: Install dependencies + run: uv sync --frozen --all-packages --all-extras + + - name: Type-check the Python snippets of the Markdown files + run: uv run --frozen --no-sync python .github/scripts/check_markdown_snippets.py + test: name: py${{ matrix.python-version }} | ${{ matrix.package }}${{ matrix.resolution == 'lowest-direct' && ' | lowest' || '' }} needs: changes @@ -192,7 +210,7 @@ jobs: ci-passed: name: CI passed - needs: [changes, lint, import-without-httpx, test] + needs: [changes, lint, import-without-httpx, markdown-snippets, test] if: ${{ always() }} runs-on: ubuntu-latest steps: @@ -201,10 +219,12 @@ jobs: CHANGES: ${{ needs.changes.result }} LINT: ${{ needs.lint.result }} IMPORTS: ${{ needs.import-without-httpx.result }} + SNIPPETS: ${{ needs.markdown-snippets.result }} TEST: ${{ needs.test.result }} run: | - echo "changes=$CHANGES lint=$LINT imports=$IMPORTS test=$TEST" + echo "changes=$CHANGES lint=$LINT imports=$IMPORTS snippets=$SNIPPETS test=$TEST" [ "$CHANGES" = success ] && [ "$LINT" = success ] && [ "$IMPORTS" = success ] \ + && [ "$SNIPPETS" = success ] \ && { [ "$TEST" = success ] || [ "$TEST" = skipped ]; } release-please: diff --git a/AGENTS.md b/AGENTS.md index 4d6ba75d4..bcc237713 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,7 @@ Setup and commands: [README.md § Local Development](README.md#local-development - `make .tests` runs pyrefly and pytest. For `auth`, `postgrest`, `storage` and `realtime`, pytest first starts Docker / Supabase CLI infra; `make stop-infra` when done. - Fast loop for tests that need no infra: from `src/`, `uv run --frozen --package pytest tests/.py`. - Code must run on Python 3.12, CI tests 3.12 to 3.15 ([ci.yml](.github/workflows/ci.yml)). +- `make snippets` type-checks every `python` code block of the Markdown files, apart from the changelogs, against the workspace. A block is the body of an async function and imports what it uses. Names a file's blocks share, like the client its README creates, are declared in `PRELUDES` of [check_markdown_snippets.py](.github/scripts/check_markdown_snippets.py). Fence v2 code shown as "before" as `python skip`. ## Public API diff --git a/MIGRATION.md b/MIGRATION.md index 5dbbdb160..4d8ca2aa6 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -66,6 +66,9 @@ Names that mirror a wire format keep their wire spelling, for example the JWT cl `ClientOptions`, `AsyncClientOptions`, their v2 names `SyncClientOptions` and `AClientOptions`, and the `supabase.lib.client_options` module are removed. `create_client`, `create_async_client`, `Client`, `AsyncClient` and their `create` methods take the settings as keyword-only arguments. Settings that apply to every service are arguments of their own. The settings of one service are grouped in an options class, passed in the argument named after the service. ```python +from supabase import AuthClientOptions, PostgrestClientOptions, StorageClientOptions +from supabase.httpx import create_client + client = create_client( url, key, diff --git a/Makefile b/Makefile index 2228b36e2..1e337314c 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ help:: @echo "Available commands" @echo " help -- (default) print this message" -ci: ruff $(call FORALL_PKGS,tests) +ci: ruff snippets $(call FORALL_PKGS,tests) help:: @echo " ci -- Run tests for all packages, the same way as CI does" @@ -30,6 +30,11 @@ help:: @echo " stop-infra -- Stop all infra used by tests." @echo " NOTE: run this command to ensure all containers are stopped after tests" +snippets: + uv run --all-packages --all-extras python .github/scripts/check_markdown_snippets.py +help:: + @echo " snippets -- Type-check the Python snippets of the Markdown files" + pyrefly: $(call FORALL_PKGS,pyrefly) help:: @echo " pyrefly -- Run pyrefly on all packages" diff --git a/README.md b/README.md index 3a3b8b94b..95f71143b 100644 --- a/README.md +++ b/README.md @@ -12,11 +12,12 @@ Python monorepo for all [Supabase](https://supabase.com) libraries. > See [CONTRIBUTING.md](CONTRIBUTING.md) for details. - [supabase](src/supabase/README.md) -- [realtime-py](src/realtime/README.md) +- [realtime](src/realtime/README.md) - [supabase_functions](src/functions/README.md) - [storage3](src/storage/README.md) - [postgrest](src/postgrest/README.md) - [supabase_auth](src/auth/README.md) +- [supabase_utils](src/utils/README.md) Relevant links: diff --git a/src/auth/README.md b/src/auth/README.md index 0687fede8..955b65819 100644 --- a/src/auth/README.md +++ b/src/auth/README.md @@ -1,37 +1,37 @@ -# Auth-py +# supabase_auth -[![CI](https://github.com/supabase-community/gotrue-py/actions/workflows/ci.yml/badge.svg)](https://github.com/supabase-community/gotrue-py/actions/workflows/ci.yml) -[![Python](https://img.shields.io/pypi/pyversions/gotrue)](https://pypi.org/project/gotrue) -[![Version](https://img.shields.io/pypi/v/gotrue?color=%2334D058)](https://pypi.org/project/gotrue) +[![CI](https://github.com/supabase/supabase-py/actions/workflows/ci.yml/badge.svg)](https://github.com/supabase/supabase-py/actions/workflows/ci.yml) +[![Python](https://img.shields.io/pypi/pyversions/supabase_auth)](https://pypi.org/project/supabase_auth) +[![Version](https://img.shields.io/pypi/v/supabase_auth?color=%2334D058)](https://pypi.org/project/supabase_auth) -This is a Python port of the [supabase js gotrue client](https://github.com/supabase/gotrue-js). The current state is that there is a features parity but with small differences that are mentioned in the section **Differences to the JS client**. As of December 14th, we renamed to repo from `gotrue-py` to `auth-py` to mirror the changes in the JavaScript library. +Python client for [Supabase Auth](https://github.com/supabase/auth), the Python counterpart of [`@supabase/auth-js`](https://github.com/supabase/supabase-js/tree/master/packages/core/auth-js). Most users use it through the [`supabase`](../supabase/README.md) package, as `client.auth`. ## Installation -The package can be installed using pip, uv or poetry: +The package needs an HTTP client adapter. The examples below use httpx: ### Pip ```bash -pip install supabase_auth +pip install supabase_auth "supabase_utils[httpx]" ``` - ### Uv ```bash -uv add supabase_auth +uv add supabase_auth "supabase_utils[httpx]" ``` ### Poetry ```bash -poetry add supabase_auth +poetry add supabase_auth "supabase_utils[httpx]" ``` +Use `supabase_utils[aiohttp]` instead to run the async client on aiohttp. + ## Features -- Full feature parity with the JavaScript client - Support for both synchronous and asynchronous operations - MFA (Multi-Factor Authentication) support - OAuth and SSO integration @@ -44,21 +44,17 @@ poetry add supabase_auth ## Differences to the JS client -It should be noted there are differences to the [JS client](https://github.com/supabase/gotrue-js). If you feel particulaly strongly about them and want to motivate a change, feel free to make a GitHub issue and we can discuss it there. - -Firstly, feature pairity is not 100% with the [JS client](https://github.com/supabase/gotrue-js). In most cases we match the methods and attributes of the [JS client](https://github.com/supabase/gotrue-js) and api classes, but is some places (e.g for browser specific code) it didn't make sense to port the code line for line. - -There is also a divergence in terms of how errors are raised. In the [JS client](https://github.com/supabase/gotrue-js), the errors are returned as part of the object, which the user can choose to process in whatever way they see fit. In this Python client, we raise the errors directly where they originate, as it was felt this was more Pythonic and adhered to the idioms of the language more directly. +Methods and attributes follow the JS client, but browser specific code is not ported. -In JS we return the error, but in Python we just raise it. +Errors are raised where they originate instead of being returned next to the data, since that is the idiomatic way in Python. Where JS returns the error: ```js -const { data, error } = client.sign_up(...) +const { data, error } = await supabase.auth.signUp({ email, password }) ``` -The other key difference is we do not use pascalCase to encode variable and method names. Instead we use the snake_case convention adopted in the Python language. +Python raises a subclass of `AuthError`, which you catch with `try`/`except`. -Also, the `supabase_auth` library for Python parses the date-time string into `datetime` Python objects. The [JS client](https://github.com/supabase/gotrue-js) keeps the date-time as strings. +Names use the Python snake_case convention instead of camelCase, and date-time strings are parsed into `datetime` objects. ## Supabase Service Compatibility @@ -68,82 +64,110 @@ If you self-host Supabase Auth, we recommend upgrading to the latest release whe ## Usage -The library provides both synchronous and asynchronous clients. Here are some examples: +The client takes the URL of the auth service, `https://.supabase.co/auth/v1` for a Supabase project, and the HTTP session it sends its requests with. Leaving the client's context manager closes the session and stops the automatic token refresh. ### Synchronous Client ```python -from supabase_auth import SyncGoTrueClient - -headers = { - "apiKey": "my-mega-awesome-api-key", - # ... any other headers you might need. -} -client: SyncGoTrueClient = SyncGoTrueClient(url="www.genericauthwebsite.com", headers=headers) - -# Sign up with email and password -user = client.sign_up(email="example@gmail.com", password="*********") +from httpx import Client +from supabase_auth import ( + SignInWithPassword, + SignInWithPasswordless, + SignUpWithPassword, + SyncSupabaseAuthClient, + UserAttributes, +) +from supabase_utils.http.adapters.httpx import HttpxSession + +with SyncSupabaseAuthClient( + "https://.supabase.co/auth/v1", + HttpxSession(Client()), + headers={"apikey": "your-publishable-key"}, +) as client: + # Sign up with email and password + response = client.sign_up( + SignUpWithPassword.email("someone@example.com", "a-strong-password") + ) -# Sign in with email and password -user = client.sign_in_with_password(email="example@gmail.com", password="*********") + # Sign in with email and password + response = client.sign_in_with_password( + SignInWithPassword.email("someone@example.com", "a-strong-password") + ) -# Sign in with magic link -user = client.sign_in_with_otp(email="example@gmail.com") + # Sign in with magic link + client.sign_in_with_otp(SignInWithPasswordless.email("someone@example.com")) -# Sign in with phone number -user = client.sign_in_with_otp(phone="+1234567890") + # Sign in with phone number + client.sign_in_with_otp(SignInWithPasswordless.phone("+1234567890")) -# Sign in with OAuth -user = client.sign_in_with_oauth(provider="google") + # Sign in with OAuth: send the user to the returned URL + oauth = client.sign_in_with_oauth("google") + print(oauth.url) -# Sign out -client.sign_out() + # Get current user + user = client.get_user() -# Get current user -user = client.get_user() + # Update user profile + user = client.update_user(UserAttributes(data={"name": "John Doe"})) -# Update user profile -user = client.update_user({"data": {"name": "John Doe"}}) + # Sign out + client.sign_out() ``` ### Asynchronous Client ```python -from supabase_auth import AsyncGoTrueClient +import asyncio -headers = { - "apiKey": "my-mega-awesome-api-key", - # ... any other headers you might need. -} -client: AsyncGoTrueClient = AsyncGoTrueClient(url="www.genericauthwebsite.com", headers=headers) +from httpx import AsyncClient +from supabase_auth import ( + AsyncSupabaseAuthClient, + SignInWithPassword, + SignInWithPasswordless, + SignUpWithPassword, + UserAttributes, +) +from supabase_utils.http.adapters.httpx import AsyncHttpxSession -async def main(): - # Sign up with email and password - user = await client.sign_up(email="example@gmail.com", password="*********") - # Sign in with email and password - user = await client.sign_in_with_password(email="example@gmail.com", password="*********") +async def main() -> None: + async with AsyncSupabaseAuthClient( + "https://.supabase.co/auth/v1", + AsyncHttpxSession(AsyncClient()), + headers={"apikey": "your-publishable-key"}, + ) as client: + # Sign up with email and password + response = await client.sign_up( + SignUpWithPassword.email("someone@example.com", "a-strong-password") + ) - # Sign in with magic link - user = await client.sign_in_with_otp(email="example@gmail.com") + # Sign in with email and password + response = await client.sign_in_with_password( + SignInWithPassword.email("someone@example.com", "a-strong-password") + ) - # Sign in with phone number - user = await client.sign_in_with_otp(phone="+1234567890") + # Sign in with magic link + await client.sign_in_with_otp( + SignInWithPasswordless.email("someone@example.com") + ) - # Sign in with OAuth - user = await client.sign_in_with_oauth(provider="google") + # Sign in with phone number + await client.sign_in_with_otp(SignInWithPasswordless.phone("+1234567890")) - # Sign out - await client.sign_out() + # Sign in with OAuth: send the user to the returned URL + oauth = await client.sign_in_with_oauth("google") + print(oauth.url) - # Get current user - user = await client.get_user() + # Get current user + user = await client.get_user() + + # Update user profile + user = await client.update_user(UserAttributes(data={"name": "John Doe"})) + + # Sign out + await client.sign_out() - # Update user profile - user = await client.update_user({"data": {"name": "John Doe"}}) -# Run the async code -import asyncio asyncio.run(main()) ``` @@ -152,20 +176,21 @@ asyncio.run(main()) The library includes support for Multi-Factor Authentication: ```python +from supabase_auth import MFAEnroll + # List MFA factors factors = client.mfa.list_factors() # Enroll a new MFA factor -enrolled_factor = client.mfa.enroll({"factor_type": "totp"}) +factor = client.mfa.enroll(MFAEnroll.totp(friendly_name="My phone")) # Challenge and verify MFA -challenge = client.mfa.challenge({"factor_id": "factor_id"}) -verified = client.mfa.verify({"factor_id": "factor_id", "code": "123456"}) +challenge = client.mfa.challenge(factor.id) +verified = client.mfa.verify(factor.id, "123456", challenge.id) + +# Or both in one call +verified = client.mfa.challenge_and_verify(factor.id, "123456") # Unenroll a factor -client.mfa.unenroll({"factor_id": "factor_id"}) +client.mfa.unenroll(factor.id) ``` - -## Contributions - -We would be immensely grateful for any contributions to this project. diff --git a/src/functions/README.md b/src/functions/README.md index be63f1637..67893e8f2 100644 --- a/src/functions/README.md +++ b/src/functions/README.md @@ -26,62 +26,66 @@ If you self-host the Supabase Edge Runtime, we recommend upgrading to the latest Deploy your Edge Function following the [Supabase Functions documentation](https://supabase.com/docs/guides/functions). +The client takes the URL of your functions, the headers to send, and the HTTP session it sends its requests with. Leaving the session's context manager closes it. A function that answers with an error status raises `FunctionsHttpError`, and one the relay could not reach raises `FunctionsRelayError`. + ### Asynchronous Client ```python import asyncio from httpx import AsyncClient -from supabase_functions import AsyncFunctionsClient +from supabase_functions import ( + AsyncFunctionsClient, + FunctionsHttpError, + FunctionsRelayError, +) from supabase_utils.http.adapters.httpx import AsyncHttpxSession -async def run_func(): - # Initialize the client with your project URL and optional headers - headers = { - "apikey": "your-publishable-key", - # Add any other headers you might need - } - - fc = AsyncFunctionsClient( - "https://.functions.supabase.co", - headers, - http_session=AsyncHttpxSession(client=AsyncClient(follow_redirects=True)), - ) - - try: - # Invoke your Edge Function - res = await fc.invoke("payment-sheet", { - "responseType": "json", - "body": {"amount": 1000, "currency": "usd"} - }) - print("Response:", res) - except Exception as e: - print(f"Error: {e}") + +async def run_func() -> None: + headers = {"apikey": "your-publishable-key"} + + async with AsyncHttpxSession(AsyncClient(follow_redirects=True)) as session: + functions = AsyncFunctionsClient( + "https://.supabase.co/functions/v1", + headers, + session, + ) + + try: + response = await functions.invoke( + "payment-sheet", body={"amount": 1000, "currency": "usd"} + ) + print("Response:", response.content) + except (FunctionsHttpError, FunctionsRelayError) as error: + print(error.status_code, error.message) + if __name__ == "__main__": asyncio.run(run_func()) ``` + ### Synchronous Client + ```python from httpx import Client -from supabase_functions import SyncFunctionsClient +from supabase_functions import FunctionsHttpError, FunctionsRelayError, SyncFunctionsClient from supabase_utils.http.adapters.httpx import HttpxSession -# Initialize the client headers = {"apikey": "your-publishable-key"} -fc = SyncFunctionsClient( - "https://.functions.supabase.co", - headers, - http_session=HttpxSession(client=Client(follow_redirects=True)), -) -# Invoke your Edge Function -try: - res = fc.invoke("payment-sheet", { - "responseType": "json", - "body": {"amount": 1000, "currency": "usd"} - }) - print("Response:", res) -except Exception as e: - print(f"Error: {e}") +with HttpxSession(Client(follow_redirects=True)) as session: + functions = SyncFunctionsClient( + "https://.supabase.co/functions/v1", + headers, + session, + ) + + try: + response = functions.invoke( + "payment-sheet", body={"amount": 1000, "currency": "usd"} + ) + print("Response:", response.content) + except (FunctionsHttpError, FunctionsRelayError) as error: + print(error.status_code, error.message) ``` diff --git a/src/postgrest/README.md b/src/postgrest/README.md index 5cbb20821..bc45648ba 100644 --- a/src/postgrest/README.md +++ b/src/postgrest/README.md @@ -15,23 +15,25 @@ If you want to use a local PostgREST server for development, you can use our preconfigured instance via Docker Compose. ```sh -docker-compose up +docker compose -f infra/docker-compose.yaml up ``` Once Docker Compose started, PostgREST is accessible at . ### Instructions +The package needs an HTTP client adapter. The examples below use httpx: + #### With uv (recommended) ```sh -uv add postgrest +uv add postgrest "supabase_utils[httpx]" ``` #### With Pip ```sh -pip install postgrest +pip install postgrest "supabase_utils[httpx]" ``` ## Supabase Service Compatibility @@ -44,18 +46,29 @@ If you self-host PostgREST, we recommend upgrading to the latest release when up ### Getting started +The client takes the URL of the PostgREST service and the HTTP session it sends its requests with. Leaving the client's context manager closes the session: + ```py import asyncio + +from httpx import AsyncClient from postgrest import AsyncPostgrestClient +from supabase_utils.http.adapters.httpx import AsyncHttpxSession -async def main(): - async with AsyncPostgrestClient("http://localhost:3000") as client: + +async def main() -> None: + async with AsyncPostgrestClient( + "http://localhost:3000", AsyncHttpxSession(AsyncClient()) + ) as client: r = await client.from_("countries").select("*").execute() countries = r.data + asyncio.run(main()) ``` +`SyncPostgrestClient` with an `HttpxSession` works the same way without `await`. The examples below use the async `client` from above. + ### Create ```py @@ -98,8 +111,6 @@ await client.from_("countries").delete().eq("name", "Việt Nam").execute() await client.from_("countries").delete().all().execute() ``` -### General filters - ### Stored procedures (RPC) ```py await client.rpc("foobar", {"arg1": "value1", "arg2": "value2"}).execute() @@ -107,11 +118,4 @@ await client.rpc("foobar", {"arg1": "value1", "arg2": "value2"}).execute() ## CHANGELOG -Read more [here](https://github.com/supabase/postgrest-py/blob/main/CHANGELOG.md). - -## SPONSORS - -We are building the features of Firebase using enterprise-grade, open source products. We support existing communities wherever possible, and if the products don’t exist we build them and open source them ourselves. Thanks to these sponsors who are making the OSS ecosystem better for everyone. - -[![Worklife VC](https://user-images.githubusercontent.com/10214025/90451355-34d71200-e11e-11ea-81f9-1592fd1e9146.png)](https://www.worklife.vc) -[![New Sponsor](https://user-images.githubusercontent.com/10214025/90518111-e74bbb00-e198-11ea-8f88-c9e3c1aa4b5b.png)](https://github.com/sponsors/supabase) +Read more [here](CHANGELOG.md). diff --git a/src/realtime/README.md b/src/realtime/README.md index bc20a6782..bd7146c58 100644 --- a/src/realtime/README.md +++ b/src/realtime/README.md @@ -107,12 +107,19 @@ async with client.channel("broadcast-test", options) as channel: - Setting `replication_ready` to `true` instructs the server to emit a `system` message once the Postgres replication connection backing the channel is established and ready to stream changes. Its payload's `status` is `"ok"` (`message: "Replication connection established"`) on success or `"error"` if the connection is not ready in time. ```python -from realtime import PostgresChangesMessage, RealtimeChannelOptions, SystemMessage +from realtime import ( + PostgresChangesMessage, + RealtimeChannelOptions, + RealtimePostgresChangesListenEvent, + SystemMessage, +) options = ( RealtimeChannelOptions() .broadcast(replication_ready=True) - .postgres_changes("*", schema="public", table="messages") + .postgres_changes( + RealtimePostgresChangesListenEvent.All, schema="public", table="messages" + ) ) async with client.channel("db-changes", options) as channel: @@ -148,14 +155,23 @@ async with client.channel("presence-test", options) as channel: Receive database changes on the client. ```python -from realtime import PostgresChangesMessage, RealtimeChannelOptions +from realtime import ( + PostgresChangesMessage, + RealtimeChannelOptions, + RealtimePostgresChangesListenEvent, +) options = ( RealtimeChannelOptions() - .postgres_changes("*", schema="public") - .postgres_changes("INSERT", schema="public", table="messages") + .postgres_changes(RealtimePostgresChangesListenEvent.All, schema="public") .postgres_changes( - "UPDATE", schema="public", table="users", filter="username=eq.Realtime" + RealtimePostgresChangesListenEvent.Insert, schema="public", table="messages" + ) + .postgres_changes( + RealtimePostgresChangesListenEvent.Update, + schema="public", + table="users", + filter="username=eq.Realtime", ) ) @@ -198,8 +214,13 @@ reduces payload size (helpful for large `bytea`/`jsonb` columns). The selected columns must be selectable by the subscribing role: ```python +from realtime import RealtimeChannelOptions, RealtimePostgresChangesListenEvent + options = RealtimeChannelOptions().postgres_changes( - "*", schema="public", table="users", select=["id", "first_name"] + RealtimePostgresChangesListenEvent.All, + schema="public", + table="users", + select=["id", "first_name"], ) async with client.channel("db-changes", options) as channel: diff --git a/src/storage/README.md b/src/storage/README.md index 53db8bb36..b6da52e16 100644 --- a/src/storage/README.md +++ b/src/storage/README.md @@ -8,28 +8,57 @@ Python Client library to interact with Supabase Storage. If you self-host Supabase Storage, we recommend upgrading to the latest release when upgrading this SDK. +## Installation + +The package needs an HTTP client adapter. The examples below use httpx: + +```bash +pip install storage3 "supabase_utils[httpx]" +# or +uv add storage3 "supabase_utils[httpx]" +``` + ## How to use -As it takes some effort to get the headers. We suggest that you use the storage functionality through the main [Supabase Python Client](https://github.com/supabase-community/supabase-py) +Most users use storage through the main [Supabase Python client](../supabase/README.md), as `client.storage`, which sets the headers for you. + +The client takes the URL of the storage service, the headers to send, and the HTTP session it sends its requests with. Leaving the client's context manager closes the session: +```python +import asyncio -```python3 +from httpx import AsyncClient from storage3 import AsyncStorageClient +from supabase_utils.http.adapters.httpx import AsyncHttpxSession -url = "https://.supabase.co/storage/v1" +url = "https://.supabase.co/storage/v1/" key = "" -headers = {"apiKey": key, "Authorization": f"Bearer {key}"} +headers = {"apikey": key, "Authorization": f"Bearer {key}"} + -storage_client = AsyncStorageClient(url, headers) +async def main() -> None: + async with AsyncStorageClient( + url, headers, AsyncHttpxSession(AsyncClient()) + ) as storage_client: + buckets = await storage_client.list_buckets() + print(buckets) -async def get_buckets(): - await storage_client.list_buckets() + +asyncio.run(main()) ``` +`SyncStorageClient` with an `HttpxSession` works the same way without `await`. + ### Uploading files -When uploading files, make sure to set the correct mimetype by using the `file_options` argument: -```py -async def file_upload(): - await storage_client.from_("bucket").upload("/folder/file.png", file_object, {"content-type": "image/png"}) + +When uploading files, set the MIME type with the `content_type` argument: + +```python +from pathlib import Path + +await storage_client.from_("bucket").upload( + "folder/file.png", Path("file.png"), content_type="image/png" +) ``` -If no mime type is given, the default `text/plain` will be used. + +If no MIME type is given, `text/plain;charset=UTF-8` is used. diff --git a/src/supabase/README.md b/src/supabase/README.md index b1df718a2..5779c8641 100644 --- a/src/supabase/README.md +++ b/src/supabase/README.md @@ -61,16 +61,37 @@ key: str = os.environ["SUPABASE_KEY"] supabase: Client = create_client(url, key) ``` -For the async client, use `create_async_client` from `supabase.httpx` or `supabase.aiohttp`, which returns an `AsyncClient`. +For the async client, use `create_async_client` from `supabase.httpx` or `supabase.aiohttp`, which returns an `AsyncClient`: + +```python +import asyncio +import os + +from supabase.httpx import create_async_client + + +async def main() -> None: + async with create_async_client( + os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"] + ) as supabase: + response = await supabase.table("countries").select("*").execute() + print(response.data) + + +asyncio.run(main()) +``` Settings are keyword arguments. `headers` and `request_timeout` apply to the database, auth, storage and edge functions, not to the realtime connection of `AsyncClient`. The settings of one service are grouped in an options class: ```python +import os + from supabase import AuthClientOptions, PostgrestClientOptions, StorageClientOptions +from supabase.httpx import create_client supabase = create_client( - url, - key, + os.environ["SUPABASE_URL"], + os.environ["SUPABASE_KEY"], headers={"x-app": "my-app"}, request_timeout=30, postgrest=PostgrestClientOptions(schema="private"), @@ -86,13 +107,21 @@ Use the supabase client to interface with your database. ### Sign-up ```python -user = supabase.auth.sign_up({ "email": users_email, "password": users_password }) +from supabase_auth import SignUpWithPassword + +response = supabase.auth.sign_up( + SignUpWithPassword.email("someone@example.com", "a-strong-password") +) ``` ### Sign-in ```python -user = supabase.auth.sign_in_with_password({ "email": users_email, "password": users_password }) +from supabase_auth import SignInWithPassword + +response = supabase.auth.sign_in_with_password( + SignInWithPassword.email("someone@example.com", "a-strong-password") +) ``` ### Insert Data @@ -157,12 +186,13 @@ data = supabase.table("countries").delete().all().execute() ### Call Edge Functions ```python -def test_func(): - try: - resp = supabase.functions.invoke("hello-world", body={}) - return resp - except (FunctionsRelayError, FunctionsHttpError) as exception: - print(exception.status_code, exception.message) +from supabase import FunctionsHttpError, FunctionsRelayError + +try: + response = supabase.functions.invoke("hello-world", body={"name": "Functions"}) + print(response.content) +except (FunctionsRelayError, FunctionsHttpError) as error: + print(error.status_code, error.message) ``` ### Download a file from Storage @@ -176,10 +206,13 @@ data = supabase.storage.from_(bucket_name).download("photo1.png") ### Upload a file ```python +from pathlib import Path + bucket_name: str = "photos" -new_file = getUserFile() -data = supabase.storage.from_(bucket_name).upload("/user1/profile.png", new_file) +data = supabase.storage.from_(bucket_name).upload( + "user1/profile.png", Path("profile.png"), content_type="image/png" +) ``` ### Remove a file @@ -254,10 +287,17 @@ SupabaseError The response errors inherit both from the root of their package and from `SupabaseAPIError`, so `except AuthApiError` and `except AuthError` keep working. Arguments the client rejects before sending a request raise the built-in `ValueError` or `TypeError`, as they do everywhere in Python, except for a vector batch of the wrong size, which raises `VectorBucketException`. A lost realtime connection is reported as the `websockets.ConnectionClosed` or built-in `TimeoutError` that failed it, not as a `SupabaseError`. -## Important: Proper Client Shutdown +## Closing the client -To ensure the Supabase client terminates correctly and to prevent resource leaks, you **must** explicitly call: +The client keeps its HTTP connections open. Use it as a context manager to close them when you are done: ```python -client.auth.sign_out() +import os + +from supabase.httpx import create_client + +with create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"]) as supabase: + data = supabase.table("countries").select("*").execute() ``` + +`AsyncClient` works the same way with `async with`. From 3182f679edc7c962f195506f17d9ceeb9710124e Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Wed, 11 Nov 2026 10:42:38 +0100 Subject: [PATCH 2/3] docs: address review of the README snippets and their check --- .github/scripts/check_markdown_snippets.py | 70 +++++++++++----------- src/auth/README.md | 8 +-- src/functions/README.md | 6 +- src/postgrest/README.md | 2 +- src/storage/README.md | 2 +- 5 files changed, 46 insertions(+), 42 deletions(-) diff --git a/.github/scripts/check_markdown_snippets.py b/.github/scripts/check_markdown_snippets.py index c5ca621f0..6dcb7e2aa 100644 --- a/.github/scripts/check_markdown_snippets.py +++ b/.github/scripts/check_markdown_snippets.py @@ -7,7 +7,8 @@ A block is the body of an async function, so it can use `await` and `async with`. It imports what it uses, as the code a user copies has to. The names a file's snippets share, such as the client its README creates once, are -declared in PRELUDES. A block fenced as ```python skip is not checked, for +declared in PRELUDES with their types. Their types are imported under private +aliases, so a snippet that uses a class without importing it still fails. A block fenced as ```python skip is not checked, for example v2 code shown as "before" or a fragment that only shows a shape. Run it from the repository root in an environment with every package and extra @@ -30,35 +31,18 @@ FENCE = re.compile(r"^(?P\s*)(?P`{3,}|~{3,})(?P.*)$") PRELUDES = { - "MIGRATION.md": [ - "from supabase import Client", - "from supabase_auth import SyncSupportedStorage", - "client: Client", - "url: str", - "key: str", - "my_storage: SyncSupportedStorage", - "account_id: str", - ], - "src/supabase/README.md": [ - "from supabase import Client", - "supabase: Client", - ], - "src/auth/README.md": [ - "from supabase_auth import SyncSupabaseAuthClient", - "client: SyncSupabaseAuthClient", - ], - "src/postgrest/README.md": [ - "from postgrest import AsyncPostgrestClient", - "client: AsyncPostgrestClient", - ], - "src/realtime/README.md": [ - "from realtime import RealtimeClient", - "client: RealtimeClient", - ], - "src/storage/README.md": [ - "from storage3 import AsyncStorageClient", - "storage_client: AsyncStorageClient", - ], + "MIGRATION.md": { + "client": "supabase.Client", + "url": "str", + "key": "str", + "my_storage": "supabase_auth.SyncSupportedStorage", + "account_id": "str", + }, + "src/supabase/README.md": {"supabase": "supabase.Client"}, + "src/auth/README.md": {"client": "supabase_auth.SyncSupabaseAuthClient"}, + "src/postgrest/README.md": {"client": "postgrest.AsyncPostgrestClient"}, + "src/realtime/README.md": {"client": "realtime.RealtimeClient"}, + "src/storage/README.md": {"storage_client": "storage3.AsyncStorageClient"}, } PYREFLY_CONFIG = """\ @@ -78,7 +62,7 @@ class Snippet: def markdown_files() -> list[str]: output = subprocess.run( - ["git", "ls-files", "--cached", "--others", "--exclude-standard", "*.md"], + ["git", "ls-files", "*.md"], check=True, capture_output=True, text=True, @@ -113,17 +97,31 @@ def python_snippets(markdown: str) -> list[Snippet]: and not closing["info"].strip() ): break - body.append(lines[index - 1][indent:]) + line = lines[index - 1] + body.append(line[min(indent, len(line) - len(line.lstrip())) :]) if words and words[0] in LANGUAGES and "skip" not in words[1:]: snippets.append(Snippet(markdown, first_line, body)) return snippets +def prelude(markdown: str) -> list[str]: + imports: list[str] = [] + declarations: list[str] = [] + for number, (name, type_path) in enumerate(PRELUDES.get(markdown, {}).items()): + module, _, type_name = type_path.rpartition(".") + if module: + alias = f"_Prelude{number}" + imports.append(f"from {module} import {type_name} as {alias}") + type_name = alias + declarations.append(f"{name}: {type_name}") + return [*imports, *declarations] + + def module_source(snippet: Snippet) -> tuple[str, int]: """Return the module that wraps the snippet and the number of lines before the snippet's first line.""" header = [ - *PRELUDES.get(snippet.markdown, []), + *prelude(snippet.markdown), "", "", "async def _snippet() -> None:", @@ -174,7 +172,11 @@ def main() -> int: located: list[tuple[str, int, str]] = [] for error in errors: - snippet, header_lines = modules[Path(error["path"]).name] + located_module = modules.get(Path(error["path"]).name) + if located_module is None: + located.append((error["path"], error["line"], error["description"])) + continue + snippet, header_lines = located_module line = snippet.first_line + error["line"] - header_lines - 1 located.append( (snippet.markdown, line, f"{error['description']} [{error['name']}]") diff --git a/src/auth/README.md b/src/auth/README.md index 955b65819..6442e3939 100644 --- a/src/auth/README.md +++ b/src/auth/README.md @@ -4,7 +4,7 @@ [![Python](https://img.shields.io/pypi/pyversions/supabase_auth)](https://pypi.org/project/supabase_auth) [![Version](https://img.shields.io/pypi/v/supabase_auth?color=%2334D058)](https://pypi.org/project/supabase_auth) -Python client for [Supabase Auth](https://github.com/supabase/auth), the Python counterpart of [`@supabase/auth-js`](https://github.com/supabase/supabase-js/tree/master/packages/core/auth-js). Most users use it through the [`supabase`](../supabase/README.md) package, as `client.auth`. +Python client for [Supabase Auth](https://github.com/supabase/auth), the Python counterpart of [`@supabase/auth-js`](https://github.com/supabase/supabase-js/tree/master/packages/core/auth-js). Most users use it through the [`supabase`](https://github.com/supabase/supabase-py/blob/main/src/supabase/README.md) package, as `client.auth`. ## Installation @@ -42,11 +42,11 @@ Use `supabase_utils[aiohttp]` instead to run the async client on aiohttp. - JWT token handling and verification - User management and profile updates -## Differences to the JS client +## Differences to the JavaScript client -Methods and attributes follow the JS client, but browser specific code is not ported. +Methods and attributes follow the JavaScript client, but browser specific code is not ported. -Errors are raised where they originate instead of being returned next to the data, since that is the idiomatic way in Python. Where JS returns the error: +Errors are raised where they originate instead of being returned next to the data, since that is the idiomatic way in Python. Where JavaScript returns the error: ```js const { data, error } = await supabase.auth.signUp({ email, password }) diff --git a/src/functions/README.md b/src/functions/README.md index 67893e8f2..5a320d8a5 100644 --- a/src/functions/README.md +++ b/src/functions/README.md @@ -43,7 +43,8 @@ from supabase_utils.http.adapters.httpx import AsyncHttpxSession async def run_func() -> None: - headers = {"apikey": "your-publishable-key"} + key = "your-publishable-key" + headers = {"apikey": key, "Authorization": f"Bearer {key}"} async with AsyncHttpxSession(AsyncClient(follow_redirects=True)) as session: functions = AsyncFunctionsClient( @@ -72,7 +73,8 @@ from httpx import Client from supabase_functions import FunctionsHttpError, FunctionsRelayError, SyncFunctionsClient from supabase_utils.http.adapters.httpx import HttpxSession -headers = {"apikey": "your-publishable-key"} +key = "your-publishable-key" +headers = {"apikey": key, "Authorization": f"Bearer {key}"} with HttpxSession(Client(follow_redirects=True)) as session: functions = SyncFunctionsClient( diff --git a/src/postgrest/README.md b/src/postgrest/README.md index bc45648ba..8a7a8f63f 100644 --- a/src/postgrest/README.md +++ b/src/postgrest/README.md @@ -118,4 +118,4 @@ await client.rpc("foobar", {"arg1": "value1", "arg2": "value2"}).execute() ## CHANGELOG -Read more [here](CHANGELOG.md). +Read more [here](https://github.com/supabase/supabase-py/blob/main/src/postgrest/CHANGELOG.md). diff --git a/src/storage/README.md b/src/storage/README.md index b6da52e16..12d07ff0a 100644 --- a/src/storage/README.md +++ b/src/storage/README.md @@ -20,7 +20,7 @@ uv add storage3 "supabase_utils[httpx]" ## How to use -Most users use storage through the main [Supabase Python client](../supabase/README.md), as `client.storage`, which sets the headers for you. +Most users use storage through the main [Supabase Python client](https://github.com/supabase/supabase-py/blob/main/src/supabase/README.md), as `client.storage`, which sets the headers for you. The client takes the URL of the storage service, the headers to send, and the HTTP session it sends its requests with. Leaving the client's context manager closes the session: From 83caa2279ea9061cc73c3b256def9a1ef051e0cb Mon Sep 17 00:00:00 2001 From: Lukas Klingsbo Date: Wed, 11 Nov 2026 10:53:38 +0100 Subject: [PATCH 3/3] docs(functions): send the publishable key only as apikey --- src/functions/README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/functions/README.md b/src/functions/README.md index 5a320d8a5..e09427b44 100644 --- a/src/functions/README.md +++ b/src/functions/README.md @@ -26,7 +26,7 @@ If you self-host the Supabase Edge Runtime, we recommend upgrading to the latest Deploy your Edge Function following the [Supabase Functions documentation](https://supabase.com/docs/guides/functions). -The client takes the URL of your functions, the headers to send, and the HTTP session it sends its requests with. Leaving the session's context manager closes it. A function that answers with an error status raises `FunctionsHttpError`, and one the relay could not reach raises `FunctionsRelayError`. +The client takes the URL of your functions, the headers to send, and the HTTP session it sends its requests with. Leaving the session's context manager closes it. A function that answers with an error status raises `FunctionsHttpError`, and one the relay could not reach raises `FunctionsRelayError`. The publishable key goes in the `apikey` header only. For a function that verifies the JWT of the caller, also send `Authorization: Bearer ` with the access token of the signed in user. ### Asynchronous Client @@ -43,8 +43,7 @@ from supabase_utils.http.adapters.httpx import AsyncHttpxSession async def run_func() -> None: - key = "your-publishable-key" - headers = {"apikey": key, "Authorization": f"Bearer {key}"} + headers = {"apikey": "your-publishable-key"} async with AsyncHttpxSession(AsyncClient(follow_redirects=True)) as session: functions = AsyncFunctionsClient( @@ -73,8 +72,7 @@ from httpx import Client from supabase_functions import FunctionsHttpError, FunctionsRelayError, SyncFunctionsClient from supabase_utils.http.adapters.httpx import HttpxSession -key = "your-publishable-key" -headers = {"apikey": key, "Authorization": f"Bearer {key}"} +headers = {"apikey": "your-publishable-key"} with HttpxSession(Client(follow_redirects=True)) as session: functions = SyncFunctionsClient(