Quickstart: Use Python to call the Bing Web Search API

Get a Cognitive Services access key under Search. See also Cognitive Services Pricing - Bing Search API.

Use this quickstart to make your first call to the Bing Web Search API and receive a JSON response in less than 10 minutes.

This quickstart requires an Azure Cognitive Services account with Bing Search APIs. If you don't have an account, you can use the free trial to get a subscription key.

See also Cognitive Services Pricing - Bing Search API.

This example is run as a Jupyter notebook on MyBinder. Click the launch Binder badge:

Binder

Define variables

Replace the subscription_key value with a valid subscription key from your Azure account.

subscription_key = "YOUR_ACCESS_KEY"
assert subscription_key

Declare the Bing Web Search API endpoint. If you run into any 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"

Feel free to customize the search query by replacing the value for search_term.

search_term = "Azure Cognitive Services"

Make a request

This block uses the requests library to call the Bing Web Search API and return the results as a JSON object. The API key is passed in the headers dictionary, and the search term and query parameters are passed in the params dictionary. See Bing Web Search API v7 documentation for a complete list of options and parameters.

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()

Format and display the response

The search_results object includes the search results and metadata such as related queries and pages. This code uses the IPython.display library to format and display the response in your browser.

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))

Sample code on GitHub

If you'd like to run this code locally, the complete sample is available on GitHub.

Next steps

See also