SDK Configuration
Production settings for VocaFuse SDKs—timeouts, retry behavior, debug logging, and error handling patterns.
Timeout
Set request timeout in seconds:
- Python
- Node.js
from vocafuse import Client
import os
client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
timeout=30 # 30 seconds (default: 10)
)
const { Client } = require('vocafuse-node');
const client = new Client({
apiKey: process.env.VOCAFUSE_API_KEY,
apiSecret: process.env.VOCAFUSE_API_SECRET,
timeout: 30000, // 30 seconds in milliseconds (default: 30000)
});
For long-running operations or slow networks, increase the timeout. For latency-sensitive applications, keep it lower and handle timeouts gracefully.
Retry Configuration
Configure automatic retries for transient failures:
- Python
- Node.js
client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
max_retries=3, # Number of retry attempts (default: 2)
retry_delay=1.0 # Initial delay between retries in seconds (default: 0.5)
)
const { Client } = require('vocafuse-node');
const client = new Client({
apiKey: process.env.VOCAFUSE_API_KEY,
apiSecret: process.env.VOCAFUSE_API_SECRET,
retry: {
maxRetries: 3, // Number of retry attempts (default: 3)
retryDelay: 1000, // Initial delay between retries in ms (default: 1000)
// retryableStatuses: [408, 429, 500, 502, 503, 504], // Optional override
},
});
The SDK uses exponential backoff—each retry waits longer than the previous. With max_retries=3 and retry_delay=1.0:
| Attempt | Wait Time |
|---|---|
| 1 | Immediate |
| 2 | 1 second |
| 3 | 2 seconds |
| 4 | 4 seconds |
Note: Only idempotent requests (GET, DELETE) and 5xx errors are retried automatically. POST requests are not retried to avoid duplicate operations.
Debug Logging
Enable verbose logging for development and troubleshooting:
- Python
- Node.js
import logging
# Set logging level before creating client
logging.basicConfig(level=logging.DEBUG)
client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
debug=True
)
const { Client } = require('vocafuse-node');
const client = new Client({
apiKey: process.env.VOCAFUSE_API_KEY,
apiSecret: process.env.VOCAFUSE_API_SECRET,
// No built-in `debug` flag in the Node SDK; use your own logging
});
async function getRecording(id) {
console.debug('[VocaFuse] Fetching recording', id);
const response = await client.recordings(id).get();
console.debug('[VocaFuse] Response status:', response.statusCode);
return response;
}
Debug mode logs:
- Full request URLs and headers
- Request/response bodies (credentials redacted)
- Retry attempts and timing
- Connection pool status
Disable debug logging in production—it may expose sensitive data in logs.
Error Handling
The SDK raises specific exceptions for different error scenarios:
- Python
- Node.js
from vocafuse import (
Client,
VocaFuseError,
AuthenticationError,
RateLimitError,
ValidationError,
NotFoundError
)
client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET']
)
try:
recording = client.recordings.get('rec_123')
except AuthenticationError:
# Invalid API credentials - check your keys
logging.error('Invalid API credentials')
except RateLimitError as e:
# Too many requests - back off and retry
logging.warning(f'Rate limited. Retry after {e.retry_after} seconds')
time.sleep(e.retry_after)
except NotFoundError:
# Resource doesn't exist
logging.warning('Recording not found')
except ValidationError as e:
# Invalid request parameters
logging.error(f'Validation error: {e.message}')
except VocaFuseError as e:
# Catch-all for other API errors
logging.error(f'API error: {e.message}')
const {
Client,
VocaFuseError,
AuthenticationError,
RateLimitError,
ValidationError,
NotFoundError,
} = require('vocafuse-node');
const client = new Client({
apiKey: process.env.VOCAFUSE_API_KEY,
apiSecret: process.env.VOCAFUSE_API_SECRET,
});
async function getRecordingWithHandling(id) {
try {
const recording = await client.recordings(id).get();
return recording;
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API credentials');
} else if (error instanceof RateLimitError) {
console.warn(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof NotFoundError) {
console.warn('Recording not found');
} else if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
} else if (error instanceof VocaFuseError) {
console.error('API error:', error.friendlyMessage);
} else {
console.error('Unexpected error:', error);
}
throw error;
}
}
Exception Types
| Exception | HTTP Status | Description | Common Causes |
|---|---|---|---|
AuthenticationError | 401 | Invalid API credentials | Wrong API key/secret, expired credentials |
RateLimitError | 429 | Rate limit exceeded | Too many requests, implement backoff |
ValidationError | 400 | Invalid request parameters | Missing required fields, invalid formats |
NotFoundError | 404 | Resource not found | Invalid recording ID, deleted resource |
VocaFuseError | 5xx | Server error | Transient issues, retry with backoff |
Rate Limit Handling
When rate limited, the exception includes retry timing:
- Python
- Node.js
except RateLimitError as e:
print(f"Rate limited. Retry after: {e.retry_after} seconds")
print(f"Limit: {e.limit}")
print(f"Remaining: {e.remaining}")
# Implement exponential backoff
time.sleep(e.retry_after)
const { Client, RateLimitError } = require('vocafuse-node');
const client = new Client({
apiKey: process.env.VOCAFUSE_API_KEY,
apiSecret: process.env.VOCAFUSE_API_SECRET,
});
async function listWithRateLimitHandling() {
try {
return await client.recordings.list();
} catch (error) {
if (error instanceof RateLimitError && error.retryAfter) {
console.warn(`Rate limited. Retry after: ${error.retryAfter} seconds`);
await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000));
return client.recordings.list();
}
throw error;
}
}
Django Integration
For Django applications, here's a complete integration pattern:
# views.py
import json
import os
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from vocafuse import Client, AccessToken, RequestValidator
client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET']
)
@require_POST
def generate_token(request):
"""Generate JWT token for frontend SDK authentication."""
user_id = request.user.id
token = AccessToken(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
identity=str(user_id)
)
return JsonResponse(token(expires_in=3600))
@csrf_exempt
@require_POST
def handle_webhook(request):
"""Receive and process VocaFuse webhook events."""
validator = RequestValidator(os.environ['VOCAFUSE_WEBHOOK_SECRET'])
payload = request.body.decode('utf-8')
signature = request.headers.get('X-VocaFuse-Signature')
if not validator.validate(payload, signature):
return JsonResponse({'error': 'Invalid signature'}, status=401)
data = json.loads(payload)
if data['event'] == 'recording.transcribed':
recording_id = data['recording']['id']
# Process transcription...
return JsonResponse({'status': 'received'})
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/vocafuse-token/', views.generate_token, name='vocafuse_token'),
path('api/webhooks/vocafuse/', views.handle_webhook, name='vocafuse_webhook'),
]
Environment-Specific Configuration
Use different settings per environment:
- Python
- Node.js
import os
# Determine environment
ENV = os.environ.get('ENVIRONMENT', 'development')
# Environment-specific defaults
CONFIG = {
'development': {
'timeout': 30,
'max_retries': 1,
'debug': True
},
'staging': {
'timeout': 15,
'max_retries': 2,
'debug': True
},
'production': {
'timeout': 10,
'max_retries': 3,
'debug': False
}
}
client = Client(
api_key=os.environ['VOCAFUSE_API_KEY'],
api_secret=os.environ['VOCAFUSE_API_SECRET'],
**CONFIG[ENV]
)
const { Client } = require('vocafuse-node');
const ENV = process.env.ENVIRONMENT || 'development';
const CONFIG = {
development: {
timeout: 30000,
retry: { maxRetries: 1, retryDelay: 500 },
},
staging: {
timeout: 15000,
retry: { maxRetries: 2, retryDelay: 1000 },
},
production: {
timeout: 10000,
retry: { maxRetries: 3, retryDelay: 1000 },
},
};
const client = new Client({
apiKey: process.env.VOCAFUSE_API_KEY,
apiSecret: process.env.VOCAFUSE_API_SECRET,
...CONFIG[ENV],
});
Next Steps
- Python Speech to Text Tutorial — Build a complete Python backend
- Webhooks Guide — Production webhook patterns
- API Reference — Full endpoint documentation