Search code examples
pythonpython-3.xazure-cognitive-services

Python AZ translate The request is not authorized because credentials are missing or invalid


I am using Python 3.8.3 and try to use Azure Translation. Based on the example of (https://learn.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


Solution

  • 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())
    }