Quickstart: Perform a news search using Python and the Bing News Search REST API

This walkthrough demonstrates a simple example of calling into the Bing News Search API and post-processing the resulting JSON object. For more information, see Bing New Search documentation.

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



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. See also Cognitive Services Pricing - Bing Search API.

Running the walkthrough

First, 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/news/search"

Set search_term to look for news articles about Microsoft.

search_term = "Microsoft"

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)
search_results = response.json()

The search_results object contains the relevant new articles along with rich metadata. For example, the following line of code extracts the descriptions of the articles.

descriptions = [article["description"] for article in search_results["value"]]

These descriptions can then be rendered as a table with the search keyword highlighted in bold.

from IPython.display import HTML
rows = "\n".join(["<tr><td>{0}</td></tr>".format(desc) for desc in descriptions])

Next steps

See also

Searching the web for news
Try it