shripati007
shripati007

Reputation: 87

Authorization header in Requests package in python

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.

Upvotes: 0

Views: 22292

Answers (2)

Christopher Gamella
Christopher Gamella

Reputation: 21

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()

Upvotes: 1

Jonny Morrill
Jonny Morrill

Reputation: 517

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()

Upvotes: 1

Related Questions