SDKs
⚠️ Future Content: The detailed SDK implementation guides and language-specific integration patterns below will be provided in future documentation updates. Advanced SDK features and enterprise development tools are being developed for production environments.
Filedgr provides official Software Development Kits (SDKs) for popular programming languages, making integration faster and more reliable than direct API calls.
Available SDKs
JavaScript/TypeScript SDK
npm package: @filedgr/sdk
Full-featured SDK with TypeScript support, ideal for:
- Node.js backend applications
- Browser-based applications
- React/Vue/Angular frontends
- Serverless functions (AWS Lambda, Vercel, etc.)
Python SDK
pip package: filedgr-python
Pythonic SDK perfect for:
- Data science applications
- AI/ML workflows
- Django/Flask applications
- Automation scripts and data pipelines
Go SDK
go module: github.com/filedgr/go-sdk
High-performance SDK for:
- Microservices architectures
- High-throughput applications
- Cloud-native deployments
- Kubernetes workloads
JavaScript/TypeScript SDK
Installation
npm install @filedgr/sdk
# or
yarn add @filedgr/sdk
Quick Start
import { Filedgr } from '@filedgr/sdk';
const filedgr = new Filedgr({
apiKey: process.env.FILEDGR_API_KEY,
apiSecret: process.env.FILEDGR_API_SECRET,
environment: 'production' // or 'test'
});
// Create a vault
const vault = await filedgr.vaults.create({
templateId: 'general-template-v1',
name: 'My First Vault',
metadata: {
category: 'documents',
project: 'api-integration'
}
});
console.log(`Vault created: ${vault.id}`);
// Upload a file
const file = await filedgr.vaults.uploadFile(vault.id, {
file: fileBuffer,
filename: 'document.pdf',
metadata: {
type: 'certificate',
importance: 'high'
}
});
console.log(`File uploaded: ${file.id}`);
Configuration Options
const filedgr = new Filedgr({
// Authentication
apiKey: 'your-api-key',
apiSecret: 'your-api-secret',
// Environment
environment: 'production', // 'test' | 'production'
baseUrl: 'https://api.filedgr.io', // Custom API endpoint
// Network settings
timeout: 30000, // Request timeout in milliseconds
retries: 3, // Number of retry attempts
retryDelay: 1000, // Delay between retries
// Rate limiting
rateLimit: {
requests: 100,
window: 60000 // per minute
},
// Logging
debug: process.env.NODE_ENV === 'development',
logger: console, // Custom logger
// Headers
userAgent: 'MyApp/1.0.0',
customHeaders: {
'X-Custom-Header': 'value'
}
});
Vault Operations
// List vaults
const vaults = await filedgr.vaults.list({
page: 1,
limit: 20,
category: 'documents',
search: 'certificate'
});
// Get vault details
const vault = await filedgr.vaults.get('vault_abc123');
// Update vault
const updatedVault = await filedgr.vaults.update('vault_abc123', {
name: 'Updated Vault Name',
metadata: {
status: 'active'
}
});
// Delete vault
await filedgr.vaults.delete('vault_abc123');
File Management
// Upload file from buffer
const fileBuffer = fs.readFileSync('./document.pdf');
const file = await filedgr.vaults.uploadFile('vault_abc123', {
file: fileBuffer,
filename: 'document.pdf',
contentType: 'application/pdf',
metadata: {
type: 'certificate',
category: 'compliance'
}
});
// Upload file from stream (Node.js)
const fileStream = fs.createReadStream('./large-file.pdf');
const file = await filedgr.vaults.uploadFileStream('vault_abc123', {
stream: fileStream,
filename: 'large-file.pdf',
contentType: 'application/pdf'
});
// Upload multiple files
const files = await Promise.all([
filedgr.vaults.uploadFile('vault_abc123', {
file: buffer1,
filename: 'file1.pdf'
}),
filedgr.vaults.uploadFile('vault_abc123', {
file: buffer2,
filename: 'file2.pdf'
})
]);
// Download file
const fileData = await filedgr.files.download('file_xyz789');
fs.writeFileSync('./downloaded-file.pdf', fileData);
// Get file metadata
const fileInfo = await filedgr.files.get('file_xyz789');
Data Streams
// Create data stream
const stream = await filedgr.streams.create({
name: 'Temperature Monitoring',
vaultId: 'vault_abc123',
type: 'iot_sensor',
schema: {
temperature: { type: 'number', unit: 'celsius' },
humidity: { type: 'number', unit: 'percent' },
timestamp: { type: 'datetime', required: true }
}
});
// Send data to stream
await filedgr.streams.sendData(stream.id, {
temperature: 23.5,
humidity: 65.2,
timestamp: new Date().toISOString()
});
// Query stream data
const data = await filedgr.streams.query(stream.id, {
timeRange: {
start: '2024-01-01T00:00:00Z',
end: '2024-01-31T23:59:59Z'
},
aggregation: 'hourly'
});
Permissions Management
// Set user permissions
await filedgr.vaults.setPermission('vault_abc123', 'user_def456', {
permission: 'VIEWER',
expiresAt: '2024-12-31T23:59:59Z'
});
// List vault permissions
const permissions = await filedgr.vaults.getPermissions('vault_abc123');
// Revoke permission
await filedgr.vaults.revokePermission('vault_abc123', 'user_def456');
Webhooks
// Create webhook
const webhook = await filedgr.webhooks.create({
url: 'https://api.myapp.com/webhooks/filedgr',
events: ['vault.created', 'vault.data_updated'],
secret: 'my-webhook-secret'
});
// List webhooks
const webhooks = await filedgr.webhooks.list();
// Update webhook
await filedgr.webhooks.update(webhook.id, {
events: ['vault.created', 'vault.verification_complete'],
active: true
});
// Verify webhook signature (for handling webhooks)
const isValid = filedgr.webhooks.verifySignature(
payload,
signature,
secret
);
Error Handling
import { FiledgrError, RateLimitError, ValidationError } from '@filedgr/sdk';
try {
const vault = await filedgr.vaults.create(vaultData);
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after: ${error.retryAfter} seconds`);
// Implement retry logic
} else if (error instanceof ValidationError) {
console.log('Validation errors:', error.details);
// Handle validation errors
} else if (error instanceof FiledgrError) {
console.log(`API error: ${error.message} (${error.statusCode})`);
} else {
console.error('Unexpected error:', error);
}
}
TypeScript Support
import { Filedgr, Vault, VaultCreateParams, FileUploadParams } from '@filedgr/sdk';
interface MyVaultMetadata {
projectId: string;
department: string;
priority: 'low' | 'medium' | 'high';
}
const filedgr = new Filedgr({
apiKey: process.env.FILEDGR_API_KEY!,
apiSecret: process.env.FILEDGR_API_SECRET!
});
const createVaultWithMetadata = async (
params: VaultCreateParams<MyVaultMetadata>
): Promise<Vault<MyVaultMetadata>> => {
return await filedgr.vaults.create(params);
};
const vault = await createVaultWithMetadata({
templateId: 'project-template-v1',
name: 'Project Alpha Vault',
metadata: {
projectId: 'PROJECT-001',
department: 'engineering',
priority: 'high'
}
});
Python SDK
Installation
pip install filedgr-python
Quick Start
import filedgr
import os
client = filedgr.Client(
api_key=os.environ['FILEDGR_API_KEY'],
api_secret=os.environ['FILEDGR_API_SECRET'],
environment='production'
)
# Create vault
vault = client.vaults.create(
template_id='general-template-v1',
name='My Python Vault',
metadata={
'category': 'documents',
'created_by': 'python-script'
}
)
print(f"Vault created: {vault.id}")
# Upload file
with open('document.pdf', 'rb') as file:
uploaded_file = client.vaults.upload_file(
vault_id=vault.id,
file=file,
filename='document.pdf',
metadata={
'type': 'certificate',
'importance': 'high'
}
)
print(f"File uploaded: {uploaded_file.id}")
Configuration
import filedgr
from filedgr.exceptions import FiledgrError, RateLimitError
client = filedgr.Client(
api_key='your-api-key',
api_secret='your-api-secret',
# Environment
environment='production', # 'test' | 'production'
base_url='https://api.filedgr.io',
# Network settings
timeout=30,
max_retries=3,
retry_backoff_factor=2,
# Rate limiting
rate_limit_requests=100,
rate_limit_window=60, # seconds
# Debugging
debug=False,
logger=None
)
Vault Operations
# List vaults
vaults = client.vaults.list(
page=1,
limit=20,
category='documents',
search='certificate'
)
for vault in vaults.data:
print(f"Vault: {vault.name} ({vault.id})")
# Get vault
vault = client.vaults.get('vault_abc123')
# Update vault
updated_vault = client.vaults.update('vault_abc123', {
'name': 'Updated Python Vault',
'metadata': {'status': 'active'}
})
# Delete vault
client.vaults.delete('vault_abc123')
File Operations
# Upload file from path
uploaded_file = client.vaults.upload_file_from_path(
vault_id='vault_abc123',
file_path='./document.pdf',
metadata={'type': 'certificate'}
)
# Upload multiple files
files_to_upload = ['file1.pdf', 'file2.jpg', 'file3.json']
uploaded_files = client.vaults.upload_files_from_paths(
vault_id='vault_abc123',
file_paths=files_to_upload
)
# Download file
file_data = client.files.download('file_xyz789')
with open('downloaded_file.pdf', 'wb') as f:
f.write(file_data)
# Get file info
file_info = client.files.get('file_xyz789')
print(f"File size: {file_info.size} bytes")
Data Streams
# Create stream
stream = client.streams.create(
name='Python IoT Stream',
vault_id='vault_abc123',
stream_type='iot_sensor',
schema={
'temperature': {'type': 'number', 'unit': 'celsius'},
'humidity': {'type': 'number', 'unit': 'percent'},
'timestamp': {'type': 'datetime', 'required': True}
}
)
# Send data
client.streams.send_data(stream.id, {
'temperature': 23.5,
'humidity': 65.2,
'timestamp': '2024-01-15T10:30:00Z'
})
# Query data
data = client.streams.query(
stream_id=stream.id,
time_range={
'start': '2024-01-01T00:00:00Z',
'end': '2024-01-31T23:59:59Z'
},
aggregation='daily'
)
Pandas Integration
import pandas as pd
import filedgr
client = filedgr.Client(api_key='...', api_secret='...')
# Convert stream data to DataFrame
stream_data = client.streams.query('stream_abc123')
df = pd.DataFrame(stream_data.data_points)
# Upload DataFrame as CSV
csv_data = df.to_csv(index=False).encode('utf-8')
client.vaults.upload_file(
vault_id='vault_abc123',
file=csv_data,
filename='data_export.csv',
content_type='text/csv'
)
# Process and re-upload analytics
analytics_df = df.groupby('date').agg({
'temperature': ['mean', 'min', 'max'],
'humidity': ['mean', 'min', 'max']
})
analytics_csv = analytics_df.to_csv().encode('utf-8')
client.vaults.upload_file(
vault_id='vault_abc123',
file=analytics_csv,
filename='daily_analytics.csv'
)
Error Handling
from filedgr.exceptions import (
FiledgrError,
ValidationError,
RateLimitError,
AuthenticationError
)
try:
vault = client.vaults.create(vault_data)
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after} seconds")
time.sleep(e.retry_after)
# Retry the operation
except ValidationError as e:
print(f"Validation errors: {e.details}")
# Handle validation errors
except AuthenticationError as e:
print(f"Authentication failed: {e.message}")
# Handle auth error
except FiledgrError as e:
print(f"API error: {e.message} (status: {e.status_code})")
except Exception as e:
print(f"Unexpected error: {e}")
Async Support
import asyncio
import filedgr
async def main():
client = filedgr.AsyncClient(
api_key=os.environ['FILEDGR_API_KEY'],
api_secret=os.environ['FILEDGR_API_SECRET']
)
# Async operations
vault = await client.vaults.create(
template_id='async-template-v1',
name='Async Vault'
)
# Parallel uploads
tasks = []
for i in range(5):
task = client.vaults.upload_file(
vault_id=vault.id,
file=f"file_{i}.txt".encode(),
filename=f"file_{i}.txt"
)
tasks.append(task)
files = await asyncio.gather(*tasks)
print(f"Uploaded {len(files)} files concurrently")
await client.close()
asyncio.run(main())
Go SDK
Installation
go get github.com/filedgr/go-sdk
Quick Start
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/filedgr/go-sdk"
)
func main() {
client := filedgr.NewClient(&filedgr.Config{
APIKey: os.Getenv("FILEDGR_API_KEY"),
APISecret: os.Getenv("FILEDGR_API_SECRET"),
Environment: "production",
})
ctx := context.Background()
// Create vault
vault, err := client.Vaults.Create(ctx, &filedgr.VaultCreateParams{
TemplateID: "general-template-v1",
Name: "Go SDK Vault",
Metadata: map[string]interface{}{
"category": "documents",
"created_by": "go-application",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Vault created: %s\n", vault.ID)
// Upload file
file, err := os.Open("document.pdf")
if err != nil {
log.Fatal(err)
}
defer file.Close()
uploadedFile, err := client.Vaults.UploadFile(ctx, vault.ID, &filedgr.FileUploadParams{
File: file,
Filename: "document.pdf",
Metadata: map[string]interface{}{
"type": "certificate",
"importance": "high",
},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("File uploaded: %s\n", uploadedFile.ID)
}
Configuration
config := &filedgr.Config{
APIKey: "your-api-key",
APISecret: "your-api-secret",
// Environment
Environment: "production", // "test" | "production"
BaseURL: "https://api.filedgr.io",
// Network settings
Timeout: 30 * time.Second,
MaxRetries: 3,
RetryDelay: 2 * time.Second,
// Rate limiting
RateLimit: filedgr.RateLimitConfig{
Requests: 100,
Window: time.Minute,
},
// HTTP client
HTTPClient: &http.Client{
Timeout: 30 * time.Second,
},
// Debugging
Debug: false,
Logger: log.Default(),
}
client := filedgr.NewClient(config)
Vault Operations
// List vaults
vaults, err := client.Vaults.List(ctx, &filedgr.VaultListParams{
Page: 1,
Limit: 20,
Category: "documents",
Search: "certificate",
})
if err != nil {
log.Fatal(err)
}
for _, vault := range vaults.Data {
fmt.Printf("Vault: %s (%s)\n", vault.Name, vault.ID)
}
// Get vault
vault, err := client.Vaults.Get(ctx, "vault_abc123")
if err != nil {
log.Fatal(err)
}
// Update vault
updatedVault, err := client.Vaults.Update(ctx, "vault_abc123", &filedgr.VaultUpdateParams{
Name: "Updated Go Vault",
Metadata: map[string]interface{}{
"status": "active",
},
})
if err != nil {
log.Fatal(err)
}
// Delete vault
err = client.Vaults.Delete(ctx, "vault_abc123")
if err != nil {
log.Fatal(err)
}
Concurrent Operations
// Upload multiple files concurrently
func uploadFilessConcurrently(client *filedgr.Client, vaultID string, filePaths []string) error {
const maxConcurrency = 5
sem := make(chan struct{}, maxConcurrency)
errChan := make(chan error, len(filePaths))
var wg sync.WaitGroup
for _, filePath := range filePaths {
wg.Add(1)
go func(path string) {
defer wg.Done()
sem <- struct{}{} // Acquire semaphore
defer func() { <-sem }() // Release semaphore
file, err := os.Open(path)
if err != nil {
errChan <- err
return
}
defer file.Close()
_, err = client.Vaults.UploadFile(context.Background(), vaultID, &filedgr.FileUploadParams{
File: file,
Filename: filepath.Base(path),
})
if err != nil {
errChan <- err
}
}(filePath)
}
wg.Wait()
close(errChan)
for err := range errChan {
if err != nil {
return err
}
}
return nil
}
Stream Operations
// Create data stream
stream, err := client.Streams.Create(ctx, &filedgr.StreamCreateParams{
Name: "Go IoT Stream",
VaultID: "vault_abc123",
Type: "iot_sensor",
Schema: map[string]interface{}{
"temperature": map[string]interface{}{
"type": "number",
"unit": "celsius",
},
"timestamp": map[string]interface{}{
"type": "datetime",
"required": true,
},
},
})
if err != nil {
log.Fatal(err)
}
// Send data to stream
err = client.Streams.SendData(ctx, stream.ID, map[string]interface{}{
"temperature": 23.5,
"humidity": 65.2,
"timestamp": time.Now().Format(time.RFC3339),
})
if err != nil {
log.Fatal(err)
}
// Query stream data
data, err := client.Streams.Query(ctx, stream.ID, &filedgr.StreamQueryParams{
TimeRange: filedgr.TimeRange{
Start: time.Now().Add(-24 * time.Hour),
End: time.Now(),
},
Aggregation: "hourly",
})
if err != nil {
log.Fatal(err)
}
Error Handling
import "github.com/filedgr/go-sdk/errors"
vault, err := client.Vaults.Create(ctx, vaultParams)
if err != nil {
switch e := err.(type) {
case *errors.RateLimitError:
fmt.Printf("Rate limited. Retry after: %v\n", e.RetryAfter)
// Implement retry logic
case *errors.ValidationError:
fmt.Printf("Validation errors: %v\n", e.Details)
// Handle validation errors
case *errors.AuthenticationError:
fmt.Printf("Authentication failed: %s\n", e.Message)
// Handle auth error
case *errors.FiledgrError:
fmt.Printf("API error: %s (status: %d)\n", e.Message, e.StatusCode)
default:
fmt.Printf("Unexpected error: %v\n", err)
}
return
}
SDK Best Practices
Error Handling
- Always handle errors - Check return values and handle exceptions
- Retry logic - Implement exponential backoff for rate limits and network errors
- Specific error types - Handle different error types appropriately
- Logging - Log errors with context for debugging
Performance
- Connection pooling - Reuse HTTP connections when possible
- Concurrent operations - Use async/parallel processing for bulk operations
- Batch operations - Group multiple API calls when supported
- Caching - Cache frequently accessed data locally
Security
- Environment variables - Store credentials in environment variables
- Secrets management - Use proper secrets management systems in production
- Token refresh - Handle access token expiration gracefully
- Rate limiting - Respect API rate limits to avoid throttling
Development
- Configuration - Use different configs for development/staging/production
- Logging - Enable debug logging during development
- Testing - Write unit tests with mocked API responses
- Documentation - Document your integration code
Testing SDKs
JavaScript Testing
import { jest } from '@jest/globals';
import { Filedgr } from '@filedgr/sdk';
// Mock the SDK for testing
jest.mock('@filedgr/sdk');
describe('Filedgr Integration', () => {
let filedgr;
beforeEach(() => {
filedgr = new Filedgr({
apiKey: 'test-key',
apiSecret: 'test-secret',
environment: 'test'
});
});
test('should create vault', async () => {
const mockVault = { id: 'vault_test123', name: 'Test Vault' };
filedgr.vaults.create.mockResolvedValue(mockVault);
const vault = await filedgr.vaults.create({
templateId: 'test-template',
name: 'Test Vault'
});
expect(vault).toEqual(mockVault);
});
});
Python Testing
import pytest
from unittest.mock import Mock, patch
import filedgr
@pytest.fixture
def mock_client():
with patch('filedgr.Client') as mock:
yield mock.return_value
def test_create_vault(mock_client):
# Mock the response
mock_vault = Mock(id='vault_test123', name='Test Vault')
mock_client.vaults.create.return_value = mock_vault
# Test the function
client = filedgr.Client(api_key='test', api_secret='test')
vault = client.vaults.create(
template_id='test-template',
name='Test Vault'
)
assert vault.id == 'vault_test123'
assert vault.name == 'Test Vault'
Go Testing
package main
import (
"context"
"testing"
"github.com/filedgr/go-sdk"
"github.com/filedgr/go-sdk/mocks"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestCreateVault(t *testing.T) {
mockClient := &mocks.Client{}
expectedVault := &filedgr.Vault{
ID: "vault_test123",
Name: "Test Vault",
}
mockClient.Vaults.On("Create", mock.Anything, mock.AnythingOfType("*filedgr.VaultCreateParams")).
Return(expectedVault, nil)
vault, err := mockClient.Vaults.Create(context.Background(), &filedgr.VaultCreateParams{
TemplateID: "test-template",
Name: "Test Vault",
})
assert.NoError(t, err)
assert.Equal(t, "vault_test123", vault.ID)
assert.Equal(t, "Test Vault", vault.Name)
}
Migration Guides
From Direct API to SDK
Before (Direct API)
const response = await fetch('https://api.filedgr.io/vaults', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
templateId: 'template_123',
name: 'My Vault'
})
});
const vault = await response.json();
After (SDK)
const vault = await filedgr.vaults.create({
templateId: 'template_123',
name: 'My Vault'
});
SDK Version Updates
When updating SDK versions:
- Check changelog - Review breaking changes
- Update gradually - Test in development first
- Handle deprecations - Replace deprecated methods
- Test thoroughly - Ensure all integrations work
- Monitor performance - Check for performance impacts
Getting Help
Documentation
- API Reference - Complete API documentation
- GitHub Examples - Example implementations
- TypeScript Definitions - Full type definitions
Community
- Discord Community - Chat with other developers
- GitHub Issues - Report bugs and request features
- Stack Overflow - Get help from the community
Support
- SDK Support - Direct SDK assistance
- Integration Support - Integration guidance
- Documentation Issues - Report documentation problems
Next Steps
- Error Handling Guide - Handle errors gracefully
- Rate Limits Documentation - Understand API limits
- Integration Examples - See real-world implementations
- Performance Optimization - Optimize your integration
Choose the SDK that best fits your stack and start building with Filedgr today. Our SDKs handle the complexity so you can focus on your application logic.