Text Translation
POST
/translate-text/
Translates a single text from a source language to one or more target languages with optional styling.
Request Parameters
Parameter
Type
Required
Description
text
string
Yes
Text to translate (max 5000 characters)
source_language
string
Yes
Source language code
target_languages
array
No
Target languages (if empty, translates to all except source)
translation_style
string
No
Translation style (e.g., "formal", "casual", "technical")
Request Example
curl -X POST "https://your-api-domain.com/translate-text/" \
-H "X-API-Key: your-api-key-here" \
-F "text=Hello world, how are you today?" \
-F "source_language=english" \
-F "target_languages=spanish" \
-F "target_languages=french" \
-F "translation_style=formal"
Response Format
{
"message": "Text translated successfully",
"id": 123,
"original_text": "Hello world, how are you today?",
"original_language": "english",
"translations": {
"spanish": "Hola mundo, ¿cómo estás hoy?",
"french": "Bonjour le monde, comment allez-vous aujourd'hui?"
}
}
CSV Translation
POST
/translate-csv/
Translates text content from a CSV file in batch mode. Perfect for processing multiple texts efficiently.
Request Parameters
Parameter
Type
Required
Description
file
file
Yes
CSV file with text in first column (max 10MB)
source_language
string
Yes
Source language code
target_languages
array
No
Target languages
translation_style
string
No
Translation style
Input CSV Format
Your input CSV should have the text to translate in the first column:
Text to translate
Hello world
How are you today?
Welcome to our service
Thank you for choosing us
Request Example
curl -X POST "https://your-api-domain.com/translate-csv/" \
-H "X-API-Key: your-api-key-here" \
-F "file=@translations.csv" \
-F "source_language=english" \
-F "target_languages=spanish" \
-F "target_languages=french" \
--output translated_file.csv
Output CSV Format
Returns a CSV file with original text and translations:
Original,spanish,french
Hello world,Hola mundo,Bonjour le monde
How are you today?,¿Cómo estás hoy?,Comment allez-vous aujourd'hui?
Welcome to our service,Bienvenido a nuestro servicio,Bienvenue dans notre service
Thank you for choosing us,Gracias por elegirnos,Merci de nous avoir choisis
Implementation Examples
Python
C#
Java
JavaScript
PHP
C++
Python Implementation
import requests
import json
class TranslationAPI:
def __init__(self, base_url, api_key):
self.base_url = base_url
self.headers = {"X-API-Key": api_key}
def translate_text(self, text, source_lang, target_langs=None, style=None):
"""Translate a single text"""
url = f"{self.base_url}/translate-text/"
data = {
"text": text,
"source_language": source_lang
}
if target_langs:
data["target_languages"] = target_langs
if style:
data["translation_style"] = style
response = requests.post(url, headers=self.headers, data=data)
response.raise_for_status()
return response.json()
def translate_csv(self, file_path, source_lang, target_langs=None, style=None):
"""Translate a CSV file"""
url = f"{self.base_url}/translate-csv/"
data = {"source_language": source_lang}
if target_langs:
data["target_languages"] = target_langs
if style:
data["translation_style"] = style
with open(file_path, 'rb') as f:
files = {"file": f}
response = requests.post(url, headers=self.headers, data=data, files=files)
response.raise_for_status()
return response.content
def get_translations(self, translation_type="all", limit=50, offset=0):
"""Get list of translations"""
url = f"{self.base_url}/api/translations/"
params = {
"translation_type": translation_type,
"limit": limit,
"offset": offset
}
response = requests.get(url, headers=self.headers, params=params)
response.raise_for_status()
return response.json()
# Usage example
api = TranslationAPI("https://your-api-domain.com", "your-api-key-here")
# Translate text
result = api.translate_text(
text="Hello, how are you?",
source_lang="english",
target_langs=["spanish", "french"],
style="formal"
)
print(json.dumps(result, indent=2))
# Translate CSV
csv_content = api.translate_csv(
file_path="input.csv",
source_lang="english",
target_langs=["spanish"]
)
with open("output.csv", "wb") as f:
f.write(csv_content)
C# Implementation
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json;
public class TranslationAPI
{
private readonly HttpClient _httpClient;
private readonly string _baseUrl;
public TranslationAPI(string baseUrl, string apiKey)
{
_baseUrl = baseUrl;
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Add("X-API-Key", apiKey);
}
public async Task<TranslationResponse> TranslateTextAsync(
string text,
string sourceLanguage,
List<string> targetLanguages = null,
string style = null)
{
var content = new MultipartFormDataContent();
content.Add(new StringContent(text), "text");
content.Add(new StringContent(sourceLanguage), "source_language");
if (targetLanguages != null)
{
foreach (var lang in targetLanguages)
{
content.Add(new StringContent(lang), "target_languages");
}
}
if (!string.IsNullOrEmpty(style))
{
content.Add(new StringContent(style), "translation_style");
}
var response = await _httpClient.PostAsync($"{_baseUrl}/translate-text/", content);
response.EnsureSuccessStatusCode();
var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TranslationResponse>(jsonResponse);
}
public async Task<byte[]> TranslateCsvAsync(
byte[] csvData,
string fileName,
string sourceLanguage,
List<string> targetLanguages = null)
{
var content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(csvData), "file", fileName);
content.Add(new StringContent(sourceLanguage), "source_language");
if (targetLanguages != null)
{
foreach (var lang in targetLanguages)
{
content.Add(new StringContent(lang), "target_languages");
}
}
var response = await _httpClient.PostAsync($"{_baseUrl}/translate-csv/", content);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync();
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
public class TranslationResponse
{
public string Message { get; set; }
public int Id { get; set; }
public string OriginalText { get; set; }
public string OriginalLanguage { get; set; }
public Dictionary<string, string> Translations { get; set; }
}
// Usage example
class Program
{
static async Task Main(string[] args)
{
var api = new TranslationAPI("https://your-api-domain.com", "your-api-key-here");
try
{
var result = await api.TranslateTextAsync(
"Hello, how are you?",
"english",
new List<string> { "spanish", "french" },
"formal"
);
Console.WriteLine($"Translation ID: {result.Id}");
foreach (var translation in result.Translations)
{
Console.WriteLine($"{translation.Key}: {translation.Value}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
api.Dispose();
}
}
}
Java Implementation
import java.io.*;
import java.net.http.*;
import java.net.URI;
import java.util.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class TranslationAPI {
private final HttpClient httpClient;
private final String baseUrl;
private final String apiKey;
private final Gson gson;
public TranslationAPI(String baseUrl, String apiKey) {
this.baseUrl = baseUrl;
this.apiKey = apiKey;
this.httpClient = HttpClient.newHttpClient();
this.gson = new Gson();
}
public TranslationResponse translateText(String text, String sourceLanguage,
List<String> targetLanguages, String style)
throws IOException, InterruptedException {
String boundary = "----" + System.currentTimeMillis();
StringBuilder requestBody = new StringBuilder();
requestBody.append("--").append(boundary).append("\r\n");
requestBody.append("Content-Disposition: form-data; name=\"text\"\r\n\r\n");
requestBody.append(text).append("\r\n");
requestBody.append("--").append(boundary).append("\r\n");
requestBody.append("Content-Disposition: form-data; name=\"source_language\"\r\n\r\n");
requestBody.append(sourceLanguage).append("\r\n");
if (targetLanguages != null) {
for (String lang : targetLanguages) {
requestBody.append("--").append(boundary).append("\r\n");
requestBody.append("Content-Disposition: form-data; name=\"target_languages\"\r\n\r\n");
requestBody.append(lang).append("\r\n");
}
}
if (style != null) {
requestBody.append("--").append(boundary).append("\r\n");
requestBody.append("Content-Disposition: form-data; name=\"translation_style\"\r\n\r\n");
requestBody.append(style).append("\r\n");
}
requestBody.append("--").append(boundary).append("--\r\n");
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + "/translate-text/"))
.header("X-API-Key", apiKey)
.header("Content-Type", "multipart/form-data; boundary=" + boundary)
.POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException("API call failed: " + response.body());
}
return gson.fromJson(response.body(), TranslationResponse.class);
}
public List<Translation> getTranslations(String type, int limit, int offset)
throws IOException, InterruptedException {
String url = String.format("%s/api/translations/?translation_type=%s&limit=%d&offset=%d",
baseUrl, type, limit, offset);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("X-API-Key", apiKey)
.GET()
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException("API call failed: " + response.body());
}
Map<String, Object> result = gson.fromJson(response.body(),
new TypeToken<Map<String, Object>>(){}.getType());
List<Map<String, Object> translationsData =
(List<Map<String, Object>>) result.get("translations");
List<Translation> translations = new ArrayList<>();
for (Map<String, Object> data : translationsData) {
translations.add(gson.fromJson(gson.toJson(data), Translation.class));
}
return translations;
}
// Data classes
public static class TranslationResponse {
public String message;
public int id;
public String originalText;
public String originalLanguage;
public Map<String, String> translations;
}
public static class Translation {
public int id;
public String type;
public String sourceLanguage;
public List<String> targetLanguages;
public String createdAt;
public double cost;
}
// Usage example
public static void main(String[] args) {
TranslationAPI api = new TranslationAPI("https://your-api-domain.com",
"your-api-key-here");
try {
TranslationResponse result = api.translateText(
"Hello, how are you?",
"english",
Arrays.asList("spanish", "french"),
"formal"
);
System.out.println("Translation ID: " + result.id);
result.translations.forEach((lang, text) ->
System.out.println(lang + ": " + text));
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
JavaScript/Node.js Implementation
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
class TranslationAPI {
constructor(baseUrl, apiKey) {
this.baseUrl = baseUrl;
this.headers = {
'X-API-Key': apiKey
};
}
async translateText(text, sourceLanguage, targetLanguages = null, style = null) {
const formData = new FormData();
formData.append('text', text);
formData.append('source_language', sourceLanguage);
if (targetLanguages) {
targetLanguages.forEach(lang => {
formData.append('target_languages', lang);
});
}
if (style) {
formData.append('translation_style', style);
}
try {
const response = await axios.post(
`${this.baseUrl}/translate-text/`,
formData,
{
headers: {
...this.headers,
...formData.getHeaders()
}
}
);
return response.data;
} catch (error) {
throw new Error(`Translation failed: ${error.response?.data?.detail || error.message}`);
}
}
async translateCSV(filePath, sourceLanguage, targetLanguages = null, style = null) {
const formData = new FormData();
formData.append('file', fs.createReadStream(filePath));
formData.append('source_language', sourceLanguage);
if (targetLanguages) {
targetLanguages.forEach(lang => {
formData.append('target_languages', lang);
});
}
if (style) {
formData.append('translation_style', style);
}
try {
const response = await axios.post(
`${this.baseUrl}/translate-csv/`,
formData,
{
headers: {
...this.headers,
...formData.getHeaders()
},
responseType: 'arraybuffer'
}
);
return response.data;
} catch (error) {
throw new Error(`CSV translation failed: ${error.response?.data?.detail || error.message}`);
}
}
async getTranslations(type = 'all', limit = 50, offset = 0) {
try {
const response = await axios.get(
`${this.baseUrl}/api/translations/`,
{
headers: this.headers,
params: {
translation_type: type,
limit: limit,
offset: offset
}
}
);
return response.data;
} catch (error) {
throw new Error(`Failed to get translations: ${error.response?.data?.detail || error.message}`);
}
}
async getTranslationById(id, type = 'text') {
try {
const response = await axios.get(
`${this.baseUrl}/api/translation/${id}`,
{
headers: this.headers,
params: { translation_type: type }
}
);
return response.data;
} catch (error) {
throw new Error(`Failed to get translation: ${error.response?.data?.detail || error.message}`);
}
}
}
// Usage example
async function example() {
const api = new TranslationAPI('https://your-api-domain.com', 'your-api-key-here');
try {
// Translate text
const textResult = await api.translateText(
'Hello, how are you?',
'english',
['spanish', 'french'],
'formal'
);
console.log('Text Translation Result:');
console.log(JSON.stringify(textResult, null, 2));
// Get translations list
const translations = await api.getTranslations('text', 10, 0);
console.log('Your translations:', translations);
// Translate CSV
const csvResult = await api.translateCSV(
'input.csv',
'english',
['spanish']
);
fs.writeFileSync('output.csv', csvResult);
console.log('CSV translation saved to output.csv');
} catch (error) {
console.error('Error:', error.message);
}
}
// Run example
example();
PHP Implementation
<?php
class TranslationAPI {
private $baseUrl;
private $apiKey;
public function __construct($baseUrl, $apiKey) {
$this->baseUrl = $baseUrl;
$this->apiKey = $apiKey;
}
private function getHeaders() {
return [
'X-API-Key: ' . $this->apiKey
];
}
public function translateText($text, $sourceLanguage, $targetLanguages = null, $style = null) {
$url = $this->baseUrl . '/translate-text/';
$postData = [
'text' => $text,
'source_language' => $sourceLanguage
];
if ($targetLanguages) {
foreach ($targetLanguages as $lang) {
$postData['target_languages[]'] = $lang;
}
}
if ($style) {
$postData['translation_style'] = $style;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_error($ch)) {
throw new Exception('cURL error: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('Translation failed. HTTP Code: ' . $httpCode . ' Response: ' . $response);
}
return json_decode($response, true);
}
public function translateCSV($filePath, $sourceLanguage, $targetLanguages = null, $style = null) {
$url = $this->baseUrl . '/translate-csv/';
$postData = [
'source_language' => $sourceLanguage
];
if ($targetLanguages) {
foreach ($targetLanguages as $lang) {
$postData['target_languages[]'] = $lang;
}
}
if ($style) {
$postData['translation_style'] = $style;
}
// Add file
$postData['file'] = new CURLFile($filePath);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_error($ch)) {
throw new Exception('cURL error: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('CSV translation failed. HTTP Code: ' . $httpCode);
}
return $response; // Returns CSV content
}
public function getTranslations($type = 'all', $limit = 50, $offset = 0) {
$url = $this->baseUrl . '/api/translations/?' . http_build_query([
'translation_type' => $type,
'limit' => $limit,
'offset' => $offset
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_error($ch)) {
throw new Exception('cURL error: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('Failed to get translations. HTTP Code: ' . $httpCode);
}
return json_decode($response, true);
}
public function getTranslationById($id, $type = 'text') {
$url = $this->baseUrl . '/api/translation/' . $id . '?' . http_build_query([
'translation_type' => $type
]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_error($ch)) {
throw new Exception('cURL error: ' . curl_error($ch));
}
curl_close($ch);
if ($httpCode !== 200) {
throw new Exception('Failed to get translation. HTTP Code: ' . $httpCode);
}
return json_decode($response, true);
}
}
// Usage example
try {
$api = new TranslationAPI('https://your-api-domain.com', 'your-api-key-here');
// Translate text
$result = $api->translateText(
'Hello, how are you?',
'english',
['spanish', 'french'],
'formal'
);
echo "Translation Result:\n";
echo json_encode($result, JSON_PRETTY_PRINT) . "\n";
// Get translations list
$translations = $api->getTranslations('text', 10, 0);
echo "Your translations:\n";
echo json_encode($translations, JSON_PRETTY_PRINT) . "\n";
// Translate CSV file
$csvContent = $api->translateCSV(
'input.csv',
'english',
['spanish']
);
file_put_contents('output.csv', $csvContent);
echo "CSV translation saved to output.csv\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
?>
C++ Implementation
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <curl/curl.h>
#include <json/json.h>
#include <fstream>
class TranslationAPI {
private:
std::string baseUrl;
std::string apiKey;
struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, struct MemoryStruct *userp) {
size_t realsize = size * nmemb;
char *ptr = (char*)realloc(userp->memory, userp->size + realsize + 1);
if (!ptr) {
printf("Not enough memory (realloc returned NULL)\n");
return 0;
}
userp->memory = ptr;
memcpy(&(userp->memory[userp->size]), contents, realsize);
userp->size += realsize;
userp->memory[userp->size] = 0;
return realsize;
}
public:
TranslationAPI(const std::string& url, const std::string& key)
: baseUrl(url), apiKey(key) {
curl_global_init(CURL_GLOBAL_DEFAULT);
}
~TranslationAPI() {
curl_global_cleanup();
}
Json::Value translateText(const std::string& text,
const std::string& sourceLanguage,
const std::vector<std::string>& targetLanguages = {},
const std::string& style = "") {
CURL *curl;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = (char*)malloc(1);
chunk.size = 0;
curl = curl_easy_init();
if (!curl) {
throw std::runtime_error("Failed to initialize CURL");
}
// Prepare form data
curl_mime *form = curl_mime_init(curl);
curl_mimepart *field;
// Add text field
field = curl_mime_addpart(form);
curl_mime_name(field, "text");
curl_mime_data(field, text.c_str(), CURL_ZERO_TERMINATED);
// Add source language
field = curl_mime_addpart(form);
curl_mime_name(field, "source_language");
curl_mime_data(field, sourceLanguage.c_str(), CURL_ZERO_TERMINATED);
// Add target languages
for (const auto& lang : targetLanguages) {
field = curl_mime_addpart(form);
curl_mime_name(field, "target_languages");
curl_mime_data(field, lang.c_str(), CURL_ZERO_TERMINATED);
}
// Add style if provided
if (!style.empty()) {
field = curl_mime_addpart(form);
curl_mime_name(field, "translation_style");
curl_mime_data(field, style.c_str(), CURL_ZERO_TERMINATED);
}
// Set headers
struct curl_slist *headers = NULL;
std::string authHeader = "X-API-Key: " + apiKey;
headers = curl_slist_append(headers, authHeader.c_str());
// Configure CURL
std::string url = baseUrl + "/translate-text/";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_MIMEPOST, form);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
// Perform request
res = curl_easy_perform(curl);
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
// Cleanup
curl_slist_free_all(headers);
curl_mime_free(form);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
free(chunk.memory);
throw std::runtime_error("CURL request failed: " + std::string(curl_easy_strerror(res)));
}
if (response_code != 200) {
std::string error = "HTTP error: " + std::to_string(response_code);
if (chunk.memory) {
error += " - " + std::string(chunk.memory);
}
free(chunk.memory);
throw std::runtime_error(error);
}
// Parse JSON response
Json::Value jsonResponse;
Json::CharReaderBuilder builder;
std::string errs;
std::istringstream responseStream(chunk.memory);
if (!Json::parseFromStream(builder, responseStream, &jsonResponse, &errs)) {
free(chunk.memory);
throw std::runtime_error("Failed to parse JSON response: " + errs);
}
free(chunk.memory);
return jsonResponse;
}
std::vector<char> translateCSV(const std::string& filePath,
const std::string& sourceLanguage,
const std::vector<std::string>& targetLanguages = {}) {
CURL *curl;
CURLcode res;
struct MemoryStruct chunk;
chunk.memory = (char*)malloc(1);
chunk.size = 0;
curl = curl_easy_init();
if (!curl) {
throw std::runtime_error("Failed to initialize CURL");
}
// Prepare form data
curl_mime *form = curl_mime_init(curl);
curl_mimepart *field;
// Add file
field = curl_mime_addpart(form);
curl_mime_name(field, "file");
curl_mime_filedata(field, filePath.c_str());
// Add source language
field = curl_mime_addpart(form);
curl_mime_name(field, "source_language");
curl_mime_data(field, sourceLanguage.c_str(), CURL_ZERO_TERMINATED);
// Add target languages
for (const auto& lang : targetLanguages) {
field = curl_mime_addpart(form);
curl_mime_name(field, "target_languages");
curl_mime_data(field, lang.c_str(), CURL_ZERO_TERMINATED);
}
// Set headers
struct curl_slist *headers = NULL;
std::string authHeader = "X-API-Key: " + apiKey;
headers = curl_slist_append(headers, authHeader.c_str());
// Configure CURL
std::string url = baseUrl + "/translate-csv/";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_MIMEPOST, form);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
// Perform request
res = curl_easy_perform(curl);
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
// Cleanup
curl_slist_free_all(headers);
curl_mime_free(form);
curl_easy_cleanup(curl);
if (res != CURLE_OK) {
free(chunk.memory);
throw std::runtime_error("CURL request failed: " + std::string(curl_easy_strerror(res)));
}
if (response_code != 200) {
free(chunk.memory);
throw std::runtime_error("HTTP error: " + std::to_string(response_code));
}
// Convert to vector
std::vector<char> result(chunk.memory, chunk.memory + chunk.size);
free(chunk.memory);
return result;
}
};
// Usage example
int main() {
try {
TranslationAPI api("https://your-api-domain.com", "your-api-key-here");
// Translate text
std::vector<std::string> targetLangs = {"spanish", "french"};
Json::Value result = api.translateText(
"Hello, how are you?",
"english",
targetLangs,
"formal"
);
std::cout << "Translation Result:" << std::endl;
std::cout << result << std::endl;
// Translate CSV
std::vector<char> csvResult = api.translateCSV(
"input.csv",
"english",
{"spanish"}
);
// Save CSV result
std::ofstream outFile("output.csv", std::ios::binary);
outFile.write(csvResult.data(), csvResult.size());
outFile.close();
std::cout << "CSV translation saved to output.csv" << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
return 0;
}