0
# Authentication and Configuration
1
2
API key management, Google Colab integration, and client configuration. Handles credential discovery from environment variables, Google Colab userdata, and provides custom client initialization with timeout and authentication settings.
3
4
## Capabilities
5
6
### Authentication
7
8
Secure API key management with multiple credential sources and automatic discovery from environment variables and Google Colab.
9
10
```python { .api }
11
def fetch_credentials() -> str:
12
"""
13
Fetch API credentials from available sources.
14
15
Checks in order:
16
1. FAL_KEY environment variable
17
2. FAL_KEY_ID and FAL_KEY_SECRET environment variables (combined as key_id:secret)
18
3. Google Colab userdata (if running in Colab)
19
20
Returns:
21
str: The API key or key_id:secret combination
22
23
Raises:
24
MissingCredentialsError: If no credentials found in any source
25
"""
26
27
class MissingCredentialsError(Exception):
28
"""Raised when API credentials cannot be found or are invalid."""
29
```
30
31
### Environment Variable Authentication
32
33
The primary authentication method using environment variables:
34
35
```bash
36
# Simple API key
37
export FAL_KEY="your-api-key-here"
38
39
# Or key ID and secret (for service accounts)
40
export FAL_KEY_ID="your-key-id"
41
export FAL_KEY_SECRET="your-key-secret"
42
```
43
44
Usage example:
45
```python
46
import os
47
import fal_client
48
49
# Set credentials programmatically (not recommended for production)
50
os.environ["FAL_KEY"] = "your-api-key"
51
52
# Credentials are automatically discovered
53
response = fal_client.run("fal-ai/fast-sdxl", arguments={"prompt": "test"})
54
```
55
56
### Google Colab Integration
57
58
Automatic credential discovery for Google Colab environments using Colab's secure userdata storage.
59
60
```python { .api }
61
def is_google_colab() -> bool:
62
"""
63
Check if the current environment is Google Colab.
64
65
Returns:
66
bool: True if running in Google Colab, False otherwise
67
"""
68
69
def get_colab_token() -> str | None:
70
"""
71
Get API token from Google Colab userdata if available.
72
73
Returns:
74
str | None: The API token from Colab userdata, or None if not available
75
"""
76
```
77
78
Google Colab usage:
79
```python
80
# In Google Colab, store your API key in userdata as "FAL_KEY"
81
# Then use fal_client normally - credentials are auto-discovered
82
import fal_client
83
84
response = fal_client.run("fal-ai/fast-sdxl", arguments={"prompt": "a colab test"})
85
```
86
87
### Client Configuration
88
89
Explicit client instantiation with custom configuration for advanced use cases requiring specific timeout settings or credential management.
90
91
```python { .api }
92
class SyncClient:
93
"""Synchronous client for fal.ai API with custom configuration."""
94
95
def __init__(self, key: str | None = None, default_timeout: float = 120.0):
96
"""
97
Initialize synchronous client.
98
99
Parameters:
100
- key: API key (if None, uses fetch_credentials())
101
- default_timeout: Default request timeout in seconds
102
"""
103
104
class AsyncClient:
105
"""Asynchronous client for fal.ai API with custom configuration."""
106
107
def __init__(self, key: str | None = None, default_timeout: float = 120.0):
108
"""
109
Initialize asynchronous client.
110
111
Parameters:
112
- key: API key (if None, uses fetch_credentials())
113
- default_timeout: Default request timeout in seconds
114
"""
115
```
116
117
### Custom Client Usage
118
119
Using explicit client instances for advanced configuration:
120
121
```python
122
import fal_client
123
124
# Create client with custom timeout
125
sync_client = fal_client.SyncClient(default_timeout=60.0)
126
127
# Use client methods directly
128
response = sync_client.run(
129
"fal-ai/fast-sdxl",
130
arguments={"prompt": "test"}
131
)
132
133
# Create async client
134
async_client = fal_client.AsyncClient(
135
key="custom-api-key",
136
default_timeout=180.0
137
)
138
139
# Use async client
140
import asyncio
141
142
async def main():
143
response = await async_client.run(
144
"fal-ai/fast-sdxl",
145
arguments={"prompt": "async test"}
146
)
147
return response
148
149
result = asyncio.run(main())
150
```
151
152
### Environment Configuration
153
154
Configure the fal.ai service endpoint for custom deployments or testing:
155
156
```python { .api }
157
# Environment variable for custom service endpoint
158
# FAL_RUN_HOST: Custom hostname for fal.ai service (default: "fal.run")
159
```
160
161
Usage:
162
```bash
163
# Use custom fal.ai endpoint
164
export FAL_RUN_HOST="custom.fal.run"
165
export FAL_KEY="your-api-key"
166
```
167
168
### Credential Management Patterns
169
170
### Secure Credential Handling
171
172
Best practices for managing API credentials securely:
173
174
```python
175
import os
176
import fal_client
177
from pathlib import Path
178
179
def load_credentials_from_file():
180
"""Load credentials from a secure file."""
181
182
# Load from .env file
183
env_file = Path.home() / ".fal" / "credentials"
184
if env_file.exists():
185
with open(env_file) as f:
186
api_key = f.read().strip()
187
os.environ["FAL_KEY"] = api_key
188
return api_key
189
190
raise fal_client.MissingCredentialsError("No credentials file found")
191
192
def setup_client_with_custom_key(api_key):
193
"""Set up client with explicit API key."""
194
195
# Create clients with explicit key (doesn't use environment)
196
sync_client = fal_client.SyncClient(key=api_key)
197
async_client = fal_client.AsyncClient(key=api_key)
198
199
return sync_client, async_client
200
```
201
202
### Multi-Environment Configuration
203
204
Handle different environments (development, staging, production):
205
206
```python
207
import os
208
import fal_client
209
210
class FalConfig:
211
"""Configuration manager for different environments."""
212
213
def __init__(self, environment="production"):
214
self.environment = environment
215
216
# Environment-specific configuration
217
if environment == "development":
218
os.environ["FAL_RUN_HOST"] = "dev.fal.run"
219
self.timeout = 30.0
220
elif environment == "staging":
221
os.environ["FAL_RUN_HOST"] = "staging.fal.run"
222
self.timeout = 60.0
223
else: # production
224
os.environ["FAL_RUN_HOST"] = "fal.run"
225
self.timeout = 120.0
226
227
def get_client(self):
228
"""Get configured client for the environment."""
229
return fal_client.SyncClient(default_timeout=self.timeout)
230
231
# Usage
232
config = FalConfig("development")
233
client = config.get_client()
234
```
235
236
### Error Handling and Debugging
237
238
Handle authentication errors and debug credential issues:
239
240
```python
241
import fal_client
242
import os
243
244
def diagnose_auth_issues():
245
"""Diagnose and report authentication configuration issues."""
246
247
print("=== fal-client Authentication Diagnosis ===")
248
249
# Check environment variables
250
fal_key = os.getenv("FAL_KEY")
251
fal_key_id = os.getenv("FAL_KEY_ID")
252
fal_key_secret = os.getenv("FAL_KEY_SECRET")
253
254
print(f"FAL_KEY set: {'Yes' if fal_key else 'No'}")
255
if fal_key:
256
print(f"FAL_KEY length: {len(fal_key)}")
257
258
print(f"FAL_KEY_ID set: {'Yes' if fal_key_id else 'No'}")
259
print(f"FAL_KEY_SECRET set: {'Yes' if fal_key_secret else 'No'}")
260
261
# Check Google Colab
262
if fal_client.is_google_colab():
263
print("Google Colab detected")
264
colab_token = fal_client.get_colab_token()
265
print(f"Colab token available: {'Yes' if colab_token else 'No'}")
266
else:
267
print("Not running in Google Colab")
268
269
# Test credential fetch
270
try:
271
credentials = fal_client.fetch_credentials()
272
print(f"Credentials successfully fetched (length: {len(credentials)})")
273
274
# Test API call
275
response = fal_client.run("fal-ai/fast-sdxl", arguments={"prompt": "test"})
276
print("API call successful")
277
278
except fal_client.MissingCredentialsError as e:
279
print(f"Credential error: {e}")
280
except Exception as e:
281
print(f"API error: {e}")
282
283
# Usage for debugging
284
diagnose_auth_issues()
285
```
286
287
### Context Manager for Temporary Credentials
288
289
Use context managers for temporary credential changes:
290
291
```python
292
import fal_client
293
import os
294
from contextlib import contextmanager
295
296
@contextmanager
297
def temporary_credentials(api_key):
298
"""Context manager for temporary API key usage."""
299
300
old_key = os.environ.get("FAL_KEY")
301
os.environ["FAL_KEY"] = api_key
302
303
try:
304
yield
305
finally:
306
if old_key is not None:
307
os.environ["FAL_KEY"] = old_key
308
else:
309
os.environ.pop("FAL_KEY", None)
310
311
# Usage
312
with temporary_credentials("temp-api-key"):
313
response = fal_client.run("fal-ai/fast-sdxl", arguments={"prompt": "test"})
314
print(response)
315
316
# Original credentials restored automatically
317
```