1

I need to fetch data from Inhouse API where credentials need to encoded using base64.

import base64
import requests

username = 'root'
password = '1234'
auth_str = '%s:%s' % (username, password)
b64_auth_str = base64.b64encode(auth_str)

headers = {'Authorization': 'Basic %s' % b64_auth_str}

#content_res = requests.get(get_url, headers=headers).json()

Above is my code. This throws up error on line where encoding username and password.

TypeError: a bytes-like object is required, not 'str'

Any work around?

3 Answers3

0

b64encode only accepts a bytes-like object, so you need to encode your string into bytes:

b64_auth_str = base64.b64encode(auth_str.encode('utf-8'))

Also see this answer.

xjcl
  • 12,848
  • 6
  • 67
  • 89
0

You have to encode the string into bytes:

b64_auth_str = base64.b64encode(auth_str.encode('utf-8'))

zgottch
  • 36
  • 4
0

As You mentioned your error says that the argument which you are passing b64_auth_str = base64.b64encode(auth_str) in this case auth_str should be a Byte like object not a str (string)

so to solve that problem just use .encode() function which is inbuilt in Python3 and when no argument is passed it's converts the string to byte object so you should do this:

b64_auth_str = base64.b64encode(auth_str.encode('utf-8'))

Or You Can Do This:

b64_auth_str = base64.b64encode(auth_str.encode()) Both Work Fine And when printing the b64_auth_str The Output is b'cm9vdDoxMjM0'

I Hope This Worked, Jai Hind Jai Bharat

Aditya
  • 1,132
  • 1
  • 9
  • 28