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