JSON decoder error for REST API call to Microsoft Translator

Prem Tiwari 21 Reputation points
2021-10-19T14:44:50.273+00:00

Hello Techies,

I am having a problem with the "response" from request API for Microsoft Translator resource Group. I am getting a JSON decoder error and I can not figure out what is the error and why is it so?

I shall write the code here and also enclose an image showing the outcome.

import requests  
import logging  
import sys  
import os, uuid  
from attr import attrs, attrib  
from dotenv import load_dotenv  
load_dotenv()  
from constants import MICROSOFT_CODES_TO_LANGUAGES  
from exceptions import ServerException  
  
  
  
# few global variables  
params = {  
    'api-version': '3.0',  
    'to': ['en']  
}  
  
BASE_URL = os.getenv('END_POINT')  
  
  
class MicrosoftTranslator(object):  
    """  
    It is a class that wraps functions, and makes call to MICROSOFT Cognitive SERVICES under the hood  
    to do the translation  
    """  
    def __init__(self, secret_api_key = None, location = None, source = None, target_language = 'en', **kwargs):  
        """  
  
        :param secret_api_key: required microsoft api key  
        :param location: required datacenter of microsoft to which call is made  
        :param source:  
        :param target_language: required  
        :param proxies:  
        :param kwargs:  
        """  
        if not secret_api_key:  
            raise ServerException(401)  
        else:  
            self.secret_api_key = secret_api_key  
  
        if not location:  
            raise ServerException(1017)  
        else:  
            self.location = location  
  
        self.headers = {  
            'Ocp-Apim-Subscription-Key': self.secret_api_key,  
            'Ocp-Apim-Subscription-Region':self.location,  
            'Content-type': 'application/json'  
            # 'Accept': 'applicaton/jwt'  
            # 'X-ClientTraceId': str(uuid.uuid4())  
        }  
  
        if not target_language:  
            raise ServerException(1018)  
        elif type(target_language) is not str:  
            raise ServerException(1018)  
        elif len(target_language) != 2:  
            raise ServerException(1018)  
        else:  
            self.target_language = target_language  
  
        # set the params for constructing the url  
        self.url_params = {  
            'api-version': '3.0',  
            'to': self.target_language  
        }  
  
        self.__base_url = os.getenv('END_POINT')  
  
  
    def constructed_url(self):  
        import json  
        print(self.__base_url)  
        body = [{  
            'text': 'Mien name ist wichtiger als dein name.'  
        }]  
  
        request = requests.post(self.__base_url, params=self.url_params, headers=self.headers, json=body)  
        response = request.json()  
        print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ':')))  
Azure AI Translator
Azure AI Translator
An Azure service to easily conduct machine translation with a simple REST API call.
484 questions
{count} votes

Accepted answer
  1. YutongTie-MSFT 53,966 Reputation points Moderator
    2021-10-20T01:46:05.287+00:00

    Hello,

    It seems like you have some JSON issue like you try to parse something which Python think is byte stream not a simple string. In order to parse this, you need to convert it into a string first.

    Below is my sample code working for me.

    141935-result1.jpg

    import requests, uuid, json  
      
    # Add your subscription key and endpoint  
    subscription_key = "9d71*****************5ea"  
    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 = "westus2"  
      
    path = '/translate'  
    constructed_url = endpoint + path  
      
    params = {  
        'api-version': '3.0',  
        'to': ['en']  
    }  
    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': 'Mien name ist wichtiger als dein name.'  
    }]  
      
    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=(',', ': ')))  
    

    Thanks.

    Regards,
    Yutong


0 additional answers

Sort by: Most helpful

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.