Azure / Azure/azure-sdk-for-python
azure.ai.translation.text Python SDK package returns authorization error
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 3.4k
- Avg merge
- 1d 21h
- Merged PRs (30d)
- 193
Description
- ** azure.ai.translation.text**:
- **1.0.1**:
- **Mac**:
- **3.13**:
**Describe the bug**
I get results from the AI Translation API when I call it from Postman or from Python using Requests. I followed instructions and code from this web page: https://learn.microsoft.com/en-us/python/api/overview/azure/ai-translation-text-readme?view=azure-python. I get and authorization error. I worked with CoPilot and tried a lot of alternatives, but couldn't get past the error.
**To Reproduce**
Steps to reproduce the behavior:
1.
Run this code supplied by ChatGPT - just add a valid Key from Azure
```python
from azure.ai.translation.text import TextTranslationClient
from azure.core.credentials import AzureKeyCredential
from azure.core.exceptions import HttpResponseError
# Replace with your key and endpoint
api_key = "API_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com/"
# Log the API key and endpoint to verify they are correct
print(f"API Key: {api_key}")
print(f"Endpoint: {endpoint}")
# Validate Endpoint URL
if not endpoint.startswith("https://") or not "cognitive.microsofttranslator.com" in endpoint:
print("Invalid endpoint URL. Please check the format and region.")
else:
print("Endpoint URL is valid.")
# Initialize the AzureKeyCredential and TextTranslationClient
try:
credential = AzureKeyCredential(api_key)
client = TextTranslationClient(endpoint=endpoint, credential=credential)
print("Client initialized successfully.")
except Exception as e:
print(f"Failed to initialize client: {e}")
# Function to check if the credential is valid
def is_credential_valid(credential):
try:
# Sample text to translate
text_to_translate = ["Hello, world!"]
target_language = "es"
# Construct the request body
body = [{"text": text} for text in text_to_translate]
# Call the translate method with the correct arguments
response = client.translate(body=body, to_language=[target_language])
# Print the translated text
for translation in response:
print(f"Translated text: {translation['translations'][0]['text']}")
return True
except HttpResponseError as e:
print(f"Error Code: {e.error.code}")
print(f"Message: {e.error.message}")
return False
except Exception as e:
print(f"An unexpected error occurred: {e}")
return False
# Check if the credential is valid
if is_credential_valid(credential):
print("Credential is valid.")
else:
print("Credential is invalid. Please check your API key and endpoint.")
```
**Expected behavior**
Hello World translated into Spanish
What I get (not including my key):
Endpoint: https://api.cognitive.microsofttranslator.com/
Endpoint URL is valid.
Client initialized successfully.
Error Code: 401001
Message: The request is not authorized because credentials are missing or invalid.
Credential is invalid. Please check your API key and endpoint.
Here is the code that works:
```python
import requests
import json
# Replace with your key and endpoint
api_key = "API_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0"
# Sample text to translate
text_to_translate = "Hello, world!"
target_language = "es"
# Construct the request headers and body
headers = {
"Ocp-Apim-Subscription-Key": api_key,
"Content-Type": "application/json",
"Ocp-Apim-Subscription-Region": "westus2" # Replace with your region, e.g., "westus"
}
body = [{
"text": text_to_translate
}]
# Make the request
response = requests.post(endpoint, headers=headers, json=body, params={"to": target_language})
# Check the response
if response.status_code == 200:
translations = response.json()
translated_text = translations[0]['translations'][0]['text']
print(f"Translated text: {translated_text}")
else:
print(f"Error Code: {response.status_code}")
print(f"Message: {response.text}")
```
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional context**
I don't think there's a problem with my key because the API runs when I use Python requests library or Postman to call the API.
```
Contributor guide
Assessment
This issue has not been assessed yet.