Multilingual Translation 🆕
🇹🇭 Multilingual Translation
The Multilingual Translation API provides fast, accurate translation between 28 languages using state-of-the-art language models. The API is designed for high performance and reliability with support for language detection and optimized handling of longer texts.
Try Demo
Features and Capabilities
Key Features
- 28 Languages Support: Translate between Arabic, Bengali, Czech, German, English, Spanish, Persian, French, Hebrew, Hindi, Indonesian, Italian, Japanese, Khmer, Korean, Lao, Malay, Burmese, Dutch, Polish, Portuguese, Russian, Thai, Tagalog, Turkish, Urdu, Vietnamese, and Chinese.
- VLLM Integration: Optimized with VLLM for high-throughput, memory-efficient inference with configurable parameters.
- REST API: Simple API with single and batch translation endpoints.
- Batch Compatible: Process multiple translation requests simultaneously for improved throughput.
- Unlimited Text Length: Smart chunking system handles texts of any length by splitting at sentence boundaries and preserving context between chunks.
Performance
- Fast processing (< 0.1 seconds per request for typical text)
- Supports batch processing for multiple translations
- Average 0.16-0.25 seconds per 100 characters
- 1000-character document in ~1.6 seconds (Thai → English)
- Long documents processed through intelligent chunking with minimal quality loss
- Optimized for long text with automatic chunking
- Translation caching for improved response times
Quality
- High accuracy translations powered by models
- Context-aware translation that preserves meaning
- Support for 28 languages with quality metrics
Endpoints
Translate Text
Translates text between any of the supported languages.
Endpoint: POST /v1/text/translate
Content-Type: application/x-www-form-urlencoded
Headers:
apikey
(required): Your API key for authentication
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
text | String | Yes | Text to translate |
source_lang | String | Yes | Source language code (e.g., 'en', 'th', 'zh') |
target_lang | String | Yes | Target language code (e.g., 'en', 'th', 'zh') |
max_length | Integer | No | Maximum length of generated translation (default: 2048, max: 4096) |
use_cache | Boolean | No | Whether to use cached results (default: based on server configuration) |
Example Request:
curl -X POST "https://api.iapp.co.th/v1/text/translate" \
-H "apikey: YOUR_API_KEY" \
-F "text=Hello, how are you?" \
-F "source_lang=en" \
-F "target_lang=th" \
-F "max_length=2048" \
-F "use_cache=false"
Example Response:
{
"translation": "สวัสดี คุณสบายดีไหม",
"source_lang": "en",
"target_lang": "th",
"original_text": "Hello, how are you?",
"processing_time": 0.056,
"cached": false
}
Batch Translation
Translates multiple texts in a single request.
Endpoint: POST /v1/text/batch_translate
Content-Type: application/json
Headers:
apikey
(required): Your API key for authentication
Request Body:
An array of objects, each with the following fields:
Field | Type | Required | Description |
---|---|---|---|
text | String | Yes | Text to translate |
source_lang | String | Yes | Source language code (e.g., 'en', 'th', 'zh') |
target_lang | String | Yes | Target language code (e.g., 'en', 'th', 'zh') |
max_length | Integer | No | Maximum length of generated translation (default: 2048) |
use_cache | Boolean | No | Whether to use cached results (default: based on server configuration) |
Example Request:
curl -X POST "https://api.iapp.co.th/v1/text/batch_translate" \
-H "apikey: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '[
{
"text": "Hello, how are you?",
"source_lang": "en",
"target_lang": "fr",
"max_length": 2048,
"use_cache": true
},
{
"text": "こんにちは、元気ですか?",
"source_lang": "ja",
"target_lang": "en",
"max_length": 2048,
"use_cache": true
}
]'
Example Response:
{
"results": [
{
"translation": "Bonjour, comment allez-vous ?",
"source_lang": "en",
"target_lang": "fr",
"original_text": "Hello, how are you?",
"cached": false,
"index": 0
},
{
"translation": "Hello, how are you?",
"source_lang": "ja",
"target_lang": "en",
"original_text": "こんにちは、元気ですか?",
"cached": false,
"index": 1
}
],
"count": 2,
"processing_time": 0.139
}
Cache Statistics
Returns statistics about the translation cache.
Endpoint: GET /cache/stats
Headers:
apikey
(required): Your API key for authentication
Example Request:
curl -X GET "https://api.iapp.co.th/cache/stats" \
-H "apikey: YOUR_API_KEY"
Example Response:
{
"cache_enabled": true,
"cache_size": 42,
"max_cache_size": 1000,
"cache_hit_rate": 0.65,
"default_use_cache": true
}
Clear Cache
Clears the translation cache.
Endpoint: POST /cache/clear
Headers:
apikey
(required): Your API key for authentication
Example Request:
curl -X POST "https://api.iapp.co.th/cache/clear" \
-H "apikey: YOUR_API_KEY"
Example Response:
{
"status": "success",
"message": "Cache cleared successfully",
"items_removed": 42
}
Error Responses
The API returns appropriate HTTP status codes along with error details:
Example Error Response:
{
"detail": "Source and target languages must be different"
}
Common error status codes:
400 Bad Request
: Invalid parameters401 Unauthorized
: Missing or invalid API key429 Too Many Requests
: Rate limit exceeded500 Internal Server Error
: Server-side error503 Service Unavailable
: Model not loaded or service not ready
Code Examples
Python
import requests
def translate_text(text, source_lang, target_lang, api_key, api_url="https://api.iapp.co.th"):
"""
Translate text using the Translation API
Args:
text (str): Text to translate
source_lang (str): Source language code (e.g., 'en', 'th', 'zh')
target_lang (str): Target language code (e.g., 'en', 'th', 'zh')
api_key (str): Your API key
api_url (str): Base URL of the API
Returns:
dict: Translation response
"""
# Prepare request data
data = {
"text": text,
"source_lang": source_lang,
"target_lang": target_lang
}
# Set headers with API key
headers = {
"apikey": api_key
}
# Send request to API
response = requests.post(f"{api_url}/v1/text/translate", data=data, headers=headers)
response.raise_for_status() # Raise exception for HTTP errors
return response.json()
JavaScript
// Using fetch API
async function translateText(text, sourceLang, targetLang, apiKey, apiUrl = "https://api.iapp.co.th") {
const formData = new FormData()
formData.append("text", text)
formData.append("source_lang", sourceLang)
formData.append("target_lang", targetLang)
try {
const response = await fetch(`${apiUrl}/v1/text/translate`, {
method: "POST",
headers: {
apikey: apiKey,
},
body: formData,
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.detail || "Translation request failed")
}
return await response.json()
} catch (error) {
console.error("Translation error:", error)
throw error
}
}
Swift
import Foundation
struct TranslationResponse: Decodable {
let translation: String
let sourceLang: String
let targetLang: String
let originalText: String
let processingTime: Double
let cached: Bool
enum CodingKeys: String, CodingKey {
case translation
case sourceLang = "source_lang"
case targetLang = "target_lang"
case originalText = "original_text"
case processingTime = "processing_time"
case cached
}
}
class TranslationAPI {
let apiUrl: String
let apiKey: String
init(apiUrl: String = "https://api.iapp.co.th", apiKey: String) {
self.apiUrl = apiUrl
self.apiKey = apiKey
}
func translateText(text: String, sourceLang: String, targetLang: String, completion: @escaping (Result<TranslationResponse, Error>) -> Void) {
guard let url = URL(string: "\(apiUrl)/v1/text/translate") else {
completion(.failure(NSError(domain: "TranslationAPI", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])))
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue(apiKey, forHTTPHeaderField: "apikey")
let parameters = [
"text": text,
"source_lang": sourceLang,
"target_lang": targetLang
]
let boundary = UUID().uuidString
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = createFormData(parameters: parameters, boundary: boundary)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
completion(.failure(error))
return
}
guard let data = data else {
completion(.failure(NSError(domain: "TranslationAPI", code: 1, userInfo: [NSLocalizedDescriptionKey: "No data received"])))
return
}
do {
let translationResponse = try JSONDecoder().decode(TranslationResponse.self, from: data)
completion(.success(translationResponse))
} catch {
completion(.failure(error))
}
}
task.resume()
}
private func createFormData(parameters: [String: String], boundary: String) -> Data {
var body = Data()
for (key, value) in parameters {
body.append("--\(boundary)\r\n".data(using: .utf8)!)
body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".data(using: .utf8)!)
body.append("\(value)\r\n".data(using: .utf8)!)
}
body.append("--\(boundary)--\r\n".data(using: .utf8)!)
return body
}
}
PHP
<?php
function translateText($text, $sourceLang, $targetLang, $apiKey, $apiUrl = "https://api.iapp.co.th") {
// Prepare request data
$data = [
'text' => $text,
'source_lang' => $sourceLang,
'target_lang' => $targetLang
];
// Initialize cURL session
$ch = curl_init("$apiUrl/v1/text/translate");
// Set cURL options
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"apikey: $apiKey"
]);
// Execute cURL request
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close cURL session
curl_close($ch);
// Check for errors
if ($httpCode !== 200) {
$error = json_decode($response, true);
throw new Exception($error['detail'] ?? "Request failed with status code $httpCode");
}
// Return decoded response
return json_decode($response, true);
}
Kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.io.IOException
data class TranslationResponse(
val translation: String,
val sourceLang: String,
val targetLang: String,
val originalText: String,
val processingTime: Double,
val cached: Boolean
)
class TranslationAPI(
private val apiUrl: String = "https://api.iapp.co.th",
private val apiKey: String
) {
private val client = OkHttpClient()
suspend fun translateText(text: String, sourceLang: String, targetLang: String): TranslationResponse {
return withContext(Dispatchers.IO) {
val formBody = FormBody.Builder()
.add("text", text)
.add("source_lang", sourceLang)
.add("target_lang", targetLang)
.build()
val request = Request.Builder()
.url("$apiUrl/v1/text/translate")
.addHeader("apikey", apiKey)
.post(formBody)
.build()
val response = client.newCall(request).execute()
if (!response.isSuccessful) {
val errorBody = response.body?.string()
val errorJson = errorBody?.let { JSONObject(it) }
val errorMessage = errorJson?.optString("detail") ?: "Request failed with code ${response.code}"
throw IOException(errorMessage)
}
val responseBody = response.body?.string() ?: throw IOException("Empty response")
val json = JSONObject(responseBody)
TranslationResponse(
translation = json.getString("translation"),
sourceLang = json.getString("source_lang"),
targetLang = json.getString("target_lang"),
originalText = json.getString("original_text"),
processingTime = json.getDouble("processing_time"),
cached = json.getBoolean("cached")
)
}
}
}
// Example usage
suspend fun main() {
try {
val translator = TranslationAPI(apiKey = "YOUR_API_KEY")
val result = translator.translateText(
text = "Hello, how are you?",
sourceLang = "en",
targetLang = "th"
)
println("Original (${result.sourceLang}): ${result.originalText}")
println("Translation (${result.targetLang}): ${result.translation}")
} catch (e: Exception) {
println("Error: ${e.message}")
}
}
Java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public class TranslationAPI {
private final String apiUrl;
private final String apiKey;
private final HttpClient client;
public TranslationAPI(String apiKey) {
this(apiKey, "https://api.iapp.co.th");
}
public TranslationAPI(String apiKey, String apiUrl) {
this.apiKey = apiKey;
this.apiUrl = apiUrl;
this.client = HttpClient.newHttpClient();
}
public TranslationResponse translateText(String text, String sourceLang, String targetLang) throws IOException, InterruptedException {
// Create multipart form data boundary
String boundary = "Boundary-" + System.currentTimeMillis();
// Create form data
String formData = createFormData(boundary, Map.of(
"text", text,
"source_lang", sourceLang,
"target_lang", targetLang
));
// Build request
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl + "/v1/text/translate"))
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.header("apikey", apiKey)
.POST(HttpRequest.BodyPublishers.ofString(formData))
.build();
// Send request
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// Handle errors
if (response.statusCode() != 200) {
JSONObject errorJson = new JSONObject(response.body());
String errorMessage = errorJson.optString("detail", "Request failed with code " + response.statusCode());
throw new IOException(errorMessage);
}
// Parse response
JSONObject json = new JSONObject(response.body());
return new TranslationResponse(
json.getString("translation"),
json.getString("source_lang"),
json.getString("target_lang"),
json.getString("original_text"),
json.getDouble("processing_time"),
json.getBoolean("cached")
);
}
private String createFormData(String boundary, Map<String, String> parameters) {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : parameters.entrySet()) {
builder.append("--").append(boundary).append("\r\n");
builder.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"\r\n\r\n");
builder.append(entry.getValue()).append("\r\n");
}
builder.append("--").append(boundary).append("--\r\n");
return builder.toString();
}
public static class TranslationResponse {
private final String translation;
private final String sourceLang;
private final String targetLang;
private final String originalText;
private final double processingTime;
private final boolean cached;
public TranslationResponse(String translation, String sourceLang, String targetLang,
String originalText, double processingTime, boolean cached) {
this.translation = translation;
this.sourceLang = sourceLang;
this.targetLang = targetLang;
this.originalText = originalText;
this.processingTime = processingTime;
this.cached = cached;
}
// Getters
public String getTranslation() { return translation; }
public String getSourceLang() { return sourceLang; }
public String getTargetLang() { return targetLang; }
public String getOriginalText() { return originalText; }
public double getProcessingTime() { return processingTime; }
public boolean isCached() { return cached; }
}
}
Dart (Flutter)
import 'dart:convert';
import 'package:http/http.dart' as http;
class TranslationResponse {
final String translation;
final String sourceLang;
final String targetLang;
final String originalText;
final double processingTime;
final bool cached;
TranslationResponse({
required this.translation,
required this.sourceLang,
required this.targetLang,
required this.originalText,
required this.processingTime,
required this.cached
});
factory TranslationResponse.fromJson(Map<String, dynamic> json) {
return TranslationResponse(
translation: json['translation'],
sourceLang: json['source_lang'],
targetLang: json['target_lang'],
originalText: json['original_text'],
processingTime: json['processing_time'].toDouble(),
cached: json['cached'],
);
}
}
class TranslationAPI {
final String apiUrl;
final String apiKey;
TranslationAPI({
this.apiUrl = 'https://api.iapp.co.th',
required this.apiKey,
});
Future<TranslationResponse> translateText({
required String text,
required String sourceLang,
required String targetLang,
}) async {
// Create form data
var request = http.MultipartRequest('POST', Uri.parse('$apiUrl/v1/text/translate'));
// Add headers
request.headers['apikey'] = apiKey;
// Add form fields
request.fields['text'] = text;
request.fields['source_lang'] = sourceLang;
request.fields['target_lang'] = targetLang;
try {
// Send request
var streamedResponse = await request.send();
var response = await http.Response.fromStream(streamedResponse);
// Handle errors
if (response.statusCode != 200) {
Map<String, dynamic> errorData = jsonDecode(response.body);
throw Exception(errorData['detail'] ?? 'Request failed with status code ${response.statusCode}');
}
// Parse response
Map<String, dynamic> jsonData = jsonDecode(response.body);
return TranslationResponse.fromJson(jsonData);
} catch (e) {
throw Exception('Translation request failed: $e');
}
}
}
// Example usage
void main() async {
try {
final translator = TranslationAPI(apiKey: 'YOUR_API_KEY');
final result = await translator.translateText(
text: 'Hello, how are you?',
sourceLang: 'en',
targetLang: 'th',
);
print('Original (${result.sourceLang}): ${result.originalText}');
print('Translation (${result.targetLang}): ${result.translation}');
} catch (e) {
print('Error: $e');
}
}