Search code examples
azureazure-cognitive-servicesmicrosoft-translator

How to use azure translator with authorization token?


I want to use azure translator service with the Authorization token. There are plenty of resources explaining how to do it with subscription key but I could not found any resource explaining the use of authorization token. I can get the authorization token but when I send a request with it, the response status code is 401. This is how I send the request:

curl POST 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer token' \
--data-raw '[{'\''Text'\'':'\''Hello World!'\''}]'

Solution

  • If you want to call Text Translation API with authentication token, please refer to the following steps

    1. Get a token. If your service is global, the endpoint is https://api.cognitive.microsoft.com/sts/v1.0/issueToken
    curl -v -X POST \
    "https://YOUR-REGION.api.cognitive.microsoft.com/sts/v1.0/issueToken" \
    -H "Content-type: application/x-www-form-urlencoded" \
    -H "Content-length: 0" \
    -H "Ocp-Apim-Subscription-Key: YOUR_SUBSCRIPTION_KEY"
    

    Besides, please note that an authentication token is valid for 10 minutes. The token should be reused when making multiple calls to the Translator. However, if your program makes requests to the Translator over an extended period of time, then your program must request a new access token at regular intervals (for example, every 8 minutes).

    1. Call API
    curl -X POST 'https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&from=en&to=de' \
    -H 'Authorization: Bearer YOUR_AUTH_TOKEN' \
    -H 'Content-Type: application/json' \
    --data-raw '[{ "text": "How much for the cup of coffee?" }]' | json_pp
    

    enter image description here enter image description here

    For more details, please refer to here and here.