Quickstart: Perform a news search using Python and Bing News Search REST API
Use this quickstart to make your first call to Bing News Search API. This simple Python application sends a search query to the API and processes the JSON result.
Although this application is written in Python, the API is a RESTful Web service compatible with most programming languages.
To run this code sample as a Jupyter notebook on MyBinder, select the launch binder badge:
The source code for this sample is also available on GitHub.
Create and initialize the application
Create a new Python file in your favorite IDE or editor, and import the request module. Create variables for your subscription key, endpoint, and search term.
import requests
subscription_key = "your subscription key"
search_term = "Microsoft"
search_url = "https://api.bing.microsoft.com/v7.0/news/search"
Create parameters for the request
Add your subscription key to a new dictionary, using Ocp-Apim-Subscription-Key
as the key. Do the same for your search parameters.
headers = {"Ocp-Apim-Subscription-Key" : subscription_key}
params = {"q": search_term, "textDecorations": True, "textFormat": "HTML"}
Send a request and get a response
Use the requests library to call the Bing Visual Search API with your subscription key, and the dictionary objects you created in the previous step.
response = requests.get(search_url, headers=headers, params=params) response.raise_for_status() search_results = json.dumps(response.json())
Access the descriptions of the articles contained in the response from the API, which is stored in
search_results
as a JSON object.descriptions = [article["description"] for article in search_results["value"]]
Display the results
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])
HTML("<table>"+rows+"</table>")