Python urllib2 basic authentication


Hi i'm trying to use python to access an API URL using urllib2:

import urllib2

url = ''

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
pagehandle = urllib2.urlopen(url)

I don't know what the realm is but am assuming I can use default i.e. None.

Anyway, i am still get 401 error:

Traceback (most recent call last): File "", line 12, in

pagehandle = urllib2.urlopen(url) File "/usr/lib/python2.6/", line 126, in urlopen
return, data, timeout) File "/usr/lib/python2.6/", line 397, in open
response = meth(req, response) File "/usr/lib/python2.6/", line 510, in http_response
'http', request, response, code, msg, hdrs) File "/usr/lib/python2.6/", line 435, in error
return self._call_chain(*args) File "/usr/lib/python2.6/", line 369, in _call_chain
result = func(*args) File "/usr/lib/python2.6/", line 518, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized

so it seems there is something wrong with the authentication. Is it most likely the use of realm = None?


Best Solution

I could not figure out why this method did not work but I was successful in calling the API using this code:

base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

request = urllib2.Request(url)

request.add_header("Authorization", "Basic %s" % base64string) 

result = urllib2.urlopen(request)
        data =