0

I am trying write a python script using requests package to use an online mongodb query service API hosted within the organization. The API expects the authorization header in the format 'websitename/username:Password' and using the basic authentication base64 encoding. I tried to create the GET request using the requests package which has the authorization header in the following format:

import requests

headers = {'Authorization': 'Basic %s' % 'Base64encoded 
websitename/username:Password string here'}

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

But I am getting a parse error here for the string as I think the expected string for header in requests package is in form of 'username:password' here and not the desired format i.e. 'websitename/username:password'.

Is there a way in which I could use the base64 encoded sting in the format which the service is expecting i.e. 'websitename/username:password' in requests package?

Any help is highly appreciated.

Thanks.

2 Answers 2

1

It sounds to me like you are getting a HTTP response error because the authorization header value you are passing is not base64 encoded. To correct this you can simply encode the string using the base64 python module:

Python 2.7 https://docs.python.org/2/library/base64.html

Python 3.5 https://docs.python.org/3.5/library/base64.html

An example would be something like this:

import base64
import requests

website = 'example.com'
username = 'root'
password = '1234'
auth_str = '%s/%s:%s' % (website, 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()
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot Jonny! This solved the problem that I was facing :)
Hi Jonny, What if the slash used in the auth_str string a backslash. I tried it, but it gives a error 'byte like object is required and not str'. Any workaround for this problem in your opinion?
@shripati007 Add this : auth_str = auth_str.encode("utf-8")
1
import base64
import requests

website = 'example.com'
username = 'root'
password = '1234'
auth_str = '%s/%s:%s' % (website, username, password)
b64_auth_str = base64.b64encode(auth_str.encode('ascii'))
headers = {'Authorization': 'Basic %s' % b64_auth_str}
content_res = requests.get(get_url, headers=headers).json()

2 Comments

Thanks for your answer, would you mind to add a little explanation of the code snippet above ? Have a nice day.
just added encode part, auth_str.encode(), had encounter this error during hashing part. hope it will help others.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.