Retrieves the final translated texts from a completed translation task using the provided run_id.
GET
/
translation-result
/
{run_id}
Copy
curl --request GET \ --url https://client.camb.ai/apis/translation-result/{run_id} \ --header 'x-api-key: <api-key>'
Copy
{ "texts": [ "<string>" ]}
This endpoint delivers the final product of your translation process: the translated texts themselves. Once your translation task has completed successfully and you’ve received a run_id, this endpoint allows you to retrieve the actual translations that were generated. Think of it as the pickup counter where you collect your finished translations after they’ve been processed.
To retrieve your translated texts, send a GET request to this endpoint with the run_id you received when your translation task was marked as completed. This run_id serves as your claim ticket for the finished translations. The system will respond with an array containing all your translated texts, preserving the same order as your original input.
When you call this endpoint, you’ll receive a response that includes your translated content:
texts: An array of strings containing the translated output texts. Each item in this array corresponds to one of the original texts you submitted, maintaining the same order. This makes it easy to match translations with their original content.
The structure of the response follows this format:
Copy
{ "texts": [ "Your first translated text", "Your second translated text", "Your third translated text" // ...and so on for all texts in your original request ]}
This straightforward response structure makes it simple to integrate translations into your application workflows. You can directly map each translated text to its corresponding original text by using the same array indices.
For immediate use, you can simply extract the texts array and use the translations in your application:
Copy
import requests# Your API authenticationheaders = { "x-api-key": "your-api-key", # Replace with your actual API key}# The run_id from your completed translation taskrun_id = 12345 # Replace with your actual run ID# Retrieve the translationsresponse = requests.get( f"https://client.camb.ai/apis/translation-result/{run_id}", headers=headers)# Check if the request was successfulresponse.raise_for_status()# Extract the translationsresult_data = response.json()translations = result_data["texts"]# Use the translations in your applicationfor i, translation in enumerate(translations): print(f"Translation {i+1}: {translation}")
For applications that need to show both original and translated text together, you can zip the arrays:
Copy
# Assuming you've stored your original textsoriginal_texts = [ "This is the first sentence to translate.", "Here is the second one.", "And finally, the third sentence."]# And you've retrieved the translations as shown abovetranslations = result_data["texts"]# Create parallel displayfor original, translated in zip(original_texts, translations): print("Original: " + original) print("Translated: " + translated) print("---")
For longer-term storage, you might want to save the translation results alongside their originals:
Copy
import sqlite3# Set up database connection (replace with your actual database logic)conn = sqlite3.connect("translations.db")cursor = conn.cursor()# Create table if it doesn't existcursor.execute("""CREATE TABLE IF NOT EXISTS translations ( id INTEGER PRIMARY KEY, original_text TEXT, translated_text TEXT, source_language INTEGER, target_language INTEGER, translation_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)""")# Insert translations into databasefor original, translated in zip(original_texts, translations): cursor.execute( "INSERT INTO translations (original_text, translated_text, source_language, target_language) VALUES (?, ?, ?, ?)", (original, translated, 1, 2) # Replace with your actual language codes )# Commit the changesconn.commit()conn.close()
When working with this endpoint, it’s important to handle potential error cases:
Invalid run_id: If the provided run_id doesn’t exist or has expired, the API will return an appropriate error message.
Expired Results: Translation results may be available for a limited time after completion. If too much time has passed, you may need to resubmit your translation request.
Network Issues: As with any API call, network connectivity problems can interrupt the retrieval process, so implementing retry logic can improve reliability.
A robust implementation might look like this:
Copy
import requestsimport timedef get_translation_result(run_id, api_key, max_retries=3, retry_delay=2): """ Retrieve translation results with retry logic for better reliability. Parameters: ----------- run_id : str The run identifier for the completed translation task api_key : str Your API authentication key max_retries : int Maximum number of retry attempts if the request fails retry_delay : int Initial delay between retries in seconds (doubles after each retry) Returns: -------- list Array of translated texts if successful, None otherwise """ headers = { "x-api-key": api_key, "Content-Type": "application/json" } url = f"https://client.camb.ai/apis/translation-result/{run_id}" # Initialize retry counter retries = 0 current_delay = retry_delay while retries <= max_retries: try: response = requests.get(url, headers=headers) # If successful, return the translations if response.status_code == 200: result_data = response.json() return result_data.get("texts", []) # If the run_id is invalid or results expired elif response.status_code == 404: print(f"Translation results not found for run_id: {run_id}") print("This could mean the run_id is invalid or the results have expired.") return None # If server error, retry after delay elif response.status_code >= 500: if retries < max_retries: print(f"Server error occurred. Retrying in {current_delay} seconds...") time.sleep(current_delay) current_delay *= 2 # Exponential backoff retries += 1 continue else: print("Maximum retries reached. Please try again later.") return None # Handle other errors else: print(f"Error retrieving translations: HTTP {response.status_code}") print(f"Response: {response.text}") return None except requests.exceptions.RequestException as e: if retries < max_retries: print(f"Connection error: {str(e)}. Retrying in {current_delay} seconds...") time.sleep(current_delay) current_delay *= 2 retries += 1 continue else: print(f"Connection error after {max_retries} retries: {str(e)}") return None return None
Use them in your application logic to enable multilingual functionality
The simplicity of the response format makes it easy to integrate translations wherever they’re needed in your workflow, whether you’re building a multilingual website, an educational app, or an international communication tool.
By understanding how to effectively use this endpoint, you can create smoothly functioning multilingual applications that deliver high-quality translations to your users at exactly the right moment in their journey.
The x-api-key is a custom header required for authenticating requests to our API. Include this header in your request with the appropriate API key value to securely access our endpoints. You can find your API key(s) in the 'API' section of our studio website.