Call and response: your first Bing Web Search query in Python

The Bing Web Search API provides an experience similar to Bing.com/Search by returning search results that Bing determines are relevant to the user's query. The results may include Web pages, images, videos, news, and entities, along with related search queries, spelling corrections, time zones, unit conversion, translations, and calculations. The kinds of results you get are based on their relevance and the tier of the Bing Search APIs to which you subscribe.

Refer to the API reference for technical details about the APIs.

You can run this example as a Jupyter notebook on MyBinder by clicking on the launch Binder badge:

Binder

Prerequisites

You must have a Cognitive Services API account with Bing Search APIs. The free trial is sufficient for this quickstart. You need the access key provided when you activate your free trial, or you may use a paid subscription key from your Azure dashboard.

Running the walkthrough

Set subscription_key to your API key for the Bing API service.

subscription_key = None
assert subscription_key

Next, verify that the search_url endpoint is correct. At this writing, only one endpoint is used for Bing search APIs. If you encounter authorization errors, double-check this value against the Bing search endpoint in your Azure dashboard.

search_url = "https://api.cognitive.microsoft.com/bing/v7.0/search"

Set search_term to query Bing for Microsoft Cognitive Services.

search_term = "Microsoft Cognitive Services"

The following block uses the requests library in Python to call out to the Bing search APIs and return the results as a JSON object. Observe that we pass in the API key via the headers dictionary and the search term via the params dictionary. To see the full list of options that can be used to filter search results, refer to the REST API documentation.

import requests

headers = {"Ocp-Apim-Subscription-Key" : subscription_key}
params  = {"q": search_term, "textDecorations":True, "textFormat":"HTML"}
response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()

The search_results object contains the search results along with rich metadata such as related queries and pages. The following lines of code format the top pages returned by the query.

from IPython.display import HTML

rows = "\n".join(["""<tr>
                       <td><a href=\"{0}\">{1}</a></td>
                       <td>{2}</td>
                     </tr>""".format(v["url"],v["name"],v["snippet"]) \
                  for v in search_results["webPages"]["value"]])
HTML("<table>{0}</table>".format(rows))

Next steps

See also

Bing Web Search overview
Try it
Get a free trial access key Bing Web Search API reference