### Install with pip Source: https://github.com/supabase/storage-py/blob/main/docs/index.rst Install the storage3 package using pip. Requires Python >= 3.7. ```default pip install storage3 ``` -------------------------------- ### Full bucket lifecycle Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-bucket-api.md Example demonstrating how to create, retrieve, update, empty, and delete a bucket using the SyncStorageClient. ```APIDOC ## Full bucket lifecycle ### Description Demonstrates the complete lifecycle of a bucket: create, get, update, empty, and delete. ### Code ```python from storage3 import SyncStorageClient client = SyncStorageClient( "https://your-project.supabase.co/storage/v1", {"apiKey": "key", "Authorization": "Bearer key"}, ) client.create_bucket("media", options={"public": False, "file_size_limit": 10_000_000}) bucket = client.get_bucket("media") print(bucket.id, bucket.allowed_mime_types) client.update_bucket("media", {"public": True}) client.empty_bucket("media") client.delete_bucket("media") client.session.close() ``` ``` -------------------------------- ### Install with poetry Source: https://github.com/supabase/storage-py/blob/main/docs/index.rst Add the storage3 package as a dependency using poetry. Requires Python >= 3.7. ```default poetry add storage3 ``` -------------------------------- ### AsyncBucket.info Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Gets information about files in the bucket. Returns a list of dictionaries. ```APIDOC ## AsyncBucket.info ### Description Gets information about files in the bucket. Returns a list of dictionaries. ### Method info ### Parameters - **path** (str) - Required - The path to query. - **options** (dict) - Optional - Query options. ### Returns - **list[dict[str, str]]** - List of file information dictionaries. ### Throws - **StorageApiError** - On any non-2xx HTTP response. ``` -------------------------------- ### Catching StorageException Source: https://github.com/supabase/storage-py/blob/main/_autodocs/errors.md Example of how to catch the base StorageException to handle library-level errors. ```python from storage3.utils import StorageException try: ... except StorageException as err: print(str(err)) ``` -------------------------------- ### Retrieve file info with info() Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Lists metadata for a specific file by sending a GET request to the object info endpoint. ```python async def info( self, path: str, ) -> list[dict[str, str]]: """Lists info for a particular file. Parameters ---------- path The path to the file. """ response = await self._request( "GET", f"/object/info/{self.id}/{path}", ) return response.json() ``` -------------------------------- ### Basic initialization with context manager Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-client.md Demonstrates how to instantiate the SyncStorageClient using a context manager to automatically handle the session lifecycle. ```python from storage3 import SyncStorageClient url = "https://your-project.supabase.co/storage/v1" key = "your-anon-key" headers = {"apiKey": key, "Authorization": f"Bearer {key}"} with SyncStorageClient(url, headers) as client: buckets = client.list_buckets() public_url = client.from_("avatars").get_public_url("folder/image.png") print(buckets) print(public_url) ``` -------------------------------- ### AsyncBucket.get_public_url Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Gets the public URL for a file. Returns a string. ```APIDOC ## AsyncBucket.get_public_url ### Description Gets the public URL for a file. Returns a string. ### Method get_public_url ### Parameters - **path** (str) - Required - The file path. - **options** (dict) - Optional - Additional options. ### Returns - **str** - The public URL. ``` -------------------------------- ### Basic async usage of create_client Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/create-client.md Demonstrates how to initialize an asynchronous storage client and list buckets. ```python import asyncio from storage3 import create_client async def main() -> None: client = create_client( "https://your-project.supabase.co/storage/v1", {"apiKey": "anon-key", "Authorization": "Bearer anon-key"}, is_async=True, ) buckets = await client.list_buckets() await client.session.aclose() asyncio.run(main()) ``` -------------------------------- ### Get file info method Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Retrieves metadata information for a file. ```python def info( self, path: str, ) -> list[dict[str, str]]: ``` -------------------------------- ### Upload, public URL, and download with SyncStorageClient Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Demonstrates initializing the client, uploading a file from the local filesystem, retrieving a public URL, and downloading file content. ```python from storage3 import SyncStorageClient client = SyncStorageClient("https://x.supabase.co/storage/v1", {"apiKey": "k"}) bucket = client.from_("avatars") with open("photo.png", "rb") as f: res = bucket.upload("profile/photo.png", f, {"content-type": "image/png"}) print(res.path, res.full_path) url = bucket.get_public_url("profile/photo.png") data = bucket.download("profile/photo.png") print(url, len(data)) client.session.close() ``` -------------------------------- ### Basic sync usage with error handling Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/create-client.md Demonstrates initializing a synchronous storage client with a custom timeout and handling potential StorageApiError exceptions. ```python from storage3 import create_client from storage3.exceptions import StorageApiError client = create_client( "https://your-project.supabase.co/storage/v1", {"apiKey": "anon-key", "Authorization": "Bearer anon-key"}, is_async=False, # sync client timeout=30, # overrides DEFAULT_TIMEOUT of 20s ) try: client.create_bucket("avatars", options={"public": True}) files = client.from_("avatars").list() print(files) except StorageApiError as err: print(f"status={err.status} code={err.code} message={err.message}") finally: client.session.close() ``` -------------------------------- ### download Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Downloads a file from a bucket. This method sends a GET request to the object endpoint. ```APIDOC ## GET /object/{bucket}/{path} ### Description Downloads a file from a bucket. ### Method GET ### Endpoint /object/{bucket}/{path} ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket ID. - **path** (string) - Required - The relative file path. #### Query Parameters - **transform** (object) - Optional - Image transformation options. When set, the endpoint changes to `/render/image/authenticated/{bucket}/{path}`. ### Request Example ``` GET /object/{bucket}/{path} ``` ### Response #### Success Response (200) - **bytes** - The file content as bytes. #### Response Example ``` ``` ``` -------------------------------- ### Initialization with pre-configured httpx client and error handling Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-client.md Shows how to inject a custom httpx client into the SyncStorageClient and handle StorageApiError exceptions. ```python from httpx import Client, Timeout from storage3 import SyncStorageClient from storage3.exceptions import StorageApiError http = Client(timeout=Timeout(60.0)) client = SyncStorageClient( "https://your-project.supabase.co/storage/v1", {"apiKey": "anon-key", "Authorization": "Bearer anon-key"}, http_client=http, ) try: bucket = client.get_bucket("avatars") print(bucket.name, bucket.public) except StorageApiError as err: print(f"HTTP {err.status}: {err.code} — {err.message}") finally: client.session.close() ``` -------------------------------- ### Create, list, update and empty a bucket Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-bucket-api.md Demonstrates the full lifecycle of a bucket including initialization, creation with options, listing, emptying, and deletion. ```python import asyncio from storage3 import AsyncStorageClient from storage3.types import CreateOrUpdateBucketOptions async def main() -> None: client = AsyncStorageClient( "https://your-project.supabase.co/storage/v1", {"apiKey": "key", "Authorization": "Bearer key"}, ) options: CreateOrUpdateBucketOptions = { "public": True, "file_size_limit": 5_000_000, "allowed_mime_types": ["image/png", "image/jpeg"], } await client.create_bucket("avatars", name="Avatars", options=options) buckets = await client.list_buckets() for b in buckets: print(b.id, b.public) await client.empty_bucket("avatars") await client.delete_bucket("avatars") await client.session.aclose() asyncio.run(main()) ``` -------------------------------- ### Handling SyncClient DeprecationWarning Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/utils.md Example of catching the DeprecationWarning emitted when using the deprecated SyncClient. ```python from warnings import catch_warnings, simplefilter from storage3.utils import SyncClient with catch_warnings(): simplefilter("error") try: SyncClient(base_url="https://x.supabase.co/storage/v1") except DeprecationWarning as w: print("deprecated:", w) ``` -------------------------------- ### Initialize AsyncStorageClient with async context manager Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-client.md Demonstrates basic initialization and usage of AsyncStorageClient using an asynchronous context manager to handle the session lifecycle. ```python import asyncio from storage3 import AsyncStorageClient async def main() -> None: url = "https://your-project.supabase.co/storage/v1" key = "your-anon-key" headers = {"apiKey": key, "Authorization": f"Bearer {key}"} timeout = 30 async with AsyncStorageClient(url, headers, timeout=timeout) as client: buckets = await client.list_buckets() bucket = client.from_("avatars") public_url = bucket.get_public_url("folder/image.png") print(buckets, public_url) asyncio.run(main()) ``` -------------------------------- ### info Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Retrieves information about a file. This method sends a GET request to the object info endpoint. ```APIDOC ## GET /object/info/{bucket}/{path} ### Description Retrieves information about a file. ### Method GET ### Endpoint /object/info/{bucket}/{path} ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket ID. - **path** (string) - Required - The relative file path. ### Request Example ``` GET /object/info/{bucket}/{path} ``` ### Response #### Success Response (200) - **list[dict[str, str]]** - A list of file information dictionaries. #### Response Example ```json [ { "name": "file.png", "id": "...", "updated_at": "...", "created_at": "...", "last_accessed_at": "...", "metadata": {} } ] ``` ``` -------------------------------- ### Upload, list, download, and delete operations Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Demonstrates a complete workflow for uploading a file, listing files in a folder, downloading a file, and removing it from the bucket. ```python import asyncio from storage3 import AsyncStorageClient async def main() -> None: client = AsyncStorageClient("https://x.supabase.co/storage/v1", {"apiKey": "k"}) bucket = client.from_("avatars") with open("photo.png", "rb") as f: res = await bucket.upload("folder/photo.png", f, {"content-type": "image/png"}) print(res.path, res.full_path) # path + server Key files = await bucket.list("folder", {"limit": 10, "sortBy": {"column": "name", "order": "asc"}}) data = await bucket.download("folder/photo.png") print(files, len(data)) await bucket.remove(["folder/photo.png"]) await client.session.aclose() asyncio.run(main()) ``` -------------------------------- ### Error handling for a missing bucket Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-bucket-api.md Example showing how to catch StorageApiError when accessing a non-existent bucket. ```APIDOC ## Error handling for a missing bucket ### Description Demonstrates catching StorageApiError when a bucket does not exist. ### Code ```python from storage3 import SyncStorageClient from storage3.exceptions import StorageApiError client = SyncStorageClient("https://x.supabase.co/storage/v1", {"apiKey": "k"}) try: client.get_bucket("does-not-exist") except StorageApiError as err: print(f"status={err.status}, code={err.code}, message={err.message}") finally: client.session.close() ``` ``` -------------------------------- ### Full bucket lifecycle Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-bucket-api.md Demonstrates the complete lifecycle of a storage bucket, including initialization, creation, retrieval, updating, emptying, and deletion. ```python from storage3 import SyncStorageClient client = SyncStorageClient( "https://your-project.supabase.co/storage/v1", {"apiKey": "key", "Authorization": "Bearer key"}, ) client.create_bucket("media", options={"public": False, "file_size_limit": 10_000_000}) bucket = client.get_bucket("media") print(bucket.id, bucket.allowed_mime_types) client.update_bucket("media", {"public": True}) client.empty_bucket("media") client.delete_bucket("media") client.session.close() ``` -------------------------------- ### Get public URL method Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Constructs a public URL string locally without sending a network request. ```python def get_public_url(self, path: str, options: URLOptions = {}) -> str: ``` -------------------------------- ### Initialize AsyncStorageClient Source: https://github.com/supabase/storage-py/blob/main/README.md Initializes the storage client with the Supabase URL and authentication headers. ```python3 from storage3 import AsyncStorageClient url = "https://.supabase.co/storage/v1" key = "" headers = {"apiKey": key, "Authorization": f"Bearer {key}"} storage_client = AsyncStorageClient(url, headers) async def get_buckets(): await storage_client.list_buckets() ``` -------------------------------- ### GET /bucket/{id} Source: https://github.com/supabase/storage-py/blob/main/_autodocs/endpoints.md Retrieves a single bucket by its ID. Invoked by the get_bucket(id) method in the Python client. ```APIDOC ## GET /bucket/{id} ### Description Retrieves a single bucket by its ID. Invoked by `get_bucket(id)` in the Python client. ### Method GET ### Endpoint /bucket/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the bucket. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **body** (object) - A single bucket object mapped to `AsyncBucket` / `SyncBucket`. #### Response Example ```json { "id": "bucket-id", "name": "bucket-name", "owner": "owner-id", "public": false, "created_at": "2023-01-01T00:00:00Z", "updated_at": "2023-01-01T00:00:00Z", "file_size_limit": null, "allowed_mime_types": null, "type": "public" } ``` ### Error Responses - **404** - Bucket not found ``` -------------------------------- ### AsyncStorageClient.__init__ Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-client.md Initializes the async storage client with the base URL and headers. Optional deprecated parameters for timeout, verify, proxy, or a custom httpx client can be provided. ```APIDOC ## AsyncStorageClient.__init__ ### Description Initializes the async storage client with the base URL and headers. Optional deprecated parameters for timeout, verify, proxy, or a custom httpx client can be provided. ### Method Constructor ### Signature ```python def __init__( self, url: str, headers: dict[str, str], timeout: Optional[int] = None, verify: Optional[bool] = None, proxy: Optional[str] = None, http_client: Optional[AsyncClient] = None, ) -> None: ``` ### Parameters - **url** (str) - Required - Base URL of the Supabase Storage API, e.g. https://.supabase.co/storage/v1. Becomes the httpx base_url. - **headers** (dict[str, str]) - Required - Request headers. A User-Agent header supabase-py/storage3 v{__version__} is always prepended and the given headers merged over it. - **timeout** (Optional[int]) - Optional - Deprecated. If provided, emits DeprecationWarning; stored as self.timeout = int(abs(timeout)), falling back to DEFAULT_TIMEOUT (= 20) when None. - **verify** (Optional[bool]) - Optional - Deprecated. If provided, emits DeprecationWarning. Stored as self.verify (True when None). - **proxy** (Optional[str]) - Optional - Deprecated. If provided, emits DeprecationWarning; forwarded to httpx. - **http_client** (Optional[httpx.AsyncClient]) - Optional - Pre-configured httpx client. When given, its base_url is overwritten with url and its headers are updated with the merged headers; all other httpx options are ignored. ### Instance Attributes - **self.verify** (bool) - True unless verify=False was passed - **self.timeout** (int) - abs(timeout) if given else DEFAULT_TIMEOUT (20) - **self.session** (httpx.AsyncClient) - The underlying httpx client (also available as self._client via the bucket API base) ### Deprecation Warnings Passing a non-None timeout, verify, or proxy triggers a DeprecationWarning (stacklevel=2) telling you to configure these on the http client instead. ``` -------------------------------- ### GET /object/info/{bucket}/{path} Source: https://github.com/supabase/storage-py/blob/main/_autodocs/endpoints.md Retrieves information about an object. Invoked by info(path). Returns a list of info objects. ```APIDOC ## GET /object/info/{bucket}/{path} ### Description Retrieves information about an object. Invoked by info(path). ### Method GET ### Endpoint /object/info/{bucket}/{path} ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket id. - **path** (string) - Required - The object path. ### Request Body None ### Response #### Success Response (200) JSON array of info objects. #### Response Example [ { "name": "file.txt", "id": "...", "updated_at": "...", "created_at": "...", "last_accessed_at": "...", "metadata": {} } ] ``` -------------------------------- ### AsyncStorageBucketAPI.__init__ Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-bucket-api.md Constructor for the AsyncStorageBucketAPI class. Initializes the API client with an httpx AsyncClient session. ```APIDOC ## AsyncStorageBucketAPI.__init__ ### Description Initializes the AsyncStorageBucketAPI with an HTTP session. ### Method Constructor ### Signature ```python def __init__(self, session: AsyncClient) -> None: ``` ### Parameters - **session** (httpx.AsyncClient) - Required - HTTP session; stored as self._client. ### Returns None ``` -------------------------------- ### SyncStorageClient.from_(bucket_name) Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-client.md Returns a SyncStorageBucketAPI instance for interacting with a specific bucket, allowing operations like getting public URLs. ```APIDOC ## from_(bucket_name) ### Description Creates a bucket-specific API client for operations on files within the bucket. ### Parameters - **bucket_name** (str) - Required - The name of the bucket. ### Returns - SyncStorageBucketAPI instance. ### Example ```python public_url = client.from_("avatars").get_public_url("folder/image.png") ``` ``` -------------------------------- ### Initialize AsyncStorageClient with custom httpx client and error handling Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-client.md Shows how to inject a pre-configured httpx AsyncClient into the AsyncStorageClient and handle StorageApiError exceptions. ```python import asyncio from httpx import AsyncClient, Timeout from storage3 import AsyncStorageClient from storage3.exceptions import StorageApiError async def main() -> None: http = AsyncClient(timeout=Timeout(60.0), http2=True) client = AsyncStorageClient( "https://your-project.supabase.co/storage/v1", {"apiKey": "anon-key", "Authorization": "Bearer anon-key"}, http_client=http, ) try: data = await client.download("avatars/photo.png") # via proxy print(len(data)) except StorageApiError as err: print(f"HTTP {err.status}: {err.code} — {err.message}") finally: await client.session.aclose() asyncio.run(main()) ``` -------------------------------- ### create_client() Source: https://github.com/supabase/storage-py/blob/main/docs/api/index.rst Creates a new storage client instance. This is the entry point for interacting with Supabase Storage. ```APIDOC ## create_client() ### Description Creates a new storage client instance. This is the entry point for interacting with Supabase Storage. ### Method create_client ### Endpoint storage3.create_client ### Parameters No parameters documented. ### Request Example No request example documented. ### Response #### Success Response No response fields documented. #### Response Example No response example documented. ``` -------------------------------- ### Inherited bucket methods Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-client.md The class inherits from AsyncStorageBucketAPI, providing methods to list, get, create, update, empty, and delete buckets. ```APIDOC ## Inherited bucket methods ### Description The class inherits from `AsyncStorageBucketAPI`, providing bucket management operations. ### Methods - `list_buckets() -> list[AsyncBucket]` - `get_bucket(id) -> AsyncBucket` - `create_bucket(id, name=None, options=None) -> dict[str, str]` - `update_bucket(id, options) -> dict[str, str]` - `empty_bucket(id) -> dict[str, str]` - `delete_bucket(id) -> dict[str, str]` ### See Also [AsyncStorageBucketAPI](async-storage-bucket-api.md) ``` -------------------------------- ### AsyncBucketProxy.download(path, options) Source: https://github.com/supabase/storage-py/blob/main/docs/api/bucket.rst Downloads a file from the bucket. Returns the file content as bytes. ```APIDOC ## AsyncBucketProxy.download(path, options) ### Description Downloads a file. ### Method async download(path: str, options: DownloadOptions = {}) -> bytes ### Parameters - **path** (str) - Required - The file path to be downloaded, including the path and file name. For example folder/image.png. - **options** (DownloadOptions) - Optional - Additional download options. ### Returns bytes - The file content as bytes. ``` -------------------------------- ### GET /bucket Source: https://github.com/supabase/storage-py/blob/main/_autodocs/endpoints.md Lists all buckets. Invoked by the list_buckets method in the Python client. Returns a JSON array of bucket objects mapped to BaseBucket fields. ```APIDOC ## GET /bucket ### Description Lists all buckets. Invoked by `list_buckets` in the Python client. ### Method GET ### Endpoint /bucket ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **body** (array) - JSON array; each element is a bucket object mapped onto `BaseBucket` fields (`id`, `name`, `owner`, `public`, `created_at`, `updated_at`, `file_size_limit`, `allowed_mime_types`, `type`) #### Response Example ```json [ { "id": "bucket-id", "name": "bucket-name", "owner": "owner-id", "public": false, "created_at": "2023-01-01T00:00:00Z", "updated_at": "2023-01-01T00:00:00Z", "file_size_limit": null, "allowed_mime_types": null, "type": "public" } ] ``` ### Error Responses - **401** - Unauthorized - **403** - Forbidden ``` -------------------------------- ### SyncStorageClient.__init__ Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-client.md Constructor for the synchronous storage client. Initializes the underlying httpx.Client with the provided base URL and headers, and handles deprecated timeout, verify, and proxy parameters. ```APIDOC ## SyncStorageClient.__init__ ### Description Initializes a synchronous client for the Supabase Storage API. Sets up the underlying httpx.Client with the given base URL and headers, and processes optional deprecated parameters. ### Method Constructor ### Signature ```python def __init__( self, url: str, headers: dict[str, str], timeout: Optional[int] = None, verify: Optional[bool] = None, proxy: Optional[str] = None, http_client: Optional[Client] = None, ) -> None: ``` ### Parameters - **url** (str) - Required - Base URL of the Supabase Storage API, e.g. `https://.supabase.co/storage/v1`. Becomes the httpx `base_url`. - **headers** (dict[str, str]) - Required - Request headers. A `User-Agent` header `supabase-py/storage3 v{__version__}` is always prepended and the given headers merged over it. - **timeout** (Optional[int]) - Optional - Deprecated. If provided, emits `DeprecationWarning`; stored as `self.timeout = int(abs(timeout))`, falling back to `DEFAULT_TIMEOUT` (= 20) when `None`. - **verify** (Optional[bool]) - Optional - Deprecated. If provided, emits `DeprecationWarning`. Stored as `self.verify` (`True` when `None`). - **proxy** (Optional[str]) - Optional - Deprecated. If provided, emits `DeprecationWarning`; forwarded to httpx. - **http_client** (Optional[httpx.Client]) - Optional - Pre-configured httpx client. When given, its `base_url` is overwritten with `url` and its headers are updated with the merged headers; all other httpx options are ignored. ### Instance Attributes - **self.verify** (bool) - `True` unless `verify=False` was passed. - **self.timeout** (int) - `abs(timeout)` if given else `DEFAULT_TIMEOUT` (20). - **self.session** (httpx.Client) - The underlying httpx client (also available as `self._client` via the bucket API base). ### Deprecation Warnings All `DeprecationWarning` with `stacklevel=2`: non-`None` `timeout`, `verify`, or `proxy` trigger a warning telling you to configure these on the http client instead. ``` -------------------------------- ### GET /object/{bucket}/{path} Source: https://github.com/supabase/storage-py/blob/main/_autodocs/endpoints.md Downloads an object or checks existence. Invoked by download(path, options={}) and exists(path) (HEAD). Returns bytes or boolean. ```APIDOC ## GET /object/{bucket}/{path} ### Description Downloads an object or checks existence. Invoked by download(path, options={}) and exists(path) (HEAD). ### Method GET (or HEAD for exists) ### Endpoint /object/{bucket}/{path} ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket id. - **path** (string) - Required - The object path. ### Request Body None ### Response #### Success Response (200) - For download: raw object bytes. - For HEAD: headers only. #### Response Example Binary data ### Status Codes - 200 OK - 404 Object not found (StorageApiError) ``` -------------------------------- ### GET /render/image/public/{bucket}/{path}?{transform} Source: https://github.com/supabase/storage-py/blob/main/_autodocs/endpoints.md Constructs a public URL for a transformed image. Used by get_public_url() when options["transform"] is set. Not an actual request. ```APIDOC ## GET /render/image/public/{bucket}/{path}?{transform} ### Description Constructs a public URL for a transformed image. Used by get_public_url() when options["transform"] is set. Not an actual request. ### Method GET (URL construction only) ### Endpoint /render/image/public/{bucket}/{path}?{transform} ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket id. - **path** (string) - Required - The object path. #### Query Parameters - **width** (integer) - Optional - Transform width. - **height** (integer) - Optional - Transform height. - **resize** (string) - Optional - Resize mode. - **format** (string) - Optional - Output format. - **quality** (integer) - Optional - Quality percentage. ### Response Returns a string URL. ``` -------------------------------- ### create_signed_upload_url method implementation Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Creates a signed upload URL by posting to /object/upload/sign/{bucket}/{path}. Resolves the returned relative URL against the client base URL and extracts the token query parameter. Throws StorageException if no token is present. ```python async def create_signed_upload_url(self, path: str) -> SignedUploadURL: """ Creates a signed upload URL. Parameters ---------- path The file path, including the file name. For example `folder/image.png`. """ _path = self._get_final_path(path) response = await self._request("POST", f"/object/upload/sign/{_path}") data = response.json() full_url: urllib.parse.ParseResult = urllib.parse.urlparse( str(self._client.base_url) + cast(str, data["url"]).lstrip("/") ) query_params = urllib.parse.parse_qs(full_url.query) if not query_params.get("token"): raise StorageException("No token sent by the API") return { "signed_url": full_url.geturl(), "signedUrl": full_url.geturl(), "token": query_params["token"][0], "path": path, } ``` -------------------------------- ### AsyncBucketProxy.list(path, options) Source: https://github.com/supabase/storage-py/blob/main/docs/api/bucket.rst Lists all files within a bucket or a specific folder. Supports search options like limit, offset, sortBy, and search. ```APIDOC ## AsyncBucketProxy.list(path, options) ### Description Lists all the files within a bucket. ### Method async list(path: str | None = None, options: ListBucketFilesOptions | None = None) -> list[dict[str, str]] ### Parameters - **path** (str | None) - Optional - The folder path. - **options** (ListBucketFilesOptions | None) - Optional - Search options, including limit, offset, sortBy and search. ### Returns list[dict[str, str]] - A list of dictionaries containing file information. ``` -------------------------------- ### GET /render/image/authenticated/{bucket}/{path}?{transform} Source: https://github.com/supabase/storage-py/blob/main/_autodocs/endpoints.md Downloads a transformed image. Invoked by download() when options["transform"] is set. Returns transformed image bytes. ```APIDOC ## GET /render/image/authenticated/{bucket}/{path}?{transform} ### Description Downloads a transformed image. Invoked by download() when options["transform"] is set. ### Method GET ### Endpoint /render/image/authenticated/{bucket}/{path}?{transform} ### Parameters #### Path Parameters - **bucket** (string) - Required - The bucket id. - **path** (string) - Required - The object path. #### Query Parameters - **width** (integer) - Optional - Transform width. - **height** (integer) - Optional - Transform height. - **resize** (string) - Optional - Resize mode. - **format** (string) - Optional - Output format. - **quality** (integer) - Optional - Quality percentage. ### Response #### Success Response (200) Transformed image bytes. ``` -------------------------------- ### List bucket files method Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Lists files in a bucket based on a path prefix and search options. ```python def list( self, path: Optional[str] = None, options: Optional[ListBucketFilesOptions] = None, ) -> list[dict[str, str]]: ``` -------------------------------- ### URLOptions Source: https://github.com/supabase/storage-py/blob/main/_autodocs/types.md Options for creating signed URLs and getting public URLs. The download field controls attachment download behavior, and transform switches to the image render path. ```APIDOC ## URLOptions ### Description Options for creating signed URLs and getting public URLs. The download field controls attachment download behavior, and transform switches to the image render path. ### Fields - `download` (Union[str, bool]) - Optional - True appends bare &download; a string appends &download={value} (forces attachment download) - `transform` (TransformOptions) - Optional - Image transform; switches the render path to render/image ### Accepted By - `create_signed_url(path, expires_in, options={})` - `get_public_url(path, options={})` ``` -------------------------------- ### Get public URL with get_public_url() Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Builds a public URL for a file locally without making an HTTP request. The transform and download options modify the resulting URL structure. ```python async def get_public_url(self, path: str, options: URLOptions = {}) -> str: ``` -------------------------------- ### SyncStorageClient create_signed_url and create_signed_urls Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Demonstrates how to create signed URLs for single and multiple files, including error handling for StorageApiError. ```APIDOC ## SyncStorageClient create_signed_url and create_signed_urls ### Description Creates signed URLs for accessing files with temporary permissions. Supports both single and batch operations. ### Method create_signed_url, create_signed_urls ### Endpoint Not applicable (SDK method) ### Parameters #### create_signed_url - **path** (str) - Required - The path of the file. - **expires_in** (int) - Required - Expiration time in seconds. - **options** (dict) - Optional - Additional options, e.g., download. #### create_signed_urls - **paths** (list[str]) - Required - List of file paths. - **expires_in** (int) - Required - Expiration time in seconds. ### Request Example ```python from storage3 import SyncStorageClient from storage3.exceptions import StorageApiError client = SyncStorageClient("https://x.supabase.co/storage/v1", {"apiKey": "k"}) bucket = client.from_("files") try: signed = bucket.create_signed_url("reports/q1.pdf", expires_in=3600, options={"download": True}) print(signed["signedURL"]) many = bucket.create_signed_urls(["a.pdf", "b.pdf"], 600) for item in many: print(item.get("error"), item["path"], item["signedURL"]) except StorageApiError as err: print(f"status={err.status}, code={err.code}, message={err.message}") finally: client.session.close() ``` ### Response #### Success Response - **create_signed_url**: SignedUrlResponse - Contains signedURL. - **create_signed_urls**: list[CreateSignedUrlResponse] - Each item contains path, signedURL, and optionally error. #### Response Example ```python # create_signed_url response signed["signedURL"] # create_signed_urls response for item in many: print(item.get("error"), item["path"], item["signedURL"]) ``` ``` -------------------------------- ### How to catch StorageApiError Source: https://github.com/supabase/storage-py/blob/main/_autodocs/errors.md Example of catching StorageApiError when calling a client method like get_bucket. It shows accessing the status, code, message attributes and the to_dict() method. Also demonstrates catching the parent StorageException class as a fallback since StorageApiError is a subclass. ```python from storage3.exceptions import StorageApiError from storage3.utils import StorageException try: client.get_bucket("missing") except StorageApiError as err: print(err.status) # int, e.g. 404 print(err.code) # str error code from the API print(err.message) # human-readable message print(err.to_dict()) # {'name': ..., 'code': ..., 'message': ..., 'status': ...} except StorageException as err: # StorageApiError is a subclass print(str(err)) ``` -------------------------------- ### AsyncBucket.list Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Lists files in a folder. Returns a list of dictionaries. ```APIDOC ## AsyncBucket.list ### Description Lists files in a folder. Returns a list of dictionaries. ### Method list ### Parameters - **path** (str) - Required - The folder path. - **options** (dict) - Optional - List options such as limit and sortBy. ### Returns - **list[dict[str, str]]** - List of file metadata dictionaries. ### Throws - **StorageApiError** - On any non-2xx HTTP response. ### Example ```python files = await bucket.list("folder", {"limit": 10, "sortBy": {"column": "name", "order": "asc"}}) print(files) ``` ``` -------------------------------- ### create_signed_urls(paths, expires_in, options={}) -> list[CreateSignedUrlResponse] Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Creates signed download URLs for multiple file paths. Posts to POST /object/sign/{bucket} with the list of paths and expiration time. Returns a list of CreateSignedUrlResponse TypedDicts, one per path. ```APIDOC ## create_signed_urls(paths, expires_in, options={}) -> list[CreateSignedUrlResponse] ### Description Creates signed download URLs for multiple file paths. Posts to POST /object/sign/{bucket} with the list of paths and expiration time. Returns a list of CreateSignedUrlResponse TypedDicts, one per path. ### Method POST ### Endpoint /object/sign/{bucket} ### Parameters #### Path Parameters - **bucket** (str) - Required - The bucket name (implicitly from the client). #### Request Body - **paths** (list[str]) - Required - File paths to download. - **expiresIn** (str) - Required - Seconds until the signed URLs expire (sent as the string form of the number). - **download** (Union[str, bool]) - Optional - If truthy, adds `download` to the body and appends `&download=` (when True) or `&download={value}` to the final URL. ### Request Example { "paths": ["folder/image1.png", "folder/image2.png"], "expiresIn": "3600", "download": true } ### Response #### Success Response (200) - **error** (Optional[str]) - Per-path error message (None/absent on success). - **path** (str) - The file path. - **signedURL** (str) - The signed URL. - **signedUrl** (str) - Alias for signedURL. #### Response Example [ { "error": null, "path": "folder/image1.png", "signedURL": "https://example.com/object/sign/bucket/path1?token=abc", "signedUrl": "https://example.com/object/sign/bucket/path1?token=abc" }, { "error": null, "path": "folder/image2.png", "signedURL": "https://example.com/object/sign/bucket/path2?token=def", "signedUrl": "https://example.com/object/sign/bucket/path2?token=def" } ] ``` -------------------------------- ### create_bucket Method Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-bucket-api.md Creates a new storage bucket with optional configuration settings. ```python async def create_bucket( self, id: str, name: Optional[str] = None, options: Optional[CreateOrUpdateBucketOptions] = None, ) -> dict[str, str]: """Creates a new storage bucket. Parameters ---------- id A unique identifier for the bucket you are creating. name A name for the bucket you are creating. If not passed, the id is used as the name as well. options Extra options to send while creating the bucket. Valid options are `public`, `file_size_limit` and `allowed_mime_types`. """ json: dict[str, Any] = {"id": id, "name": name or id} if options: json.update(**options) res = await self._request( "POST", "/bucket", json=json, ) return res.json() ``` -------------------------------- ### list_buckets() -> list[SyncBucket] Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-bucket-api.md Retrieves the details of all storage buckets within an existing product. Returns a list of SyncBucket objects. ```APIDOC ## GET /bucket ### Description Retrieves the details of all storage buckets within an existing product. ### Method GET ### Endpoint /bucket ### Response #### Success Response (200) - **body** (list[SyncBucket]) - List of SyncBucket objects. #### Response Example [ { "id": "bucket-id", "name": "bucket-name", "owner": "owner-id", "public": false, "created_at": "2023-01-01T00:00:00Z", "updated_at": "2023-01-01T00:00:00Z", "file_size_limit": null, "allowed_mime_types": null } ] ``` -------------------------------- ### SyncBucket and SyncBucketProxy Class Definitions Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-bucket.md Definitions for SyncBucketActionsMixin, SyncBucket, and SyncBucketProxy as found in storage3/_sync/file_api.py. ```python class SyncBucketActionsMixin: """Functions needed to access the file API.""" id: str _client: Client class SyncBucket(BaseBucket): """Represents a storage bucket.""" @dataclass class SyncBucketProxy(SyncBucketActionsMixin): """A bucket proxy, this contains the minimum required fields to query the File API.""" id: str _client: Client = field(repr=False) ``` -------------------------------- ### Signed-URL flow with error handling Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Shows how to create a signed upload URL, upload data to it, and handle potential StorageApiError or StorageException errors. ```python import asyncio from storage3 import AsyncStorageClient from storage3.exceptions import StorageApiError from storage3.utils import StorageException async def main() -> None: client = AsyncStorageClient("https://x.supabase.co/storage/v1", {"apiKey": "k"}) bucket = client.from_("avatars") try: signed = await bucket.create_signed_upload_url("uploads/notes.txt") resp = await bucket.upload_to_signed_url( "uploads/notes.txt", signed["token"], b"hello", {"content-type": "text/plain"} ) print(resp.fullPath) except StorageApiError as err: print(f"API error {err.status}: {err.code} {err.message}") except StorageException as err: print(f"Client error: {err}") finally: await client.session.aclose() asyncio.run(main()) ``` -------------------------------- ### list_buckets() method Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-bucket-api.md Retrieves the details of all storage buckets within an existing product. Returns a list of SyncBucket pydantic models. ```python def list_buckets(self) -> list[SyncBucket]: """Retrieves the details of all storage buckets within an existing product.""" res = self._request("GET", "/bucket") return [SyncBucket(**bucket) for bucket in res.json()] ``` -------------------------------- ### storage3.create_client(url: str, headers: dict[str, str], is_async: Literal[False]) -> SyncStorageClient Source: https://github.com/supabase/storage-py/blob/main/docs/api/client.rst Creates a synchronous client instance for interacting with the Storage API. This is the entrypoint for sync usage. ```APIDOC ## create_client(url: str, headers: dict[str, str], is_async: Literal[False]) -> SyncStorageClient ### Description Creates a synchronous client instance for interacting with the Storage API. This is the entrypoint for sync usage. ### Parameters - **url** (str) - Required - The base URL of the Storage API. - **headers** (dict[str, str]) - Required - Headers to include in requests. - **is_async** (Literal[False]) - Required - Must be False to return a sync client. ### Returns - **SyncStorageClient** - An instance of the sync client. ``` -------------------------------- ### AsyncStorageBucketAPI Constructor Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-storage-bucket-api.md The constructor initializes the class with an httpx AsyncClient session. ```python def __init__(self, session: AsyncClient) -> None: ``` -------------------------------- ### create_signed_upload_url(path) -> SignedUploadURL Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/async-bucket.md Creates a signed upload URL for a file path. Posts to POST /object/upload/sign/{bucket}/{path}, resolves the returned relative URL against the client base URL, and extracts the token query parameter. Returns a SignedUploadURL TypedDict. ```APIDOC ## create_signed_upload_url(path) -> SignedUploadURL ### Description Creates a signed upload URL for a file path. Posts to POST /object/upload/sign/{bucket}/{path}, resolves the returned relative URL against the client base URL, and extracts the token query parameter. Returns a SignedUploadURL TypedDict. ### Method POST ### Endpoint /object/upload/sign/{bucket}/{path} ### Parameters #### Path Parameters - **bucket** (str) - Required - The bucket name (implicitly from the client). - **path** (str) - Required - The file path, including the file name. For example `folder/image.png`. ### Request Example POST /object/upload/sign/{bucket}/{path} ### Response #### Success Response (200) - **signed_url** (str) - The full signed URL. - **signedUrl** (str) - Alias for signed_url. - **token** (str) - The token extracted from the query parameter. - **path** (str) - The original file path. #### Response Example { "signed_url": "https://example.com/object/upload/sign/bucket/path?token=abc", "signedUrl": "https://example.com/object/upload/sign/bucket/path?token=abc", "token": "abc", "path": "folder/image.png" } ### Errors - **StorageException** - Thrown when the response URL carries no `token` query parameter. - **StorageApiError** - Thrown on HTTP error status. ``` -------------------------------- ### SyncStorageBucketAPI Constructor Source: https://github.com/supabase/storage-py/blob/main/_autodocs/api-reference/sync-storage-bucket-api.md The constructor for SyncStorageBucketAPI, requiring an httpx.Client session. ```python def __init__(self, session: Client) -> None: ```