API Usage Examples

Copy-paste code for real-world translation scenarios. Python & JavaScript, ready to run.

1 E-commerce Product Translation

Translate product titles, descriptions, and specs for international storefronts. Batch translate to cut API calls by 10x.

import requests

API_KEY = "your-api-key"
BASE    = "https://api.socketsio.com"

# Batch translate product info to 3 languages
products = [
    "Wireless Bluetooth Headphones - Active Noise Cancelling",
    "Premium quality, 40-hour battery life, foldable design",
    "Compatible with iOS, Android, Windows, macOS"
]

for lang in ["zh", "ja", "de"]:
    resp = requests.post(f"{BASE}/v1/translate/batch", json={
        "q": products,
        "target": lang
    }, headers={"X-API-Key": API_KEY})

    data = resp.json()
    print(f"\n--- {lang.upper()} ---")
    for item in data["data"]["translations"]:
        print(item["translatedText"])

2 Real-time Chat Translation

Detect the sender's language automatically, then translate to the recipient's preferred language. Sub-200ms latency.

import requests

API_KEY = "your-api-key"
BASE    = "https://api.socketsio.com"

def translate_message(text, recipient_lang="en"):
    """Auto-detect source language and translate."""
    # Step 1: Detect language
    detect = requests.post(f"{BASE}/v1/detect", json={
        "q": text
    }, headers={"X-API-Key": API_KEY}).json()

    source_lang = detect["data"]["detections"][0][0]["language"]

    # Skip if already in recipient's language
    if source_lang == recipient_lang:
        return text

    # Step 2: Translate
    result = requests.post(f"{BASE}/v1/translate", json={
        "q": text,
        "target": recipient_lang,
        "source": source_lang
    }, headers={"X-API-Key": API_KEY}).json()

    return result["data"]["translations"][0]["translatedText"]

# Usage
messages = [
    ("こんにちは、元気ですか?", "en"),
    ("Bonjour, comment allez-vous?", "zh"),
    ("오늘 날씨가 좋네요", "en"),
]

for msg, target in messages:
    translated = translate_message(msg, target)
    print(f"{msg}  →  {translated}")

3 Website & CMS Localization

Translate all UI strings from a JSON locale file. Perfect for React i18n, Vue i18n, or any JSON-based localization system.

import requests, json

API_KEY = "your-api-key"
BASE    = "https://api.socketsio.com"

# Your English locale file
en_locale = {
    "nav.home": "Home",
    "nav.pricing": "Pricing",
    "nav.docs": "Documentation",
    "hero.title": "Build faster with our API",
    "hero.subtitle": "Ship multilingual apps in minutes, not months",
    "cta.signup": "Get Started Free",
    "cta.demo": "Watch Demo",
    "footer.terms": "Terms of Service",
    "footer.privacy": "Privacy Policy"
}

def translate_locale(locale_dict, target_lang):
    """Translate all values in a locale dict using batch API."""
    keys = list(locale_dict.keys())
    values = list(locale_dict.values())

    resp = requests.post(f"{BASE}/v1/translate/batch", json={
        "q": values,
        "target": target_lang
    }, headers={"X-API-Key": API_KEY}).json()

    translated = {}
    for i, item in enumerate(resp["data"]["translations"]):
        translated[keys[i]] = item["translatedText"]
    return translated

# Generate locale files for 5 languages
for lang in ["zh", "ja", "ko", "es", "fr"]:
    result = translate_locale(en_locale, lang)
    with open(f"locale_{lang}.json", "w", encoding="utf-8") as f:
        json.dump(result, f, ensure_ascii=False, indent=2)
    print(f"✅ locale_{lang}.json — {len(result)} strings")

4 Email Template Translation

Translate transactional email templates while preserving placeholders like {{name}} and {{amount}}. Send localized emails at scale.

import requests, re

API_KEY = "your-api-key"
BASE    = "https://api.socketsio.com"

def translate_template(template, target_lang):
    """Translate text while preserving {{placeholders}}."""
    # Extract and replace placeholders with tokens
    placeholders = re.findall(r'\{\{.*?\}\}', template)
    safe = template
    for i, ph in enumerate(placeholders):
        safe = safe.replace(ph, f"__PH{i}__")

    # Translate
    resp = requests.post(f"{BASE}/v1/translate", json={
        "q": safe,
        "target": target_lang
    }, headers={"X-API-Key": API_KEY}).json()

    result = resp["data"]["translations"][0]["translatedText"]

    # Restore placeholders
    for i, ph in enumerate(placeholders):
        result = result.replace(f"__PH{i}__", ph)
    return result

# Email templates
templates = {
    "welcome": "Hi {{name}}, welcome to SocketsIO! Your API key is ready.",
    "invoice": "Dear {{name}}, your invoice for {{amount}} is attached.",
    "reset":   "Click here to reset your password, {{name}}."
}

for key, tmpl in templates.items():
    for lang in ["ja", "es"]:
        translated = translate_template(tmpl, lang)
        print(f"[{key}/{lang}] {translated}")

5 Language Detection & Routing

Detect the language of incoming text to route support tickets, classify content, or auto-select translation targets.

import requests

API_KEY = "your-api-key"
BASE    = "https://api.socketsio.com"

# Support tickets from around the world
tickets = [
    "My payment didn't go through, please help!",
    "支払いができません。助けてください。",
    "Mi pago no se procesó, necesito ayuda.",
    "Meine Zahlung wurde nicht verarbeitet.",
    "결제가 안 됩니다. 도와주세요."
]

TEAM_ROUTING = {
    "en": "team-us",
    "ja": "team-japan",
    "es": "team-latam",
    "de": "team-europe",
    "ko": "team-korea"
}

for ticket in tickets:
    resp = requests.post(f"{BASE}/v1/detect", json={
        "q": ticket
    }, headers={"X-API-Key": API_KEY}).json()

    lang = resp["data"]["detections"][0][0]["language"]
    conf = resp["data"]["detections"][0][0]["confidence"]
    team = TEAM_ROUTING.get(lang, "team-default")

    print(f"[{lang} {conf:.0%}] → {team}: {ticket[:40]}...")

6 Django Middleware — Auto-translate Responses

Drop-in Django middleware that automatically translates API responses based on the Accept-Language header. Zero changes to your existing views.

# translation_middleware.py
import json
import requests

SOCKETSIO_API_KEY = "your-api-key"
SOCKETSIO_BASE = "https://api.socketsio.com"

class AutoTranslateMiddleware:
    """
    Django middleware that auto-translates JSON responses
    based on the Accept-Language request header.
    
    Add to settings.py MIDDLEWARE list:
        'myapp.translation_middleware.AutoTranslateMiddleware'
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        # Only process JSON responses
        content_type = response.get("Content-Type", "")
        if "application/json" not in content_type:
            return response

        # Get target language from Accept-Language header
        accept_lang = request.META.get("HTTP_ACCEPT_LANGUAGE", "en")
        target_lang = accept_lang.split(",")[0].split("-")[0].strip()

        # Skip if already English
        if target_lang == "en":
            return response

        try:
            data = json.loads(response.content)
            translated = self._translate_dict(data, target_lang)
            response.content = json.dumps(translated, ensure_ascii=False).encode("utf-8")
            response["Content-Length"] = len(response.content)
        except Exception:
            pass  # Fail silently — return original response

        return response

    def _translate_dict(self, obj, target_lang):
        """Recursively translate all string values in a dict/list."""
        if isinstance(obj, str) and obj.strip():
            return self._translate_text(obj, target_lang)
        elif isinstance(obj, dict):
            return {k: self._translate_dict(v, target_lang) for k, v in obj.items()}
        elif isinstance(obj, list):
            return [self._translate_dict(item, target_lang) for item in obj]
        return obj

    def _translate_text(self, text, target_lang):
        resp = requests.post(
            f"{SOCKETSIO_BASE}/v1/translate",
            json={"q": text, "target": target_lang},
            headers={"X-API-Key": SOCKETSIO_API_KEY},
            timeout=5
        )
        resp.raise_for_status()
        return resp.json()["data"]["translations"][0]["translatedText"]


# --- Usage in settings.py ---
# MIDDLEWARE = [
#     'django.middleware.security.SecurityMiddleware',
#     'myapp.translation_middleware.AutoTranslateMiddleware',  # Add here
#     ...
# ]
#
# Now any API endpoint automatically returns translated content:
# curl -H "Accept-Language: ja" https://yourapp.com/api/products/
# → Returns Japanese product descriptions

7 Express.js Middleware — i18n API Gateway

Express middleware that intercepts outgoing JSON responses and translates them on-the-fly. Works with any Express app or REST API.

// translateMiddleware.js
const axios = require('axios');

const SOCKETSIO_API_KEY = process.env.SOCKETSIO_API_KEY || 'your-api-key';
const SOCKETSIO_BASE = 'https://api.socketsio.com';

/**
 * Express middleware: auto-translate JSON responses
 * based on Accept-Language header.
 * 
 * Usage:
 *   const { translateMiddleware } = require('./translateMiddleware');
 *   app.use(translateMiddleware);
 */
async function translateText(text, targetLang) {
  const res = await axios.post(
    `${SOCKETSIO_BASE}/v1/translate`,
    { q: text, target: targetLang },
    { headers: { 'X-API-Key': SOCKETSIO_API_KEY } }
  );
  return res.data.data.translations[0].translatedText;
}

async function translateDeep(obj, targetLang) {
  if (typeof obj === 'string' && obj.trim()) {
    return translateText(obj, targetLang);
  }
  if (Array.isArray(obj)) {
    return Promise.all(obj.map(item => translateDeep(item, targetLang)));
  }
  if (obj && typeof obj === 'object') {
    const result = {};
    for (const [key, val] of Object.entries(obj)) {
      result[key] = await translateDeep(val, targetLang);
    }
    return result;
  }
  return obj;
}

const translateMiddleware = (req, res, next) => {
  const acceptLang = req.headers['accept-language'] || 'en';
  const targetLang = acceptLang.split(',')[0].split('-')[0].trim();

  if (targetLang === 'en') return next();

  // Intercept res.json()
  const originalJson = res.json.bind(res);
  res.json = async (data) => {
    try {
      const translated = await translateDeep(data, targetLang);
      return originalJson(translated);
    } catch (err) {
      console.error('[translate-middleware] error:', err.message);
      return originalJson(data); // Fallback to original
    }
  };

  next();
};

module.exports = { translateMiddleware };

// --- app.js usage ---
// const express = require('express');
// const { translateMiddleware } = require('./translateMiddleware');
// const app = express();
// app.use(express.json());
// app.use(translateMiddleware);
//
// app.get('/api/products', (req, res) => {
//   res.json({ name: 'Wireless Headphones', description: 'Premium sound quality' });
// });
// // curl -H "Accept-Language: de" http://localhost:3000/api/products
// // → { "name": "Kabellose Kopfhörer", "description": "Premium-Klangqualität" }

8 React — useTranslation Hook

Custom React hook for real-time translation. Supports dynamic language switching, caching, and loading states. Drop into any React component.

// hooks/useTranslation.js
import { useState, useEffect, useRef } from 'react';

const API_KEY = process.env.REACT_APP_SOCKETSIO_KEY || 'your-api-key';
const BASE_URL = 'https://api.socketsio.com';

// Simple in-memory cache: { "en→ja:Hello": "こんにちは" }
const cache = {};

export function useTranslation(targetLang = 'en') {
  const [translations, setTranslations] = useState({});
  const [loading, setLoading] = useState(false);
  const pendingRef = useRef({});

  const t = (text) => {
    if (!text || targetLang === 'en') return text;
    const cacheKey = `${targetLang}:${text}`;
    return translations[cacheKey] || text; // Return cached or original while loading
  };

  const preload = async (texts) => {
    if (targetLang === 'en') return;

    const uncached = texts.filter(text => {
      const key = `${targetLang}:${text}`;
      return !cache[key] && !pendingRef.current[key];
    });

    if (uncached.length === 0) {
      // All cached — update state immediately
      const result = {};
      texts.forEach(text => {
        const key = `${targetLang}:${text}`;
        result[key] = cache[key] || text;
      });
      setTranslations(prev => ({ ...prev, ...result }));
      return;
    }

    // Mark as pending
    uncached.forEach(text => {
      pendingRef.current[`${targetLang}:${text}`] = true;
    });

    setLoading(true);
    try {
      const res = await fetch(`${BASE_URL}/v1/translate`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-API-Key': API_KEY },
        body: JSON.stringify({ q: uncached, target: targetLang })
      });
      const data = await res.json();
      const result = {};
      uncached.forEach((text, i) => {
        const key = `${targetLang}:${text}`;
        const translated = data.data.translations[i].translatedText;
        cache[key] = translated;
        result[key] = translated;
      });
      setTranslations(prev => ({ ...prev, ...result }));
    } catch (err) {
      console.error('[useTranslation] error:', err);
    } finally {
      setLoading(false);
      uncached.forEach(text => {
        delete pendingRef.current[`${targetLang}:${text}`];
      });
    }
  };

  return { t, preload, loading };
}

// --- Component usage ---
// import { useTranslation } from './hooks/useTranslation';
//
// function ProductCard({ product, lang }) {
//   const { t, preload, loading } = useTranslation(lang);
//
//   useEffect(() => {
//     preload([product.name, product.description]);
//   }, [product, lang]);
//
//   return (
//     <div className="product-card">
//       {loading && <span className="badge">Translating...</span>}
//       <h3>{t(product.name)}</h3>
//       <p>{t(product.description)}</p>
//     </div>
//   );
// }

9 Laravel — Translation Service

Laravel service class with facade support, caching via Laravel Cache, and Artisan command for bulk translation of lang files.

<?php
// app/Services/SocketsIOTranslator.php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class SocketsIOTranslator
{
    protected string $apiKey;
    protected string $baseUrl = 'https://api.socketsio.com';
    protected int $cacheTtl = 86400; // 24 hours

    public function __construct()
    {
        $this->apiKey = config('services.socketsio.key');
    }

    /**
     * Translate a single string.
     */
    public function translate(string $text, string $targetLang, string $sourceLang = null): string
    {
        $cacheKey = "socketsio:{$targetLang}:" . md5($text);

        return Cache::remember($cacheKey, $this->cacheTtl, function () use ($text, $targetLang, $sourceLang) {
            $payload = ['q' => $text, 'target' => $targetLang];
            if ($sourceLang) {
                $payload['source'] = $sourceLang;
            }

            $response = Http::withHeaders(['X-API-Key' => $this->apiKey])
                ->post("{$this->baseUrl}/v1/translate", $payload);

            $response->throw(); // Throws on 4xx/5xx

            return $response->json('data.translations.0.translatedText');
        });
    }

    /**
     * Translate multiple strings in one API call.
     */
    public function translateBatch(array $texts, string $targetLang): array
    {
        $response = Http::withHeaders(['X-API-Key' => $this->apiKey])
            ->post("{$this->baseUrl}/v1/translate", [
                'q'      => $texts,
                'target' => $targetLang,
            ]);

        $response->throw();

        return array_column($response->json('data.translations'), 'translatedText');
    }

    /**
     * Detect language of a string.
     */
    public function detect(string $text): array
    {
        $response = Http::withHeaders(['X-API-Key' => $this->apiKey])
            ->post("{$this->baseUrl}/v1/detect", ['q' => $text]);

        $response->throw();

        return $response->json('data.detections.0.0');
        // Returns: ['language' => 'ja', 'confidence' => 0.98, 'isReliable' => true]
    }
}

// --- config/services.php ---
// 'socketsio' => [
//     'key' => env('SOCKETSIO_API_KEY'),
// ],

// --- .env ---
// SOCKETSIO_API_KEY=your-api-key

// --- Usage in a Controller ---
// use App\Services\SocketsIOTranslator;
//
// class ProductController extends Controller {
//     public function show(Product $product, SocketsIOTranslator $translator) {
//         $lang = request()->header('Accept-Language', 'en');
//         $lang = substr($lang, 0, 2);
//
//         if ($lang !== 'en') {
//             $product->name = $translator->translate($product->name, $lang);
//             $product->description = $translator->translate($product->description, $lang);
//         }
//
//         return response()->json($product);
//     }
// }

10 Go — HTTP Client with Retry

Production-ready Go client for the SocketsIO API. Includes retry logic, context cancellation, and batch translation support.

// socketsio/client.go
package socketsio

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"
)

const baseURL = "https://api.socketsio.com"

type Client struct {
	APIKey     string
	HTTPClient *http.Client
	MaxRetries int
}

type TranslateRequest struct {
	Q      interface{} `json:"q"`      // string or []string
	Target string      `json:"target"`
	Source string      `json:"source,omitempty"`
	Format string      `json:"format,omitempty"` // "text" or "html"
}

type Translation struct {
	TranslatedText         string `json:"translatedText"`
	DetectedSourceLanguage string `json:"detectedSourceLanguage,omitempty"`
}

type TranslateResponse struct {
	Data struct {
		Translations []Translation `json:"translations"`
	} `json:"data"`
}

func NewClient(apiKey string) *Client {
	return &Client{
		APIKey:     apiKey,
		HTTPClient: &http.Client{Timeout: 10 * time.Second},
		MaxRetries: 3,
	}
}

// Translate translates a single string.
func (c *Client) Translate(ctx context.Context, text, targetLang string) (string, error) {
	results, err := c.TranslateBatch(ctx, []string{text}, targetLang)
	if err != nil {
		return "", err
	}
	return results[0], nil
}

// TranslateBatch translates multiple strings in one API call.
func (c *Client) TranslateBatch(ctx context.Context, texts []string, targetLang string) ([]string, error) {
	payload := TranslateRequest{Q: texts, Target: targetLang}
	body, _ := json.Marshal(payload)

	var resp TranslateResponse
	if err := c.doRequest(ctx, "/v1/translate", body, &resp); err != nil {
		return nil, err
	}

	results := make([]string, len(resp.Data.Translations))
	for i, t := range resp.Data.Translations {
		results[i] = t.TranslatedText
	}
	return results, nil
}

func (c *Client) doRequest(ctx context.Context, path string, body []byte, out interface{}) error {
	var lastErr error
	for attempt := 0; attempt <= c.MaxRetries; attempt++ {
		if attempt > 0 {
			select {
			case <-ctx.Done():
				return ctx.Err()
			case <-time.After(time.Duration(attempt*attempt) * 100 * time.Millisecond):
			}
		}

		req, err := http.NewRequestWithContext(ctx, "POST", baseURL+path, bytes.NewReader(body))
		if err != nil {
			return err
		}
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("X-API-Key", c.APIKey)

		httpResp, err := c.HTTPClient.Do(req)
		if err != nil {
			lastErr = err
			continue
		}
		defer httpResp.Body.Close()

		if httpResp.StatusCode == 429 {
			lastErr = fmt.Errorf("rate limit exceeded")
			continue
		}
		if httpResp.StatusCode >= 400 {
			b, _ := io.ReadAll(httpResp.Body)
			return fmt.Errorf("API error %d: %s", httpResp.StatusCode, string(b))
		}

		return json.NewDecoder(httpResp.Body).Decode(out)
	}
	return fmt.Errorf("max retries exceeded: %w", lastErr)
}

// --- main.go usage ---
// package main
//
// import (
//     "context"
//     "fmt"
//     "socketsio"
// )
//
// func main() {
//     client := socketsio.NewClient("your-api-key")
//     ctx := context.Background()
//
//     // Single translation
//     result, err := client.Translate(ctx, "Hello, World!", "ja")
//     if err != nil {
//         panic(err)
//     }
//     fmt.Println(result) // こんにちは、世界!
//
//     // Batch translation
//     texts := []string{"Good morning", "Thank you", "Goodbye"}
//     results, err := client.TranslateBatch(ctx, texts, "ko")
//     if err != nil {
//         panic(err)
//     }
//     for _, r := range results {
//         fmt.Println(r) // 좋은 아침, 감사합니다, 안녕히 가세요
//     }
// }

Ready to Build?

Get your free API key — 500,000 characters/month, no credit card required.

Get Free API Key →