0

I have a problem when i want to send JSON data with a post request python API (Python 3.9). I have a list of string dictionaries that i convert to JSON using json.loads() method but it returns an error :

Traceback (most recent call last):
  File "/product/tedh/environment/callminer_py3/lib/python3.9/site-packages/requests/models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "/product/tedh/environment/callminer_py3/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/product/tedh/environment/callminer_py3/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/product/tedh/environment/callminer_py3/lib/python3.9/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

My code :

consumer_identifiers = bytes(f"{CONSUMER_USERNAME}:{CONSUMER_PASSWORD}", encoding='utf-8')
        headers: requests.structures.CaseInsensitiveDict = CaseInsensitiveDict()
        headers["Basic-Authorization"] = f"Basic {b64encode(consumer_identifiers).decode('ascii')}"
        headers["Authorization"] = f"Bearer {self.__token['access_token']}"
        metadata_body_list = self.__fill_metadata()
        logger.info("Start send metadata to Callminer...")
        logger.info(f"The number of metadata sent is : {len(metadata_body_list)}")
        assert METADATA_INGESTION_URL is not None
        for metadata_body in metadata_body_list:
            json_metadata_body = json.loads(metadata_body)
            try:
                response = requests.post(METADATA_INGESTION_URL, headers=headers, json=json_metadata_body)
                if response.json():
                    if "CorrelationId" in response.json() and "MiningId" in response.json() and \
                            response.json()["CorrelationId"] in metadata_body:
                        logger.debug(f"Response POST request {response.json()}")
                    else:
                        raise RuntimeError(
                            f"Error occurred when sending metadata to Callminer.\n Response: {response.json()}.")
            except requests.exceptions.HTTPError as e:
                raise RuntimeError(f"Error: {str(e)}")
        logger.info("End of sending metadata.")

When i print the json, i see that it's correct:

{'Metadata': [{'Key': 'udf_text_14', 'Value': 'ACTIF'}, {'Key': 'udf_text_16', 'Value': 'F2K-140 Go 5G'}, {'Key': 'udf_text_17', 'Value': 'None'}, {'Key': 'udf_text_18', 'Value': 'None'}, {'Key': 'udf_text_23', 'Value': '2019-01-15 10:12:21'}, {'Key': 'udf_text_19', 'Value': 'NON'}, {'Key': 'udf_text_21', 'Value': 'OUI'}, {'Key': 'udf_text_20', 'Value': 'NON'}, {'Key': 'udf_text_22', 'Value': 'None'}], 'SourceId': 'SFRALLO', 'Correlationid': '78293941'}
LilyAZ
  • 133
  • 3
  • 10
  • JSON requires double quotes for strings, you have single quotes. Possible duplicate: https://stackoverflow.com/questions/4162642/single-vs-double-quotes-in-json – Tzane Jun 09 '22 at 12:50
  • Thanks for your help @Tzane. But then why did the others json's pass without error? – LilyAZ Jun 09 '22 at 12:56
  • Im not sure what you mean by "other jsons", but simple answer would be that they were correct :P If you doubt that it's not about the double quotes, try comparing the valid and invalid json to see if it could be something else. – Tzane Jun 09 '22 at 13:21

1 Answers1

1

I finally found the cause of my problem, it's the token expiration, my token expires after 1h and my request takes much longer because i have too much JSON to send, I re-generate it before the expiration time.

LilyAZ
  • 133
  • 3
  • 10