0

I'm having the small Python problem. I'm not used to this Python coding so my mistake might be silly one. I'm trying to call API using the Python requests module.

Here I tried 2 methods but both showing different errors. So now, I'm getting any of them.

Code:

import requests
import base64

def api_call():
    filepath = 'File_Path'
    fileData = open(filepath, mode='rb');
    base64String = base64.b64encode(fileData.read());

    filename = filepath.split("/")[-1];

    payload = {
        "archive_data": base64String.decode('utf-8'), # Method 1
        # "archive_data": base64.b64decode(base64String), # Method 2
        "archive_name": filename
    }

    headers = {
        "Access_key": "ABC"
    }

    url = get_from_env(URL);

    response = requests.post(url, headers=headers, json=payload);
    jsonResponse = response.json();
    print(jsonResponse);

api_call();

Method 1 Output:

{'code': 400, 'msg': 'Validation Failure', 'hydra_error': 1, 'relying_party_error': 0, 'validations': {'archive_data': 'Expected type to be one of `bytes, bytearray` but got `str`.'}}

Method 2 Output:

TypeError: Object of type bytes is not JSON serializable

Appreciate you time and efforts in advance.

Jay Bhajiyawala
  • 101
  • 1
  • 4
  • 11
  • Well, for method 2, it is normal that it fails. bytes are not JSON serializable and then need to be decoded into a string first. However, the path of method 1 seems to be correct. The error is sent by the server. How do they mention sending "bytes" in a json payload? – Fnaxiom Oct 20 '22 at 14:18
  • Actually API's body parameters should be, **achieve_data** which suppose to be binary(Binary data of file). Seems like code sending the appropriate data for method 1. But I'm new so can't say that surely that. Any method fir decoding string? – Jay Bhajiyawala Oct 21 '22 at 06:31

0 Answers0