@steve corman Welcome to Microsoft Q&A Forum, Thank you for posting your query here!
.
I was able to achieve this via the Translate REST API by sending custom id like below:
{"id": 1, "text": "Hello, world!"}, {"id": 2, "text": "Good morning!"}
I am sharing the below Python code if that helps:
import requests
import json
# Define your subscription key and region
subscription_key = 'a4b6a7XXXXXXXXXXXdec50'
region = 'eastus'
# Define the endpoint URL
endpoint = 'https://api.cognitive.microsofttranslator.com/translate'
params = {
'api-version': '3.0',
'to': 'de'
}
# Define the headers
headers = {
'Ocp-Apim-Subscription-Key': subscription_key,
'Ocp-Apim-Subscription-Region': region,
'Content-Type': 'application/json'
}
# Define your translation requests with custom IDs
translation_requests = [
{"id": 1, "text": "Hello, world!"},
{"id": 2, "text": "Good morning!"}
]
# Extract the texts to be translated
texts = [{"text": req["text"]} for req in translation_requests]
# Make the POST request
response = requests.post(endpoint, params=params, headers=headers, data=json.dumps(texts))
# Check if the request was successful
if response.status_code == 200:
translations = response.json()
# Add the IDs back to the translations based on the order of the requests
for i, translated_text in enumerate(translations):
translated_text['id'] = translation_requests[i]['id']
print(json.dumps(translations, indent=4))
else:
print(f"Error: {response.status_code}")
print(response.text)
.
I received response like below:
[
{
"detectedLanguage": {
"language": "en",
"score": 1.0
},
"translations": [
{
"text": "Hallo Welt!",
"to": "de"
}
],
"id": 1
},
{
"detectedLanguage": {
"language": "en",
"score": 1.0
},
"translations": [
{
"text": "Guten Morgen!",
"to": "de"
"id": 2
}
]
By using the above approach, you can ensure that the translated texts are correctly associated with their corresponding records in your database, even if the API itself doesn't support custom fields directly in the request and response.
.
Hope this helps. If you have any follow-up questions, please let me know. I would be happy to help.