SDK Documentation
Overview
We provide SDKs for multiple programming languages to help developers quickly integrate our services. This documentation covers installation, configuration, and usage methods for all official SDKs.
Supported SDKs
JavaScript/TypeScript SDK
Installation
bash
# npm
npm install @yourapp/sdk
# yarn
yarn add @yourapp/sdk
# pnpm
pnpm add @yourapp/sdkBasic Usage
javascript
import { YourAppSDK } from '@yourapp/sdk';
// Initialize SDK
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
environment: 'production', // or 'sandbox'
timeout: 30000
});
// User management
const user = await sdk.users.create({
email: 'user@example.com',
name: 'John Doe'
});
// Project management
const project = await sdk.projects.create({
name: 'My Project',
description: 'Project description'
});
// File upload
const file = await sdk.files.upload({
file: fileBuffer,
filename: 'document.pdf',
projectId: project.id
});TypeScript Support
typescript
import { YourAppSDK, User, Project, CreateUserRequest } from '@yourapp/sdk';
const sdk = new YourAppSDK({
apiKey: process.env.YOURAPP_API_KEY!,
environment: 'production'
});
// Type-safe user creation
const createUser = async (userData: CreateUserRequest): Promise<User> => {
return await sdk.users.create(userData);
};
// Type-safe project query
const getProjects = async (): Promise<Project[]> => {
return await sdk.projects.list({
limit: 10,
offset: 0
});
};Python SDK
Installation
bash
pip install yourapp-sdkBasic Usage
python
from yourapp_sdk import YourAppSDK
from yourapp_sdk.exceptions import YourAppError
# Initialize SDK
sdk = YourAppSDK(
api_key='your-api-key',
environment='production',
timeout=30
)
# User management
try:
user = sdk.users.create(
email='user@example.com',
name='John Doe'
)
print(f'Created user: {user.id}')
except YourAppError as e:
print(f'Error creating user: {e.message}')
# Project management
project = sdk.projects.create(
name='My Project',
description='Project description'
)
# File upload
with open('document.pdf', 'rb') as file:
uploaded_file = sdk.files.upload(
file=file,
filename='document.pdf',
project_id=project.id
)Async Support
python
import asyncio
from yourapp_sdk import AsyncYourAppSDK
async def main():
# Async SDK initialization
sdk = AsyncYourAppSDK(
api_key='your-api-key',
environment='production'
)
# Async user creation
user = await sdk.users.create(
email='user@example.com',
name='John Doe'
)
# Async project list
projects = await sdk.projects.list(limit=10)
# Close connection
await sdk.close()
# Run async code
asyncio.run(main())Go SDK
Installation
bash
go get github.com/yourapp/sdk-goBasic Usage
go
package main
import (
"context"
"fmt"
"log"
"github.com/yourapp/sdk-go"
)
func main() {
// Initialize SDK
client := yourapp.NewClient(&yourapp.Config{
APIKey: "your-api-key",
Environment: "production",
Timeout: 30 * time.Second,
})
ctx := context.Background()
// User management
user, err := client.Users.Create(ctx, &yourapp.CreateUserRequest{
Email: "user@example.com",
Name: "John Doe",
})
if err != nil {
log.Fatalf("Failed to create user: %v", err)
}
fmt.Printf("Created user: %s\n", user.ID)
// Project management
project, err := client.Projects.Create(ctx, &yourapp.CreateProjectRequest{
Name: "My Project",
Description: "Project description",
})
if err != nil {
log.Fatalf("Failed to create project: %v", err)
}
// File upload
file, err := os.Open("document.pdf")
if err != nil {
log.Fatalf("Failed to open file: %v", err)
}
defer file.Close()
uploadedFile, err := client.Files.Upload(ctx, &yourapp.UploadFileRequest{
File: file,
Filename: "document.pdf",
ProjectID: project.ID,
})
if err != nil {
log.Fatalf("Failed to upload file: %v", err)
}
fmt.Printf("Uploaded file: %s\n", uploadedFile.ID)
}Java SDK
Installation
Maven
xml
<dependency>
<groupId>com.yourapp</groupId>
<artifactId>yourapp-sdk</artifactId>
<version>1.0.0</version>
</dependency>Gradle
gradle
implementation 'com.yourapp:yourapp-sdk:1.0.0'Basic Usage
java
import com.yourapp.sdk.YourAppSDK;
import com.yourapp.sdk.models.*;
import com.yourapp.sdk.exceptions.YourAppException;
public class Example {
public static void main(String[] args) {
// Initialize SDK
YourAppSDK sdk = YourAppSDK.builder()
.apiKey("your-api-key")
.environment(Environment.PRODUCTION)
.timeout(Duration.ofSeconds(30))
.build();
try {
// User management
CreateUserRequest userRequest = CreateUserRequest.builder()
.email("user@example.com")
.name("John Doe")
.build();
User user = sdk.users().create(userRequest);
System.out.println("Created user: " + user.getId());
// Project management
CreateProjectRequest projectRequest = CreateProjectRequest.builder()
.name("My Project")
.description("Project description")
.build();
Project project = sdk.projects().create(projectRequest);
// File upload
File file = new File("document.pdf");
UploadFileRequest uploadRequest = UploadFileRequest.builder()
.file(file)
.filename("document.pdf")
.projectId(project.getId())
.build();
UploadedFile uploadedFile = sdk.files().upload(uploadRequest);
System.out.println("Uploaded file: " + uploadedFile.getId());
} catch (YourAppException e) {
System.err.println("SDK Error: " + e.getMessage());
}
}
}PHP SDK
Installation
bash
composer require yourapp/sdkBasic Usage
php
<?php
require_once 'vendor/autoload.php';
use YourApp\SDK\YourAppSDK;
use YourApp\SDK\Exceptions\YourAppException;
// Initialize SDK
$sdk = new YourAppSDK([
'api_key' => 'your-api-key',
'environment' => 'production',
'timeout' => 30
]);
try {
// User management
$user = $sdk->users->create([
'email' => 'user@example.com',
'name' => 'John Doe'
]);
echo "Created user: {$user['id']}\n";
// Project management
$project = $sdk->projects->create([
'name' => 'My Project',
'description' => 'Project description'
]);
// File upload
$uploadedFile = $sdk->files->upload([
'file' => fopen('document.pdf', 'r'),
'filename' => 'document.pdf',
'project_id' => $project['id']
]);
echo "Uploaded file: {$uploadedFile['id']}\n";
} catch (YourAppException $e) {
echo "SDK Error: {$e->getMessage()}\n";
}
?>Ruby SDK
Installation
bash
gem install yourapp-sdkBasic Usage
ruby
require 'yourapp-sdk'
# Initialize SDK
sdk = YourApp::SDK.new(
api_key: 'your-api-key',
environment: 'production',
timeout: 30
)
begin
# User management
user = sdk.users.create(
email: 'user@example.com',
name: 'John Doe'
)
puts "Created user: #{user.id}"
# Project management
project = sdk.projects.create(
name: 'My Project',
description: 'Project description'
)
# File upload
File.open('document.pdf', 'rb') do |file|
uploaded_file = sdk.files.upload(
file: file,
filename: 'document.pdf',
project_id: project.id
)
puts "Uploaded file: #{uploaded_file.id}"
end
rescue YourApp::SDK::Error => e
puts "SDK Error: #{e.message}"
endConfiguration Options
Common Configuration
All SDKs support the following configuration options:
javascript
const config = {
// Required configuration
apiKey: 'your-api-key',
// Environment configuration
environment: 'production', // 'production' | 'sandbox'
baseUrl: 'https://api.yourapp.com', // Custom API endpoint
// Network configuration
timeout: 30000, // Request timeout (milliseconds)
retries: 3, // Number of retries
retryDelay: 1000, // Retry delay (milliseconds)
// Logging configuration
logLevel: 'info', // 'debug' | 'info' | 'warn' | 'error'
logger: customLogger, // Custom logger
// Proxy configuration
proxy: {
host: 'proxy.example.com',
port: 8080,
auth: {
username: 'proxy-user',
password: 'proxy-pass'
}
}
};Environment Variables
All SDKs support configuration through environment variables:
bash
# API Key
export YOURAPP_API_KEY="your-api-key"
# Environment
export YOURAPP_ENVIRONMENT="production"
# Custom endpoint
export YOURAPP_BASE_URL="https://api.yourapp.com"
# Timeout setting
export YOURAPP_TIMEOUT="30000"
# Log level
export YOURAPP_LOG_LEVEL="info"Error Handling
Error Types
All SDKs provide unified error handling mechanisms:
javascript
try {
const user = await sdk.users.create(userData);
} catch (error) {
if (error instanceof YourAppError) {
switch (error.type) {
case 'AUTHENTICATION_ERROR':
console.error('Invalid API key');
break;
case 'VALIDATION_ERROR':
console.error('Invalid input:', error.details);
break;
case 'RATE_LIMIT_ERROR':
console.error('Rate limit exceeded');
break;
case 'NETWORK_ERROR':
console.error('Network connection failed');
break;
case 'SERVER_ERROR':
console.error('Server error:', error.message);
break;
default:
console.error('Unknown error:', error.message);
}
}
}Retry Mechanism
javascript
// Configure automatic retry
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
retries: 3,
retryDelay: 1000,
retryConditions: [
'NETWORK_ERROR',
'RATE_LIMIT_ERROR',
'SERVER_ERROR'
]
});
// Manual retry
const retryOperation = async (operation, maxRetries = 3) => {
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
if (i === maxRetries - 1 || !isRetryableError(error)) {
throw error;
}
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
};Pagination Handling
Automatic Pagination
javascript
// Get all projects (automatic pagination)
const allProjects = [];
for await (const project of sdk.projects.listAll()) {
allProjects.push(project);
}
// Or use toArray() method
const projects = await sdk.projects.listAll().toArray();Manual Pagination
javascript
// Manual pagination control
let hasMore = true;
let offset = 0;
const limit = 50;
const allProjects = [];
while (hasMore) {
const response = await sdk.projects.list({
limit,
offset
});
allProjects.push(...response.data);
hasMore = response.hasMore;
offset += limit;
}Batch Operations
Batch Creation
javascript
// Batch create users
const users = await sdk.users.createBatch([
{ email: 'user1@example.com', name: 'User 1' },
{ email: 'user2@example.com', name: 'User 2' },
{ email: 'user3@example.com', name: 'User 3' }
]);
// Batch update
const updatedUsers = await sdk.users.updateBatch([
{ id: 'user1', name: 'Updated User 1' },
{ id: 'user2', name: 'Updated User 2' }
]);Batch Deletion
javascript
// Batch delete
const result = await sdk.users.deleteBatch(['user1', 'user2', 'user3']);
console.log(`Deleted ${result.deletedCount} users`);File Handling
File Upload
javascript
// Single file upload
const file = await sdk.files.upload({
file: fileBuffer,
filename: 'document.pdf',
contentType: 'application/pdf',
projectId: 'project123'
});
// Multiple file upload
const files = await sdk.files.uploadMultiple([
{
file: file1Buffer,
filename: 'doc1.pdf',
contentType: 'application/pdf'
},
{
file: file2Buffer,
filename: 'doc2.pdf',
contentType: 'application/pdf'
}
], {
projectId: 'project123'
});
// Large file chunked upload
const largeFile = await sdk.files.uploadLarge({
file: largeFileBuffer,
filename: 'large-video.mp4',
contentType: 'video/mp4',
chunkSize: 5 * 1024 * 1024, // 5MB chunks
onProgress: (progress) => {
console.log(`Upload progress: ${progress.percentage}%`);
}
});File Download
javascript
// Download file
const fileStream = await sdk.files.download('file123');
// Download to local file
await sdk.files.downloadToFile('file123', './downloaded-file.pdf');
// Get download URL
const downloadUrl = await sdk.files.getDownloadUrl('file123', {
expiresIn: 3600 // 1 hour
});Real-time Features
WebSocket Connection
javascript
// Establish WebSocket connection
const ws = sdk.realtime.connect({
channels: ['project.updates', 'user.notifications']
});
// Listen to events
ws.on('project.updated', (data) => {
console.log('Project updated:', data);
});
ws.on('user.notification', (data) => {
console.log('New notification:', data);
});
// Send message
ws.send('project.message', {
projectId: 'project123',
message: 'Hello team!'
});
// Close connection
ws.close();Server-Sent Events (SSE)
javascript
// Listen to server-sent events
const eventSource = sdk.events.subscribe({
channels: ['project.updates']
});
eventSource.on('message', (event) => {
console.log('Received event:', event);
});
eventSource.on('error', (error) => {
console.error('SSE error:', error);
});
// Close connection
eventSource.close();Caching
Memory Cache
javascript
// Enable memory cache
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
cache: {
enabled: true,
ttl: 300, // 5 minutes
maxSize: 1000 // Maximum cache items
}
});
// Manual cache control
const user = await sdk.users.get('user123', {
cache: true,
cacheTtl: 600 // 10 minutes
});
// Clear cache
sdk.cache.clear();
sdk.cache.delete('users:user123');Redis Cache
javascript
// Use Redis cache
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
cache: {
type: 'redis',
redis: {
host: 'localhost',
port: 6379,
password: 'redis-password'
},
ttl: 300
}
});Testing
Mock Mode
javascript
// Enable mock mode for testing
const sdk = new YourAppSDK({
apiKey: 'test-api-key',
environment: 'test',
mock: true
});
// All API calls will return mock data
const user = await sdk.users.create({
email: 'test@example.com',
name: 'Test User'
});
// Returns mock user objectTesting Tools
javascript
// Jest test example
import { YourAppSDK } from '@yourapp/sdk';
import { mockSDK } from '@yourapp/sdk/testing';
describe('User Service', () => {
let sdk;
beforeEach(() => {
sdk = mockSDK();
});
test('should create user', async () => {
const userData = {
email: 'test@example.com',
name: 'Test User'
};
sdk.users.create.mockResolvedValue({
id: 'user123',
...userData
});
const user = await sdk.users.create(userData);
expect(user.id).toBe('user123');
expect(sdk.users.create).toHaveBeenCalledWith(userData);
});
});Performance Optimization
Connection Pool
javascript
// Configure connection pool
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
http: {
poolSize: 10,
keepAlive: true,
keepAliveMsecs: 30000
}
});Request Batching
javascript
// Automatically batch similar requests
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
batching: {
enabled: true,
batchSize: 10,
batchDelay: 100 // 100ms
}
});
// These requests will be automatically batched
const [user1, user2, user3] = await Promise.all([
sdk.users.get('user1'),
sdk.users.get('user2'),
sdk.users.get('user3')
]);Monitoring and Logging
Custom Logger
javascript
// Custom logger
const customLogger = {
debug: (message, meta) => console.debug('[DEBUG]', message, meta),
info: (message, meta) => console.info('[INFO]', message, meta),
warn: (message, meta) => console.warn('[WARN]', message, meta),
error: (message, meta) => console.error('[ERROR]', message, meta)
};
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
logger: customLogger,
logLevel: 'debug'
});Metrics Collection
javascript
// Enable metrics collection
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
metrics: {
enabled: true,
collector: (metrics) => {
// Send metrics to monitoring system
console.log('SDK Metrics:', metrics);
}
}
});
// Get SDK metrics
const metrics = sdk.getMetrics();
console.log('Request count:', metrics.requestCount);
console.log('Average response time:', metrics.avgResponseTime);
console.log('Error rate:', metrics.errorRate);Migration Guide
From v1 to v2
javascript
// v1 (old version)
const sdk = new YourAppSDK('your-api-key');
const user = await sdk.createUser({
email: 'user@example.com',
name: 'John Doe'
});
// v2 (new version)
const sdk = new YourAppSDK({
apiKey: 'your-api-key'
});
const user = await sdk.users.create({
email: 'user@example.com',
name: 'John Doe'
});Compatibility Layer
javascript
// Use compatibility layer to support legacy code
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
compatibility: 'v1' // Enable v1 compatibility mode
});
// v1 style calls still work
const user = await sdk.createUser(userData);Troubleshooting
Common Issues
Authentication Failure
javascript
// Check API key
if (!process.env.YOURAPP_API_KEY) {
throw new Error('YOURAPP_API_KEY environment variable is required');
}
// Validate API key format
if (!process.env.YOURAPP_API_KEY.startsWith('ya_')) {
throw new Error('Invalid API key format');
}Network Connection Issues
javascript
// Test network connection
const testConnection = async () => {
try {
const response = await sdk.health.check();
console.log('Connection OK:', response);
} catch (error) {
console.error('Connection failed:', error.message);
// Check proxy settings
if (error.code === 'ECONNREFUSED') {
console.log('Check proxy settings and firewall');
}
}
};Rate Limiting
javascript
// Handle rate limiting
const handleRateLimit = async (operation) => {
try {
return await operation();
} catch (error) {
if (error.type === 'RATE_LIMIT_ERROR') {
const retryAfter = error.retryAfter || 60;
console.log(`Rate limited. Retrying after ${retryAfter} seconds`);
await new Promise(resolve =>
setTimeout(resolve, retryAfter * 1000)
);
return await operation();
}
throw error;
}
};Debug Mode
javascript
// Enable debug mode
const sdk = new YourAppSDK({
apiKey: 'your-api-key',
debug: true,
logLevel: 'debug'
});
// Or via environment variables
process.env.YOURAPP_DEBUG = 'true';
process.env.YOURAPP_LOG_LEVEL = 'debug';Best Practices
Error Handling
javascript
// Comprehensive error handling
const createUserSafely = async (userData) => {
try {
return await sdk.users.create(userData);
} catch (error) {
// Log error
logger.error('Failed to create user', {
error: error.message,
userData: { email: userData.email } // Don't log sensitive info
});
// Handle based on error type
if (error.type === 'VALIDATION_ERROR') {
throw new Error(`Invalid user data: ${error.details.join(', ')}`);
}
if (error.type === 'RATE_LIMIT_ERROR') {
// Implement backoff retry
await new Promise(resolve => setTimeout(resolve, error.retryAfter * 1000));
return await createUserSafely(userData);
}
// Re-throw other errors
throw error;
}
};Resource Management
javascript
// Proper resource management
class UserService {
constructor() {
this.sdk = new YourAppSDK({
apiKey: process.env.YOURAPP_API_KEY
});
}
async createUser(userData) {
return await this.sdk.users.create(userData);
}
// Clean up resources
async close() {
await this.sdk.close();
}
}
// Usage example
const userService = new UserService();
try {
const user = await userService.createUser(userData);
} finally {
await userService.close();
}Configuration Management
javascript
// Environment-specific configuration
const getSDKConfig = () => {
const environment = process.env.NODE_ENV || 'development';
const baseConfig = {
apiKey: process.env.YOURAPP_API_KEY,
timeout: 30000
};
switch (environment) {
case 'production':
return {
...baseConfig,
environment: 'production',
logLevel: 'warn',
retries: 3
};
case 'staging':
return {
...baseConfig,
environment: 'sandbox',
logLevel: 'info',
retries: 2
};
default:
return {
...baseConfig,
environment: 'sandbox',
logLevel: 'debug',
retries: 1
};
}
};
const sdk = new YourAppSDK(getSDKConfig());