MIcrosoft translator API is not working

arpit.malviya 1 Reputation point
2021-11-30T19:20:27.993+00:00

Hi team,

We are using microsoft azure services and we have created a resource to translate the text api with the following end point:
For this api end point: "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=fr"
We are getting error "{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}"
We have passed the following in the headers:
Ocp-Apim-Subscription-Key
Ocp-Apim-Subscription-Region
Content-Type

Azure AI services
Azure AI services
A group of Azure services, SDKs, and APIs designed to make apps more intelligent, engaging, and discoverable.
3,602 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. romungi-MSFT 48,906 Reputation points Microsoft Employee Moderator
    2021-12-01T07:55:48.713+00:00

    @arpit.malviya Based on the error message are you using the correct keys of Azure translator resource? How are you passing the keys in the header?
    Please try this script in python by replacing your key values from the translator resource.

    import requests, uuid, json  
      
    # Add your subscription key and endpoint  
    subscription_key = "replace_your_key"  
    endpoint = "https://api.cognitive.microsofttranslator.com"  
      
    # Add your location, also known as region. The default is global.  
    # This is required if using a Cognitive Services resource.  
    location = "global"  
      
    path = '/translate'  
    constructed_url = endpoint + path  
      
    params = {  
        'api-version': '3.0',  
        'from': 'en',  
        'to': ['de', 'it']  
    }  
    constructed_url = endpoint + path  
      
    headers = {  
        'Ocp-Apim-Subscription-Key': subscription_key,  
        'Ocp-Apim-Subscription-Region': location,  
        '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, params=params, headers=headers, json=body)  
    response = request.json()  
      
    print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))  
    

    This script should print the following response:

    153949-image.png

    If an answer is helpful, please click on 130616-image.png or upvote 130671-image.png which might help other community members reading this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.