0

I have these two strings:

client_id = "id_str"
client_secret = "secret_str"

And I must pass them like so:

def getToken(code, client_id, client_secret, redirect_uri):
    body = {
        "grant_type": 'authorization_code',
        "code" : code,
        "redirect_uri": redirect_uri,
        "client_id": client_id,
        "client_secret": client_secret
    }

    encoded = base64.b64encode("{}:{}".format(client_id, client_secret))
    headers = {"Content-Type" : HEADER, "Authorization" : "Basic {}".format(encoded)} 

    post = requests.post(SPOTIFY_URL_TOKEN, params=body, headers=headers)
    return handleToken(json.loads(post.text))

but when I do so I get the error:

    encoded = base64.b64encode("{}:{}".format(client_id, client_secret))
  File "/usr/local/lib/python3.7/base64.py", line 58, in b64encode
    encoded = binascii.b2a_base64(s, newline=False)
TypeError: a bytes-like object is required, not 'str'

How do I fix this encoding/formatting for Python 3.7?

ps: I don't see this answer adressing formatting {} as well as encoding.

8-Bit Borges
  • 9,643
  • 29
  • 101
  • 198

1 Answers1

2

Change the line

encoded = base64.b64encode("{}:{}".format(client_id, client_secret))

to

encoded = base64.b64encode("{}:{}".format(client_id, client_secret).encode())

According to the documentation:

base64.b64encode(s, altchars=None)

Encode the bytes-like object s using Base64 and return the encoded bytes.

Regarding your objection:

the linked answer does not address formatting

Actually your problem has nothing to do with formatting, because format() just returns a string, but b64encode requires a bytes-like object, not a string.

Community
  • 1
  • 1
jps
  • 20,041
  • 15
  • 75
  • 79