'TypeError about needing 'bytes' not 'str' in Python

I'm attempting to use the Backblaze B2 API to eventually iterate through some .ai files I have there, but the code that Backblaze provides in their documentation is giving me an error.

Here's the code

import base64
import json
import urllib3

id_and_key = 'applicationKeyId_value:applicationKey_value'
basic_auth_string = 'Basic ' + base64.b64encode(id_and_key)
headers = { 'Authorization': basic_auth_string }

request = urllib3.Request(
    'https://api.backblazeb2.com/b2api/v2/b2_authorize_account',
    headers = headers
    )
response = urllib3.urlopen(request)
response_data = json.loads(response.read())
response.close()

When I ran the code (replacing the id_and_key with my master key ID which looked something like '6b5*********') I got an error that looked like this

Traceback (most recent call last):
  File "/Users/jacobpatty/vscode_projects/badger_colors/backblaze_test.py", line 6, in <module>
    basic_auth_string = base64.b64encode(id_and_key)
  File "/opt/homebrew/Cellar/[email protected]/3.9.12/Frameworks/Python.framework/Versions/3.9/lib/python3.9/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

I looked at the base64 documentation, but I couldn't find any useful info there. Or is it possible it has something to do with urllib3? Anyone know why I'm getting this error, or how to fix it?



Solution 1:[1]

Perhaps-confusingly, you need to .encode() the input to .b64encode()!

>>> import base64
>>> base64.b64encode("my input")
[clipped]
TypeError: a bytes-like object is required, not 'str'
>>> base64.b64encode("my input".encode())
b'bXkgaW5wdXQ='

Specifically for your auth header, you can do this all at once without bothering with the intermediate names

request = urllib3.Request(
    'https://api.backblazeb2.com/b2api/v2/b2_authorize_account',
    headers={
        "Authorization": f"Basic {base64.b64encode((f'{app_id}:{app_key}').encode()).decode()}"
    }
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1