Urllib2.HTTPError: HTTP 401 error when requesting using the new Bing API (in the azure market)

So, I made corrections based on most of the answers under one roof in the stack overflow, I still can not solve this problem.

queryBingFor = "Google Fibre"
quoted_query = urllib.quote(queryBingFor)
account_key = "dslfkslkdfhsehwekhrwkj2187iwekjfkwej3"

rootURL = "https://api.datamarket.azure.com/Bing/Search/v1/"
searchURL = rootURL + "Image?format=json&Query=" + quoted_query
cred = base64.encodestring(accountKey)

reqBing = urllib2.Request(url=searchURL)
author = "Basic %s" % cred
reqBing.add_header('Authorization',author)

readURL = urllib2.urlopen(reqBing)

I know that I am missing something in the above code, which gives me:

urllib2.HTTPError: HTTP Error 401: The authorization type you provided is not supported.  Only Basic and OAuth are supported

Is there any clue on what might be the problem?

Thank!

+4
source share
1 answer

So here is the working code. The problem I created is the query keyword format.

 queryBingFor = "'google fibre'" # the apostrophe required as that is the format the API Url expects. 
 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()

This should produce results in the appropriate JSON format. As I use urllib2 httpbasicauthhandler, the password converted to base64 is implicit, I suppose.

+3
source

All Articles