0
# Client Management
1
2
Client creation, configuration, and lifecycle management for both synchronous and asynchronous operations. Provides factory functions and client classes with comprehensive configuration options.
3
4
## Capabilities
5
6
### Synchronous Client Creation
7
8
Creates a synchronous Supabase client instance for standard blocking operations.
9
10
```python { .api }
11
def create_client(
12
supabase_url: str,
13
supabase_key: str,
14
options: Optional[ClientOptions] = None
15
) -> SyncClient:
16
"""
17
Create synchronous Supabase client.
18
19
Parameters:
20
- supabase_url: The URL to the Supabase instance
21
- supabase_key: The API key for the Supabase instance
22
- options: Optional client configuration
23
24
Returns:
25
SyncClient instance
26
27
Raises:
28
SupabaseException: If URL or key is invalid
29
"""
30
```
31
32
**Usage Example:**
33
34
```python
35
from supabase import create_client, ClientOptions
36
37
# Basic client creation
38
client = create_client("https://project.supabase.co", "your-api-key")
39
40
# With custom options
41
options = ClientOptions(
42
schema="private",
43
auto_refresh_token=False,
44
persist_session=True
45
)
46
client = create_client("https://project.supabase.co", "your-api-key", options)
47
```
48
49
### Asynchronous Client Creation
50
51
Creates an asynchronous Supabase client instance for non-blocking operations.
52
53
```python { .api }
54
async def create_async_client(
55
supabase_url: str,
56
supabase_key: str,
57
options: Optional[AsyncClientOptions] = None
58
) -> AsyncClient:
59
"""
60
Create asynchronous Supabase client.
61
62
Parameters:
63
- supabase_url: The URL to the Supabase instance
64
- supabase_key: The API key for the Supabase instance
65
- options: Optional async client configuration
66
67
Returns:
68
AsyncClient instance
69
70
Raises:
71
SupabaseException: If URL or key is invalid
72
"""
73
74
# Alternative name
75
async def acreate_client(
76
supabase_url: str,
77
supabase_key: str,
78
options: Optional[AsyncClientOptions] = None
79
) -> AsyncClient:
80
"""Alias for create_async_client"""
81
```
82
83
**Usage Example:**
84
85
```python
86
from supabase import create_async_client, AsyncClientOptions
87
import asyncio
88
89
async def main():
90
# Basic async client creation
91
client = await create_async_client("https://project.supabase.co", "your-api-key")
92
93
# With custom options
94
options = AsyncClientOptions(
95
schema="private",
96
auto_refresh_token=False
97
)
98
client = await create_async_client("https://project.supabase.co", "your-api-key", options)
99
100
asyncio.run(main())
101
```
102
103
### Synchronous Client Class
104
105
Main synchronous client class providing access to all Supabase services.
106
107
```python { .api }
108
class SyncClient:
109
"""Main synchronous Supabase client class."""
110
111
def __init__(
112
self,
113
supabase_url: str,
114
supabase_key: str,
115
options: Optional[ClientOptions] = None
116
):
117
"""
118
Initialize client instance.
119
120
Parameters:
121
- supabase_url: Supabase instance URL
122
- supabase_key: API key
123
- options: Client configuration options
124
"""
125
126
@classmethod
127
def create(
128
cls,
129
supabase_url: str,
130
supabase_key: str,
131
options: Optional[ClientOptions] = None
132
) -> 'SyncClient':
133
"""Factory method for creating client with session handling."""
134
135
# Service properties
136
@property
137
def auth(self) -> SyncSupabaseAuthClient:
138
"""Authentication client"""
139
140
@property
141
def postgrest(self) -> SyncPostgrestClient:
142
"""Database client"""
143
144
@property
145
def storage(self) -> SupabaseStorageClient:
146
"""Storage client"""
147
148
@property
149
def functions(self) -> SyncFunctionsClient:
150
"""Functions client"""
151
152
@property
153
def realtime(self) -> SyncRealtimeClient:
154
"""Realtime client"""
155
```
156
157
### Asynchronous Client Class
158
159
Main asynchronous client class providing access to all Supabase services with async/await support.
160
161
```python { .api }
162
class AsyncClient:
163
"""Main asynchronous Supabase client class."""
164
165
def __init__(
166
self,
167
supabase_url: str,
168
supabase_key: str,
169
options: Optional[AsyncClientOptions] = None
170
):
171
"""
172
Initialize async client instance.
173
174
Parameters:
175
- supabase_url: Supabase instance URL
176
- supabase_key: API key
177
- options: Async client configuration options
178
"""
179
180
@classmethod
181
async def create(
182
cls,
183
supabase_url: str,
184
supabase_key: str,
185
options: Optional[AsyncClientOptions] = None
186
) -> 'AsyncClient':
187
"""Async factory method for creating client with session handling."""
188
189
# Service properties (same as sync but with async clients)
190
@property
191
def auth(self) -> AsyncSupabaseAuthClient:
192
"""Async authentication client"""
193
194
@property
195
def postgrest(self) -> AsyncPostgrestClient:
196
"""Async database client"""
197
198
@property
199
def storage(self) -> AsyncSupabaseStorageClient:
200
"""Async storage client"""
201
202
@property
203
def functions(self) -> AsyncFunctionsClient:
204
"""Async functions client"""
205
206
@property
207
def realtime(self) -> AsyncRealtimeClient:
208
"""Async realtime client"""
209
```
210
211
### Client Configuration Options
212
213
Configuration options for customizing client behavior and service integration.
214
215
```python { .api }
216
@dataclass
217
class ClientOptions:
218
"""Synchronous client configuration options."""
219
220
schema: str = "public"
221
"""PostgreSQL schema for database operations"""
222
223
headers: Dict[str, str] = field(default_factory=lambda: {"X-Client-Info": f"supabase-py/{__version__}"})
224
"""Custom headers for HTTP requests (includes default X-Client-Info header)"""
225
226
auto_refresh_token: bool = True
227
"""Automatically refresh authentication tokens"""
228
229
persist_session: bool = True
230
"""Persist user session to storage"""
231
232
storage: SyncSupportedStorage = field(default_factory=SyncMemoryStorage)
233
"""Storage provider for session persistence"""
234
235
realtime: Optional[RealtimeClientOptions] = None
236
"""Realtime client configuration"""
237
238
httpx_client: Optional[SyncHttpxClient] = None
239
"""Custom HTTP client for requests"""
240
241
postgrest_client_timeout: Union[int, float, Timeout] = DEFAULT_POSTGREST_CLIENT_TIMEOUT
242
"""Database client request timeout"""
243
244
storage_client_timeout: Union[int, float, Timeout] = DEFAULT_STORAGE_CLIENT_TIMEOUT
245
"""Storage client request timeout"""
246
247
function_client_timeout: Union[int, float, Timeout] = DEFAULT_FUNCTION_CLIENT_TIMEOUT
248
"""Functions client request timeout"""
249
250
flow_type: AuthFlowType = "pkce"
251
"""Authentication flow type (pkce, implicit)"""
252
253
def replace(self, **kwargs) -> 'ClientOptions':
254
"""Create new ClientOptions instance with specified changes."""
255
256
@dataclass
257
class AsyncClientOptions(ClientOptions):
258
"""Asynchronous client configuration options."""
259
260
storage: AsyncSupportedStorage = field(default_factory=AsyncMemoryStorage)
261
"""Async storage provider for session persistence"""
262
263
httpx_client: Optional[AsyncHttpxClient] = None
264
"""Custom async HTTP client for requests"""
265
266
def replace(self, **kwargs) -> 'AsyncClientOptions':
267
"""Create new AsyncClientOptions instance with specified changes."""
268
```
269
270
**Usage Example:**
271
272
```python
273
from supabase import ClientOptions, AsyncClientOptions
274
from supabase_auth import SyncMemoryStorage
275
from httpx import Client as SyncHttpxClient
276
277
# Sync client options
278
sync_options = ClientOptions(
279
schema="private",
280
headers={"Custom-Header": "value"},
281
auto_refresh_token=True,
282
persist_session=True,
283
storage=SyncMemoryStorage(),
284
httpx_client=SyncHttpxClient(timeout=30),
285
flow_type="pkce"
286
)
287
288
# Create new options with changes
289
modified_options = sync_options.replace(
290
schema="public",
291
auto_refresh_token=False
292
)
293
294
# Async client options
295
async_options = AsyncClientOptions(
296
schema="private",
297
auto_refresh_token=True
298
)
299
```
300
301
### Error Handling
302
303
```python { .api }
304
class SupabaseException(Exception):
305
"""Base exception for client errors."""
306
307
def __init__(self, message: str):
308
self.message = message
309
super().__init__(self.message)
310
311
# Sync and async variants
312
class SyncSupabaseException(SupabaseException):
313
"""Synchronous client exception"""
314
315
class AsyncSupabaseException(SupabaseException):
316
"""Asynchronous client exception"""
317
```
318
319
**Common Error Scenarios:**
320
321
```python
322
from supabase import create_client, SupabaseException
323
324
try:
325
# Invalid URL format
326
client = create_client("invalid-url", "key")
327
except SupabaseException as e:
328
print(f"Client creation failed: {e.message}")
329
330
try:
331
# Missing required parameters
332
client = create_client("", "")
333
except SupabaseException as e:
334
print(f"Missing parameters: {e.message}")
335
```