Expected type to be one of bytes, bytearray but got str in Python

289 views Asked by At

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.

0

There are 0 answers