Basic Authentication in Python urllib2

Yesterday I’m playing around with github api with urllib and found a problem to perform basic authentication when I sent request to API. I’m not using requests because too lazy to install third party dependency. 😀

Here is it..

import urllib2
import base64

request = urllib2.Request("https://api.github.com/user/starred")
credential = base64.encodestring('{user}:{pwd}'.format(user=username, pwd=password)).replace('\n', '')
request.add_header('Authorization', 'Basic {credential}'.format(credential=credential))   
result = urllib2.urlopen(request)

Reference: http://stackoverflow.com/a/2955687/1936697

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s