HTTPError: HTTP Error 401: basic auth failed. Bing Search
Question: I have made a code to get urls from bing search. It gives the error mentioned
above.

    
    
    import urllib
    import urllib2
    accountKey = 'mykey'
    username =accountKey
    queryBingFor = "'JohnDalton'"
    quoted_query = urllib.quote(queryBingFor)
    
    rootURL = "https://api.datamarket.azure.com/Bing/Search/"
    searchURL = rootURL + "Image?$format=json&Query=" + quoted_query
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_mgr.add_password(None, searchURL,username,accountKey)
    
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    opener = urllib2.build_opener(handler)
    urllib2.install_opener(opener)
    readURL = urllib2.urlopen(searchURL).read()
    

I have made the username = authKey as someone told me it has to be same for
both. Anyways, i didn't get a username when i made the bing webmaster account.
Or is it just my email. Excuse me if i have made novice mistakes. I've just
started Python.


Answer: In the absence of any other information, it seems unlikely that what is
effectively your username and password would be the same thing if this site
actually needs this form of authorisation.

Are you able to make it work by doing a request in your browser like the
following?

<https://mykey:mykey@api.datamarket.azure.com/Bing/Search/Image>?$format=json&Query=blah

If so then at lerast it sounds like the credentials are right and that its the
way you are using them in python that's wrong, but more likely the above will
fail with the same error, suggesting the credentials themselves are not valid.

Also see this question, which suggests there may be a problem is the site
doesn't do 'standard' auth: [urllib2 HTTPPasswordMgr not working - Credentials
not sent
error](http://stackoverflow.com/questions/9495279/urllib2-httppasswordmgr-not-
working-credentials-not-sent-error)

It also suggests that you might need to pass the top level URL of the site tot
he password manager rather than the specific search URL.

Finally, it might be worth adapting this code:
<http://www.voidspace.org.uk/python/articles/authentication.shtml>

for your site to check the auth realm and scheme the site is sending you to
check they're supported.

