1
votes

I am using Python 3.8.3 and try to use Azure Translation. Based on the example of (https://docs.microsoft.com/nl-nl/azure/cognitive-services/Translator/quickstart-translate?pivots=programming-language-python) I try to re-create the example for myself and minimized the code.

enter image description here

I create an Azure Resource (Translate) and copied the key and the endpoint in the code. But when I run the code, I get the following error:

"code": 401000,
"message": "The request is not authorized because credentials are missing or invalid."

Can someone please explain what i doing wrong and how to fix this issue!

I use this code:

import os, requests, uuid, json

path = '/translate?api-version=3.0'
params = '&to=de&to=it'
constructed_url = "https://api.cognitive.microsofttranslator.com" + path + params

headers = {
    'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxx',
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())
}

# You can pass more than one object in body.
body = [{
    'text' : 'Hello World!'
}]
request = requests.post(constructed_url, headers=headers, json=body)
response = request.json()

print(json.dumps(response, sort_keys=True, indent=4, separators=(',', ': ')))

Many thanks Erik

1
Could the error be that there is a // in the url between the base-URL and path?Hampus Larsson
What I mean is that it should maybe be this: "https://api.cognitive.microsofttranslator.com" + path + params It's a small change, but it would drastically change the path to the API.Hampus Larsson
Thanks for the fast reply! It does not mather for the response.Have you other ideas ?Erik hoeven
In the documentation you've linked it says this: If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. If that's what you're using, then you might have to provide that in the headers variable as well.Hampus Larsson
I use indeed "TextAnalytics", "Translator", "Cognitive Service" but what need i to fill in all the keys?Erik hoeven

1 Answers

3
votes

As per this doc, since you are using multiple services. It is a must to include the 2 authentication headers with your request.

Ocp-Apim-Subscription-Key   The value is the Azure secret key for your multi-service resource.

Ocp-Apim-Subscription-Region    The value is the region of the multi-service resource.

Location here is the specified Subscription Region.

Looking through your screenshot. It appears that region to be - westeurope

Updated Headers for your use case :

headers = {
    'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxx',
    'Ocp-Apim-Subscription-Region' : 'westeurope',
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())
}