Getting started overview
Integrating LibreTranslate involves a series of steps that begin with account creation and culminate in making your first successful API call. This guide provides a structured approach to quickly set up your environment, obtain necessary credentials, and execute a basic translation request. It covers both using the hosted LibreTranslate service and provides context for self-hosting where applicable.
The core process includes:
- Account Creation: Registering on the LibreTranslate platform to gain access to the hosted API.
- API Key Retrieval: Generating and securing your unique API key, which authenticates all your programmatic requests.
- Environment Setup: Preparing your development environment for making HTTP requests, often using a client library or a direct HTTP client.
- First API Call: Constructing and executing a translation request to the LibreTranslate API endpoint.
- Response Handling: Processing the API's response to extract the translated text.
For those considering self-hosting, the initial steps differ as you would deploy the LibreTranslate software on your own infrastructure rather than using the managed service. This guide focuses on the hosted API integration for immediate use, while acknowledging the self-hosted alternative for full control over data and privacy, as outlined in the LibreTranslate official documentation.
Quick Reference Table
| Step | What to do | Where |
|---|---|---|
| 1. Create Account | Register for a LibreTranslate account. | LibreTranslate Homepage |
| 2. Get API Key | Locate and copy your API key from your account dashboard. | LibreTranslate Account Settings (after login) |
| 3. Choose Integration Method | Decide between direct HTTP requests or a client library (Python, JS, etc.). | LibreTranslate API Reference |
| 4. Make First Request | Send a POST request to the /translate endpoint with text and language parameters. |
Your code editor/terminal |
| 5. Handle Response | Parse the JSON response to retrieve the translated text. | Your code editor |
Create an account and get keys
To begin using the LibreTranslate hosted API, you must first create an account. This process typically involves providing an email address and setting a password. Upon successful registration, you will gain access to a personal dashboard where your API key is generated and managed.
- Visit the LibreTranslate Website: Navigate to the LibreTranslate homepage.
- Sign Up/Register: Look for a 'Sign Up' or 'Register' button. Follow the prompts to create your account. This usually involves entering an email address and creating a secure password.
- Access Dashboard: Once registered and logged in, you will be directed to your user dashboard or account settings page.
- Locate API Key: Within your dashboard, there will be a section dedicated to API keys or credentials. Your unique API key will be displayed there. It is crucial to treat this key as sensitive information, similar to a password, to prevent unauthorized access to your account and usage.
- Copy Your API Key: Copy the generated API key. You will need to include this key in the headers or body of all your API requests to authenticate them.
LibreTranslate offers a free tier that allows up to 20,000 characters per month, which is sufficient for initial testing and development. For higher usage, paid plans are available, starting at $29 for 5 million characters per month.
Your first request
After obtaining your API key, you can make your first translation request. LibreTranslate's API is accessible via standard HTTP POST requests. The primary endpoint for translation is /translate. You will need to send the text to be translated, the source language, and the target language, along with your API key.
API Endpoint
POST https://libretranslate.com/translate
Request Parameters
The request body should be a JSON object with the following parameters:
q(string, required): The text to be translated.source(string, required): The language code of the input text (e.g.,enfor English).target(string, required): The language code for the desired output translation (e.g.,esfor Spanish).api_key(string, required): Your unique API key.format(string, optional): The format of the input text. Default istext. Other options might includehtml.alternatives(boolean, optional): Whether to return alternative translations. Default isfalse.
A comprehensive list of supported language codes can be found in the LibreTranslate API documentation.
Example: Python using requests library
This example demonstrates how to make a translation request using Python's popular requests library. First, ensure you have the library installed: pip install requests.
import requests
# Replace with your actual API key
API_KEY = "YOUR_LIBRETRANSLATE_API_KEY"
API_URL = "https://libretranslate.com/translate"
data = {
"q": "Hello, world!",
"source": "en",
"target": "es",
"api_key": API_KEY
}
try:
response = requests.post(API_URL, json=data)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
translation_result = response.json()
print(f"Translated text: {translation_result['translatedText']}")
except requests.exceptions.HTTPError as e:
print(f"HTTP error occurred: {e}")
print(f"Response content: {response.text}")
except requests.exceptions.ConnectionError as e:
print(f"Connection error occurred: {e}")
except requests.exceptions.Timeout as e:
print(f"Timeout error occurred: {e}")
except requests.exceptions.RequestException as e:
print(f"An unexpected error occurred: {e}")
Example: JavaScript using fetch API
This example uses the browser's native fetch API for making the request. In a Node.js environment, you might use a library like node-fetch or axios.
const API_KEY = "YOUR_LIBRETRANSLATE_API_KEY"; // Replace with your actual API key
const API_URL = "https://libretranslate.com/translate";
const data = {
q: "Hello, world!",
source: "en",
target: "es",
api_key: API_KEY
};
fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(translationResult => {
console.log(`Translated text: ${translationResult.translatedText}`);
})
.catch(error => {
console.error("Error during translation:", error);
});
Interpreting the Response
A successful response from the LibreTranslate API will typically be a JSON object containing the translated text. For example:
{
"translatedText": "¡Hola Mundo!"
}
The translatedText field holds the result of the translation. Error responses will include a status code and a message describing the issue.
Common next steps
Once you have successfully made your first translation request, consider these common next steps to further integrate and optimize your use of LibreTranslate:
- Explore SDKs: LibreTranslate offers community-contributed SDKs for various languages, including Python, JavaScript, PHP, Go, Rust, and Dart/Flutter. Using an SDK can simplify API interaction by abstracting HTTP request details and handling common patterns. Refer to the LibreTranslate documentation for available client libraries and usage examples.
- Error Handling: Implement robust error handling in your application. The API can return various HTTP status codes (e.g., 400 for bad request, 401 for unauthorized, 429 for rate limit exceeded, 500 for internal server error). Your code should gracefully manage these scenarios to provide a smooth user experience. For general API error handling principles, consult resources like the Mozilla Developer Network HTTP status codes guide.
- Language Detection: Before translating, you might need to detect the source language if it's unknown. LibreTranslate's API typically includes a language detection endpoint (e.g.,
/detect) that can identify the language of a given text. This helps ensure accurate translations by providing the correctsourceparameter. - Batch Translation: For translating multiple texts efficiently, investigate if the API supports batch translation or how to effectively queue and process multiple individual requests without hitting rate limits.
- Rate Limits and Quotas: Familiarize yourself with the API's rate limits and your account's character quotas. Design your application to respect these limits to avoid service interruptions. Information on limits is usually found on the pricing page or within the API documentation.
- Self-Hosting Considerations: If privacy, data control, or high-volume translation without external service dependencies are critical, explore the option of self-hosting LibreTranslate. This involves deploying the software on your own servers, offering complete control over the translation environment.
- Security Best Practices: Always keep your API key secure. Do not hardcode it directly into client-side code or commit it to public repositories. Use environment variables or secure configuration management systems.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting tips for LibreTranslate:
401 UnauthorizedError:- Incorrect API Key: Double-check that you have copied your API key correctly from your LibreTranslate dashboard. Ensure there are no leading or trailing spaces.
- Missing API Key: Verify that the
api_keyparameter is included in your request body as required by the API. - Expired/Revoked Key: Confirm your API key is still active in your LibreTranslate account settings.
400 Bad RequestError:- Missing Parameters: Ensure all required parameters (
q,source,target,api_key) are present in your request. - Invalid Language Codes: Check that the
sourceandtargetlanguage codes are valid and supported by LibreTranslate. Refer to the LibreTranslate API reference for a list of supported codes. - Incorrect JSON Format: Verify that your request body is valid JSON. Use a JSON linter or validator if unsure.
- Content-Type Header: Ensure your request includes the
Content-Type: application/jsonheader.
- Missing Parameters: Ensure all required parameters (
429 Too Many RequestsError:- Rate Limit Exceeded: You may have sent too many requests in a short period. Wait and try again. Implement exponential backoff in your retry logic for production applications.
- Free Tier Limit: If on the free tier, you might have exceeded your monthly character limit (20,000 characters). Check your usage in your account dashboard or consider upgrading your plan on the LibreTranslate pricing page.
5xx Server Error:- These errors indicate an issue on the LibreTranslate server side. These are less common but can occur. If you encounter a 5xx error, it's best to wait and retry the request. If the problem persists, check the LibreTranslate documentation or status page for any service announcements.
- Network Issues:
- Connectivity: Ensure your machine has an active internet connection and can reach
https://libretranslate.com. - Firewall/Proxy: Check if a firewall or proxy server is blocking your outgoing requests.
- Connectivity: Ensure your machine has an active internet connection and can reach
- SDK Specific Issues:
- If using an SDK, ensure it is installed correctly and you are using the correct version. Consult the specific SDK documentation for usage examples and common pitfalls.