How to use Azure Translator API
Quick answer
Use the Azure Translator API by sending HTTP POST requests to the Azure endpoint with your subscription key in headers and the text to translate in JSON format. In Python, use the requests library to call the API endpoint /translate with parameters like to for target language and parse the JSON response for the translated text.
PREREQUISITES
Python 3.8+Azure Translator subscription key and endpointpip install requests
Setup
Install the requests library for HTTP calls and set environment variables for your Azure Translator subscription key and endpoint URL.
- Get your Azure Translator key and endpoint from the Azure Portal.
- Set environment variables
AZURE_TRANSLATOR_KEYandAZURE_TRANSLATOR_ENDPOINT. - Install
requestswithpip install requests.
pip install requests output
Collecting requests Downloading requests-2.31.0-py3-none-any.whl (62 kB) Installing collected packages: requests Successfully installed requests-2.31.0
Step by step
This example shows how to translate English text to Spanish using the Azure Translator API with Python.
import os
import requests
import uuid
def translate_text(text, to_language="es"):
key = os.environ["AZURE_TRANSLATOR_KEY"]
endpoint = os.environ["AZURE_TRANSLATOR_ENDPOINT"]
path = "/translate"
constructed_url = endpoint + path
params = {
"api-version": "3.0",
"to": to_language
}
headers = {
"Ocp-Apim-Subscription-Key": key,
"Ocp-Apim-Subscription-Region": "global",
"Content-type": "application/json",
"X-ClientTraceId": str(uuid.uuid4())
}
body = [{"Text": text}]
response = requests.post(constructed_url, params=params, headers=headers, json=body)
response.raise_for_status()
result = response.json()
return result[0]["translations"][0]["text"]
if __name__ == "__main__":
translated = translate_text("Hello, how are you?", "es")
print(f"Translated text: {translated}") output
Translated text: Hola, ¿cómo estás?
Common variations
You can translate to multiple languages by passing a list to the to parameter. For async calls, use httpx or aiohttp. The API supports other features like language detection and transliteration.
import os
import httpx
import uuid
async def translate_text_async(text, to_languages=["fr", "de"]):
key = os.environ["AZURE_TRANSLATOR_KEY"]
endpoint = os.environ["AZURE_TRANSLATOR_ENDPOINT"]
path = "/translate"
url = endpoint + path
params = {
"api-version": "3.0",
"to": to_languages
}
headers = {
"Ocp-Apim-Subscription-Key": key,
"Ocp-Apim-Subscription-Region": "global",
"Content-type": "application/json",
"X-ClientTraceId": str(uuid.uuid4())
}
body = [{"Text": text}]
async with httpx.AsyncClient() as client:
response = await client.post(url, params=params, headers=headers, json=body)
response.raise_for_status()
result = response.json()
return {t["to"]: t["text"] for t in result[0]["translations"]}
# Usage example for async (run with asyncio):
# import asyncio
# translations = asyncio.run(translate_text_async("Good morning"))
# print(translations) output
Async example output:
{'fr': 'Bonjour', 'de': 'Guten Morgen'} Troubleshooting
- If you get a 401 Unauthorized error, verify your subscription key and region.
- Ensure the endpoint URL ends with a trailing slash or no trailing slash consistently.
- Check your network connectivity and firewall settings if requests time out.
- Use
response.raise_for_status()to catch HTTP errors and inspectresponse.textfor details.
Key Takeaways
- Use the Azure Translator REST API with HTTP POST and JSON payloads for translation.
- Set your subscription key and endpoint as environment variables for secure access.
- The API supports multiple target languages and async HTTP clients for scalability.