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.

4
  • Try binascii.b2a_base64(s.encode(), newline=False) Commented Mar 15, 2020 at 2:31
  • Does this answer your question? Why do I need 'b' to encode a string with Base64? Commented Mar 15, 2020 at 2:35
  • the linked answer does not address formatting. Commented Mar 15, 2020 at 2:39
  • @ Александр some error is thrown Commented Mar 15, 2020 at 4:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.