API Best Practices

Optimize your implementation for performance, security, and cost-efficiency

Introduction

Following these best practices will help you build robust, efficient, and secure applications with WebburnsTech APIs. This guide covers request/response handling, text-to-audio, audio-to-transcript, text-to-image, image-to-text, and image generation APIs.

Pro Tip: Always use the latest version of our SDKs to benefit from performance improvements and new features.

General API Request & Response Best Practices

These practices apply to all WebburnsTech API endpoints and will help ensure reliable integration.

Request Optimization

Use Appropriate Timeouts

Set reasonable timeout values based on the API endpoint. Image generation typically takes longer than text processing.

Implement Retry Logic

Use exponential backoff for retries with jitter to handle temporary failures without overwhelming the API.

Batch Requests When Possible

For text processing, batch multiple requests to reduce overhead and improve efficiency.


// Example: Implementing retry logic with exponential backoff
async function makeRequestWithRetry(apiCall, maxRetries = 3) {
    for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
            return await apiCall();
        } catch (error) {
            if (error.status === 429 || error.status >= 500) {
                // Rate limiting or server error - retry with backoff
                const delay = Math.min(1000 * Math.pow(2, attempt) + Math.random() * 1000, 30000);
                console.log(`Attempt ${attempt} failed, retrying in ${delay}ms`);
                await new Promise(resolve => setTimeout(resolve, delay));
            } else {
                // Client error - don't retry
                throw error;
            }
        }
    }
    throw new Error(`All ${maxRetries} attempts failed`);
}

// Usage
const result = await makeRequestWithRetry(() => 
    client.nlp.analyzeSentiment({ text: 'Sample text' })
);
                        

Response Handling

Validate Responses

Always check response status and validate data structure before processing.

Handle Errors Gracefully

Implement comprehensive error handling for different types of API errors.

Cache Responses

Cache responses for identical requests to reduce API calls and improve performance.


// Example: Comprehensive response handling
async function processAPIResponse(apiCall) {
    try {
        const response = await apiCall();
        
        // Validate response structure
        if (!response || response.status !== 'success') {
            throw new Error(`API returned unexpected response: ${JSON.stringify(response)}`);
        }
        
        return response.data;
    } catch (error) {
        // Handle different error types
        if (error.status === 401) {
            // Authentication error - refresh token or redirect to login
            console.error('Authentication failed:', error.message);
            // Implement re-authentication logic
        } else if (error.status === 429) {
            // Rate limiting
            console.error('Rate limit exceeded:', error.message);
            // Implement backoff or notify user
        } else if (error.status >= 500) {
            // Server error
            console.error('Server error:', error.message);
            // Implement retry logic
        } else {
            // Other client errors
            console.error('Request failed:', error.message);
        }
        
        throw error;
    }
}
                        

Text-to-Audio API

Convert text to natural-sounding speech with various voice options and audio formats.

Parameter Type Required Description Best Practice
text String Yes Text to convert to speech Limit to 5000 characters per request
voice String No Voice identifier (e.g., "en-US-Female1") Cache voice list to avoid repeated API calls
speed Number No Speech speed (0.5 to 2.0) Default to 1.0 for natural speech
format String No Audio format (mp3, wav, ogg) Use mp3 for web, wav for high quality
Performance Tip: For long texts, consider splitting into multiple requests and concatenating the audio files client-side to avoid timeout issues.

// Example: Text-to-Audio implementation with best practices
async function generateSpeech(text, options = {}) {
    // Validate input length
    if (text.length > 5000) {
        throw new Error('Text exceeds maximum length of 5000 characters');
    }
    
    // Set defaults
    const params = {
        text: text,
        voice: options.voice || 'en-US-Female1',
        speed: options.speed || 1.0,
        format: options.format || 'mp3',
        ...options
    };
    
    try {
        const response = await client.audio.textToSpeech(params);
        
        // The response contains the audio URL and metadata
        return {
            audioUrl: response.audioUrl,
            duration: response.duration,
            size: response.size
        };
    } catch (error) {
        console.error('Text-to-Audio conversion failed:', error);
        throw error;
    }
}

// Usage
const audioResult = await generateSpeech('Hello, this is a text to speech example.', {
    voice: 'en-US-Male1',
    speed: 1.2
});
                        

Audio-to-Transcript API

Convert speech audio to text with support for multiple languages and speaker identification.

Parameter Type Required Description Best Practice
audio File/URL Yes Audio file or URL to transcribe Use supported formats: mp3, wav, ogg, m4a
language String No Language code (e.g., "en-US") Auto-detect if not specified
speaker_diarization Boolean No Identify different speakers Enable for conversations with multiple speakers
timestamps Boolean No Include word-level timestamps Enable for audio editing applications
Important: Audio files must be under 100MB and less than 4 hours in duration. For longer audio, use the chunking approach.

// Example: Audio-to-Transcript implementation with best practices
async function transcribeAudio(audioFile, options = {}) {
    // Validate file size (assuming we have file size)
    if (audioFile.size > 100 * 1024 * 1024) {
        throw new Error('Audio file exceeds maximum size of 100MB');
    }
    
    // Prepare form data for file upload
    const formData = new FormData();
    formData.append('audio', audioFile);
    formData.append('language', options.language || 'auto');
    formData.append('speaker_diarization', options.speakerDiarization || false);
    formData.append('timestamps', options.timestamps || false);
    
    try {
        const response = await client.audio.speechToText(formData);
        
        return {
            transcript: response.transcript,
            words: response.words || [], // If timestamps enabled
            speakers: response.speakers || [], // If speaker diarization enabled
            confidence: response.confidence
        };
    } catch (error) {
        console.error('Audio transcription failed:', error);
        throw error;
    }
}

// For long audio files, implement chunking
async function transcribeLongAudio(audioUrl, chunkDuration = 300) { // 5 minutes
    // Implementation would involve:
    // 1. Downloading the audio file
    // 2. Splitting into chunks of chunkDuration seconds
    // 3. Transcribing each chunk
    // 4. Combining results with proper timing
    // This is a simplified example
    console.log(`Transcribing long audio by splitting into ${chunkDuration}-second chunks`);
    
    // Actual implementation would use a media processing library
    // to split the audio and then process each chunk
}
                        

Text-to-Image API

Generate images from text descriptions with various styles, sizes, and quality options.

Parameter Type Required Description Best Practice
prompt String Yes Text description of the desired image Be specific and descriptive for better results
size String No Image dimensions (e.g., "512x512", "1024x1024") Use smaller sizes for faster generation
style String No Art style (e.g., "realistic", "cartoon", "abstract") Experiment with different styles for your use case
quality String No Image quality ("standard", "hd") Use "standard" for faster results, "hd" for final output
Prompt Engineering: For better results, include details about composition, lighting, style, and mood in your prompts. Example: "A serene mountain landscape at sunset with dramatic lighting, photorealistic style" instead of just "mountains".

// Example: Text-to-Image implementation with best practices
async function generateImage(prompt, options = {}) {
    // Validate prompt length and content
    if (!prompt || prompt.trim().length === 0) {
        throw new Error('Prompt cannot be empty');
    }
    
    if (prompt.length > 1000) {
        console.warn('Long prompts may reduce image quality. Consider simplifying.');
    }
    
    const params = {
        prompt: prompt,
        size: options.size || '512x512',
        style: options.style || 'realistic',
        quality: options.quality || 'standard',
        num_images: options.numImages || 1, // Number of images to generate
        ...options
    };
    
    try {
        const response = await client.images.generateFromText(params);
        
        // Response contains array of image URLs and generation metadata
        return {
            images: response.images, // Array of image URLs
            generationTime: response.generationTime,
            prompt: response.prompt // May include modified prompt
        };
    } catch (error) {
        console.error('Image generation failed:', error);
        throw error;
    }
}

// Usage with enhanced prompt
const imageResult = await generateImage(
    'A cozy reading nook with a comfortable armchair, bookshelves filled with books, soft lighting from a table lamp, and a cat sleeping on the chair, photorealistic style, warm color palette',
    {
        size: '1024x1024',
        quality: 'hd'
    }
);
                        

Image-to-Text API

Extract text content from images, including handwritten text, with support for multiple languages.

Parameter Type Required Description Best Practice
image File/URL Yes Image file or URL to process Use high-contrast images for better accuracy
language String No Language of text in image Specify if known, otherwise auto-detect
detect_handwriting Boolean No Enable handwriting recognition Enable for handwritten content
enhance Boolean No Pre-process image for better OCR Enable for low-quality images

// Example: Image-to-Text implementation with best practices
async function extractTextFromImage(imageFile, options = {}) {
    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp'];
    if (!allowedTypes.includes(imageFile.type)) {
        throw new Error('Unsupported image format. Use JPEG, PNG, GIF, or BMP.');
    }
    
    // Validate file size
    if (imageFile.size > 20 * 1024 * 1024) {
        throw new Error('Image file exceeds maximum size of 20MB');
    }
    
    const formData = new FormData();
    formData.append('image', imageFile);
    formData.append('language', options.language || 'auto');
    formData.append('detect_handwriting', options.detectHandwriting || false);
    formData.append('enhance', options.enhance || false);
    
    try {
        const response = await client.images.extractText(formData);
        
        return {
            text: response.text,
            words: response.words, // Array of words with bounding boxes
            confidence: response.confidence, // Overall confidence score
            language: response.language // Detected language
        };
    } catch (error) {
        console.error('Text extraction failed:', error);
        throw error;
    }
}

// Pre-processing function to improve OCR results
function preprocessImageForOCR(imageFile) {
    // In a real implementation, this would:
    // 1. Convert to grayscale
    // 2. Apply noise reduction
    // 3. Enhance contrast
    // 4. Deskew if necessary
    // This is a placeholder for the concept
    console.log('Preprocessing image for better OCR results');
    return imageFile; // In reality, return processed image
}
                        

Image Generation API

Advanced image generation with control over composition, styles, and specific elements.

Parameter Type Required Description Best Practice
prompt String Yes Detailed description of desired image Use specific, descriptive language
negative_prompt String No Elements to exclude from the image Use to refine results and avoid unwanted elements
style_preset String No Predefined style (e.g., "photographic", "digital-art") Use consistent style presets for brand consistency
steps Number No Number of generation steps (10-50) Higher values increase quality but also generation time
Advanced Technique: Use negative prompts to exclude unwanted elements. For example, if generating images of people, use negative prompts like "blurry, deformed, extra limbs" to improve quality.

// Example: Advanced Image Generation with best practices
async function generateAdvancedImage(prompt, options = {}) {
    // Enhanced prompt validation and suggestion
    if (prompt.split(' ').length < 5) {
        console.warn('Short prompts may produce generic results. Consider adding more details.');
    }
    
    const params = {
        prompt: prompt,
        negative_prompt: options.negativePrompt || 'blurry, low quality, distorted, ugly',
        style_preset: options.stylePreset || 'photographic',
        steps: Math.min(Math.max(options.steps || 20, 10), 50), // Clamp between 10-50
        cfg_scale: options.cfgScale || 7, // How closely to follow the prompt
        seed: options.seed, // For reproducible results
        ...options
    };
    
    try {
        const response = await client.images.advancedGeneration(params);
        
        return {
            images: response.images,
            generationTime: response.generationTime,
            seed: response.seed, // Save for reproducibility
            parameters: response.parameters // All generation parameters
        };
    } catch (error) {
        console.error('Advanced image generation failed:', error);
        throw error;
    }
}

// Usage with comprehensive parameters
const advancedImageResult = await generateAdvancedImage(
    'A futuristic cityscape at night with flying cars, neon lights reflecting on wet streets, towering skyscrapers with holographic advertisements, cyberpunk style',
    {
        negativePrompt: 'people, animals, daytime, vintage, historical',
        stylePreset: 'digital-art',
        steps: 30,
        cfgScale: 8,
        seed: 12345 // For reproducible results
    }
);
                        

Performance Optimization

Implement these strategies to optimize API usage and improve application performance.

Request Caching

Cache identical requests to reduce API calls and improve response times.

Connection Pooling

Reuse HTTP connections to reduce latency in high-volume applications.

Asynchronous Processing

For long-running operations, use async processing with webhooks or polling.


// Example: Implementing request caching
class APICache {
    constructor(ttl = 300000) { // 5 minutes default
        this.cache = new Map();
        this.ttl = ttl;
    }
    
    getKey(endpoint, params) {
        return `${endpoint}:${JSON.stringify(params)}`;
    }
    
    get(endpoint, params) {
        const key = this.getKey(endpoint, params);
        const item = this.cache.get(key);
        
        if (item && Date.now() - item.timestamp < this.ttl) {
            return item.data;
        }
        
        // Remove expired item
        if (item) {
            this.cache.delete(key);
        }
        
        return null;
    }
    
    set(endpoint, params, data) {
        const key = this.getKey(endpoint, params);
        this.cache.set(key, {
            data: data,
            timestamp: Date.now()
        });
    }
}

// Usage
const apiCache = new APICache(10 * 60 * 1000); // 10 minutes TTL

async function cachedAPICall(endpoint, params, apiFunction) {
    const cached = apiCache.get(endpoint, params);
    if (cached) {
        console.log('Returning cached result');
        return cached;
    }
    
    const result = await apiFunction(params);
    apiCache.set(endpoint, params, result);
    return result;
}

// Example usage with text-to-image
const imageResult = await cachedAPICall(
    'text-to-image', 
    { prompt: 'A sunset over mountains', size: '512x512' },
    (params) => client.images.generateFromText(params)
);
                        

Security Best Practices

Protect your API keys and ensure secure communication with WebburnsTech APIs.

Security Alert: Never expose API keys in client-side code. Always use a backend server to make API calls.

Environment Variables

Store API keys in environment variables, never in source code.

Key Rotation

Regularly rotate API keys and use different keys for different environments.

Rate Limiting

Implement client-side rate limiting to avoid hitting API limits.


// Example: Secure API client configuration
const { WebburnsTechAPI } = require('@webburnstech/sdk');

// API key should come from environment variables, not hardcoded
const apiKey = process.env.WEB_BURNS_TECH_API_KEY;

if (!apiKey) {
    throw new Error('WEB_BURNS_TECH_API_KEY environment variable is required');
}

const client = new WebburnsTechAPI({
    apiKey: apiKey,
    // Additional security settings
    timeout: 30000,
    maxRetries: 3,
    // Enable for production
    enableTelemetry: process.env.NODE_ENV === 'production'
});

// Example: Server-side endpoint to proxy API calls
app.post('/api/generate-image', async (req, res) => {
    try {
        // Validate user input
        const { prompt, options } = req.body;
        
        if (!prompt || typeof prompt !== 'string') {
            return res.status(400).json({ error: 'Valid prompt is required' });
        }
        
        // Implement additional security checks as needed
        if (prompt.length > 1000) {
            return res.status(400).json({ error: 'Prompt too long' });
        }
        
        // Make the API call server-side
        const result = await client.images.generateFromText({
            prompt: prompt,
            ...options
        });
        
        res.json(result);
    } catch (error) {
        console.error('API call failed:', error);
        res.status(500).json({ 
            error: 'Image generation failed',
            details: process.env.NODE_ENV === 'development' ? error.message : undefined
        });
    }
});
                        

Error Handling & Monitoring

Implement comprehensive error handling and monitoring to ensure application reliability.


// Example: Comprehensive error handling and monitoring
class APIError extends Error {
    constructor(message, code, details = {}) {
        super(message);
        this.name = 'APIError';
        this.code = code;
        this.details = details;
        this.timestamp = new Date().toISOString();
    }
    
    toJSON() {
        return {
            name: this.name,
            message: this.message,
            code: this.code,
            details: this.details,
            timestamp: this.timestamp
        };
    }
}

// Error monitoring function
function logAPIError(error, context = {}) {
    const errorData = {
        error: error instanceof APIError ? error.toJSON() : {
            name: error.name,
            message: error.message,
            stack: error.stack
        },
        context: context,
        timestamp: new Date().toISOString()
    };
    
    // Log to your error monitoring service
    console.error('API Error:', errorData);
    
    // Send to error tracking service (e.g., Sentry)
    if (typeof window !== 'undefined' && window.Sentry) {
        window.Sentry.captureException(error, { extra: context });
    }
}

// Wrapper function with comprehensive error handling
async function executeWithErrorHandling(apiCall, context = {}) {
    try {
        return await apiCall();
    } catch (error) {
        // Log the error
        logAPIError(error, context);
        
        // Determine if it's a retryable error
        const isRetryable = 
            error.status === 429 || // Rate limiting
            error.status >= 500 || // Server errors
            error.code === 'ECONNRESET' || // Network issues
            error.code === 'ETIMEDOUT';
        
        if (isRetryable) {
            throw new APIError(
                'Service temporarily unavailable', 
                'SERVICE_UNAVAILABLE',
                { originalError: error.message, retryable: true }
            );
        } else if (error.status === 401) {
            throw new APIError(
                'Authentication failed',
                'AUTHENTICATION_ERROR',
                { originalError: error.message }
            );
        } else if (error.status === 400) {
            throw new APIError(
                'Invalid request',
                'VALIDATION_ERROR',
                { originalError: error.message }
            );
        } else {
            throw new APIError(
                'Unexpected error occurred',
                'UNKNOWN_ERROR',
                { originalError: error.message }
            );
        }
    }
}

// Usage
try {
    const result = await executeWithErrorHandling(
        () => client.images.generateFromText({ prompt: 'test' }),
        { operation: 'image-generation', userId: 'user123' }
    );
} catch (error) {
    if (error instanceof APIError) {
        // Handle different error types appropriately
        switch (error.code) {
            case 'SERVICE_UNAVAILABLE':
                // Show retry message to user
                break;
            case 'AUTHENTICATION_ERROR':
                // Redirect to login
                break;
            case 'VALIDATION_ERROR':
                // Show validation error to user
                break;
            default:
                // Show generic error
                break;
        }
    }
}