This quickstart guide will walk you through the process of setting up and using the Azure Translator service to translate text programmatically. Translator is part of Azure Cognitive Services.
Navigate to the Azure portal.
Click Create a resource.
In the search bar, type "Translator" and select the Translator service.
Click Create.
Fill in the required fields:
Click Review + create, then Create.
Once the Translator resource is deployed, go to the resource.
Under Resource Management, select Keys and Endpoint.
You will find your Key1, Key2, and the Endpoint URL. Keep these secure, as they are required to authenticate your API calls.
We will now use cURL to demonstrate a simple text translation. You can adapt this to any programming language that supports HTTP requests.
This example translates the text "Hello, world!" from English to Spanish.
curl -X POST "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=es" \
-H "Ocp-Apim-Subscription-Key: YOUR_TRANSLATOR_KEY" \
-H "Content-Type: application/json" \
-d '[{"Text": "Hello, world!"}]'
Replace:
YOUR_TRANSLATOR_KEY with one of your actual subscription keys.The response will be a JSON array containing the translated text:
[
{
"translations": [
{
"text": "¡Hola Mundo!",
"to": "es"
}
]
}
]
Here's how you might approach this in common languages:
requests)import requests
import json
key = "YOUR_TRANSLATOR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com/"
path = "/translate?api-version=3.0&from=en&to=es"
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'from': 'en',
'to': 'es'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/json'
}
body = json.dumps([{'Text': 'Hello, world!'}])
response = requests.post(constructed_url, params=params, headers=headers, data=body)
response.raise_for_status()
result = response.json()
print(json.dumps(result, indent=4, ensure_ascii=False))
fetch)const key = "YOUR_TRANSLATOR_KEY";
const endpoint = "https://api.cognitive.microsofttranslator.com/";
const path = "/translate?api-version=3.0&from=en&to=es";
const translate = async () => {
const response = await fetch(endpoint + path, {
method: 'POST',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Content-Type': 'application/json'
},
body: JSON.stringify([{'Text': 'Hello, world!'}])
});
const result = await response.json();
console.log(JSON.stringify(result, null, 4));
};
translate();