Wednesday, September 5, 2012

Use Python to Access (Windows Azure) Bing Search API

As discussed in previous post, Microsoft had updated its Bing Search API and integrate it into the Windows Azure Marketplace.  But how to access the Search API in your web apps? In this doc, there are examples in Visual Basic and PHP. However, what if you like to use Python? There are a few guides on the Internet about Python wrapper on  Bing Search API, but many of them are out-dated (they are for old APIs). For the rest that work, many of them require you to install certain package, which is annoying sometimes. Actually, the python code to access Bing Search API is quite simple and the key is to do authentication.

The following shows an example:
import urllib2

# create credential for authentication
user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; FDM; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322)'
key= 'YOUR ACCOUNT KEY'
creds = (':%s' % key).encode('base64')[:-1]
auth = 'Basic %s' % creds

request = urllib2.Request('https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=%27test%27&$top=5&$format=json')
request.add_header('Authorization', auth)
request.add_header('User-Agent', user_agent)

requestor = urllib2.build_opener()
result = requestor.open(request) 
print result.read()

Here, 'key' is your Account key in Windows Azure. You can find it here. You can replace the url used in urllib2.Request() to search what you want.

No comments:

Post a Comment