Tutorial June 5, 2025

API Integration Tutorial

Step-by-step guide to integrating AltText.io API into your application, with code examples and best practices.

The AltText.io API provides a powerful way to automatically generate image metadata at scale. Whether you're building a content management system, e-commerce platform, or any application that handles images, this tutorial will guide you through the integration process.

By the end of this tutorial, you'll be able to programmatically send images to AltText.io and receive SEO-optimized alt text, titles, descriptions, and keywords for your images.

Prerequisites

Before starting, ensure you have:

  • An AltText.io account with API access
  • Your API key (found in dashboard settings)
  • Basic knowledge of HTTP requests and JSON
  • A programming language of choice (we'll use examples in multiple languages)

API Overview

Endpoint Details:

  • Base URL: https://api.alttext.io/
  • Endpoint: POST /getmetadata
  • Authentication: API key in request body
  • Response Format: JSON
  • Rate Limit: Based on your subscription plan

Request Parameters

The API accepts the following parameters in the request body:

Parameter Type Required Description
api_key string Yes Your AltText.io API key
image_url string Yes Public URL of the image
mode string No "seo" (default) or "stock"
seo_keywords string No Custom keywords to optimize for
language string No ISO 639-1 code (default: "en")

Basic Integration Examples

JavaScript (Node.js)

const axios = require('axios');

async function getImageMetadata(imageUrl) {
    try {
        const response = await axios.post('https://api.alttext.io/getmetadata', {
            api_key: 'YOUR_API_KEY_HERE',
            image_url: imageUrl,
            mode: 'seo'
        });
        
        return response.data;
    } catch (error) {
        console.error('Error:', error.response?.data || error.message);
        throw error;
    }
}

// Usage
getImageMetadata('https://example.com/image.jpg')
    .then(metadata => {
        console.log('Alt Text:', metadata.alt_text);
        console.log('Title:', metadata.title);
        console.log('Description:', metadata.description);
        console.log('Keywords:', metadata.keywords.join(', '));
    });

Python

import requests
import json

def get_image_metadata(image_url):
    endpoint = 'https://api.alttext.io/getmetadata'
    
    payload = {
        'api_key': 'YOUR_API_KEY_HERE',
        'image_url': image_url,
        'mode': 'seo'
    }
    
    try:
        response = requests.post(endpoint, json=payload)
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f'Error: {e}')
        return None

# Usage
metadata = get_image_metadata('https://example.com/image.jpg')
if metadata:
    print(f"Alt Text: {metadata['alt_text']}")
    print(f"Title: {metadata['title']}")
    print(f"Description: {metadata['description']}")
    print(f"Keywords: {', '.join(metadata['keywords'])}")

PHP

<?php
function getImageMetadata($imageUrl) {
    $endpoint = 'https://api.alttext.io/getmetadata';
    
    $data = array(
        'api_key' => 'YOUR_API_KEY_HERE',
        'image_url' => $imageUrl,
        'mode' => 'seo'
    );
    
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/json\r\n",
            'method'  => 'POST',
            'content' => json_encode($data)
        )
    );
    
    $context = stream_context_create($options);
    $result = file_get_contents($endpoint, false, $context);
    
    if ($result === FALSE) {
        return null;
    }
    
    return json_decode($result, true);
}

// Usage
$metadata = getImageMetadata('https://example.com/image.jpg');
if ($metadata) {
    echo "Alt Text: " . $metadata['alt_text'] . "\n";
    echo "Title: " . $metadata['title'] . "\n";
    echo "Description: " . $metadata['description'] . "\n";
    echo "Keywords: " . implode(', ', $metadata['keywords']) . "\n";
}
?>

Advanced Features

Stock Photography Mode

For stock photography platforms, use mode "stock" to get metadata optimized for stock photo sales:

const stockMetadata = await axios.post('https://api.alttext.io/getmetadata', {
    api_key: 'YOUR_API_KEY_HERE',
    image_url: imageUrl,
    mode: 'stock'  // Returns ~50 keywords optimized for stock photography
});

Custom SEO Keywords

Optimize metadata for specific keywords by providing them in your request:

const customMetadata = await axios.post('https://api.alttext.io/getmetadata', {
    api_key: 'YOUR_API_KEY_HERE',
    image_url: imageUrl,
    mode: 'seo',
    seo_keywords: 'sustainable fashion, eco-friendly clothing, organic cotton'
});

Multi-Language Support

Generate metadata in over 130 languages by specifying the language code:

// Spanish
const spanishMetadata = await axios.post('https://api.alttext.io/getmetadata', {
    api_key: 'YOUR_API_KEY_HERE',
    image_url: imageUrl,
    language: 'es'
});

// French
const frenchMetadata = await axios.post('https://api.alttext.io/getmetadata', {
    api_key: 'YOUR_API_KEY_HERE',
    image_url: imageUrl,
    language: 'fr'
});

Error Handling

The API returns standard HTTP status codes and detailed error messages:

Common Error Responses:

  • 400 Bad Request: Missing required parameters
  • 401 Unauthorized: Invalid API key
  • 402 Payment Required: No credits remaining
  • 404 Not Found: Image URL not accessible
  • 429 Too Many Requests: Rate limit exceeded
  • 500 Internal Server Error: Server-side issue

Example error handling implementation:

async function getImageMetadataWithErrorHandling(imageUrl) {
    try {
        const response = await axios.post('https://api.alttext.io/getmetadata', {
            api_key: 'YOUR_API_KEY_HERE',
            image_url: imageUrl
        });
        
        return { success: true, data: response.data };
    } catch (error) {
        if (error.response) {
            // API returned an error
            switch (error.response.status) {
                case 401:
                    return { success: false, error: 'Invalid API key' };
                case 402:
                    return { success: false, error: 'No credits remaining' };
                case 429:
                    return { success: false, error: 'Rate limit exceeded' };
                default:
                    return { success: false, error: error.response.data.message };
            }
        } else {
            // Network or other error
            return { success: false, error: 'Network error occurred' };
        }
    }
}

Best Practices

Follow These Guidelines:

  1. Validate Image URLs: Ensure URLs are accessible before sending to API
  2. Implement Retry Logic: Handle temporary failures gracefully
  3. Cache Results: Store metadata to avoid duplicate API calls
  4. Monitor Usage: Track your credit consumption
  5. Batch Processing: Queue images for efficient processing
  6. Security: Never expose API keys in client-side code

Complete Integration Example

Here's a complete example showing a production-ready integration with error handling, retry logic, and caching:

class AltTextClient {
    constructor(apiKey) {
        this.apiKey = apiKey;
        this.endpoint = 'https://api.alttext.io/getmetadata';
        this.cache = new Map();
    }
    
    async getMetadata(imageUrl, options = {}) {
        // Check cache first
        const cacheKey = `${imageUrl}-${JSON.stringify(options)}`;
        if (this.cache.has(cacheKey)) {
            return this.cache.get(cacheKey);
        }
        
        const payload = {
            api_key: this.apiKey,
            image_url: imageUrl,
            ...options
        };
        
        // Retry logic
        let attempts = 0;
        const maxAttempts = 3;
        
        while (attempts < maxAttempts) {
            try {
                const response = await fetch(this.endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const data = await response.json();
                
                // Cache successful result
                this.cache.set(cacheKey, data);
                
                return data;
            } catch (error) {
                attempts++;
                if (attempts === maxAttempts) {
                    throw error;
                }
                // Wait before retry (exponential backoff)
                await new Promise(resolve => setTimeout(resolve, 1000 * attempts));
            }
        }
    }
    
    // Batch processing method
    async processImages(imageUrls, options = {}) {
        const results = await Promise.allSettled(
            imageUrls.map(url => this.getMetadata(url, options))
        );
        
        return results.map((result, index) => ({
            imageUrl: imageUrls[index],
            success: result.status === 'fulfilled',
            data: result.status === 'fulfilled' ? result.value : null,
            error: result.status === 'rejected' ? result.reason.message : null
        }));
    }
}

// Usage
const client = new AltTextClient('YOUR_API_KEY_HERE');

// Single image
const metadata = await client.getMetadata('https://example.com/image.jpg', {
    mode: 'seo',
    seo_keywords: 'product photography, e-commerce'
});

// Batch processing
const images = [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
    'https://example.com/image3.jpg'
];

const results = await client.processImages(images, { mode: 'stock' });

WordPress Plugin Alternative

If you're using WordPress, consider our official plugin for easier integration:

  • Automatic processing on image upload
  • Bulk processing for existing media library
  • No coding required
  • Direct integration with WordPress media

Ready to Get Started?

Sign up for AltText.io and get your API key to start integrating today

Get API Access

Conclusion

The AltText.io API provides a simple yet powerful way to automate image metadata generation. With just a few lines of code, you can ensure all your images have proper alt text, titles, and descriptions for better SEO and accessibility.

Remember to handle errors gracefully, implement caching where appropriate, and monitor your usage to stay within your plan limits. For high-volume applications, consider implementing queue-based processing to distribute the load.

If you need help with your integration or have questions about the API, our support team is always ready to assist. Happy coding!