question

PremTiwari-7131 avatar image
0 Votes"
PremTiwari-7131 asked YutongTie-MSFT commented

JSON decoder error for REST API call to Microsoft Translator



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=(',', ':')))


[1]: /answers/storage/attachments/141842-showing-error.png



azure-translator
showing-error.png (126.1 KiB)
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hello,

Hope you have solved your issue ^^ Please let us know if you are still blocked by this.

Regards,
Yutong

0 Votes 0 ·

I will give you answer in a week !

0 Votes 0 ·

1 Answer

YutongTie-MSFT avatar image
0 Votes"
YutongTie-MSFT answered YutongTie-MSFT commented

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



result1.jpg (47.7 KiB)
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

It works as a function, but when it is designed as part of a CLASS it does not seems to work !! Still having the same issues

0 Votes 0 ·

@PremTiwari-7131 In this situation I will suggest you to raise a support ticket to deeper debug your code. Please let me know if you have no support plan, I can enable you a free ticket for this issue.

Regards,
Yutong

0 Votes 0 ·

@YutongTie-MSFT , It worked. Your answer was definitely very helpful :) You can close the issue now.

0 Votes 0 ·
Show more comments