|
3 | 3 |
|
4 | 4 | # -*- coding: utf-8 -*- |
5 | 5 |
|
6 | | -import http.client |
7 | 6 | import json |
8 | | -import urllib.parse |
9 | 7 | import os |
| 8 | +from pprint import pprint |
| 9 | +import requests |
10 | 10 |
|
11 | 11 | ''' |
12 | 12 | This sample makes a call to the Bing News Search API with a text query and returns relevant news webpages. |
|
15 | 15 |
|
16 | 16 | # Add your Bing Search V7 subscription key and endpoint to your environment variables. |
17 | 17 | subscriptionKey = os.environ['BING_SEARCH_V7_SUBSCRIPTION_KEY'] |
18 | | -host = os.environ['BING_SEARCH_V7_ENDPOINT'] |
19 | | -host = host.replace('https://', '') |
20 | | -path = "/bing/v7.0/news/search" |
| 18 | +endpoint = os.environ['BING_SEARCH_V7_ENDPOINT'] + "/bing/v7.0/news/search" |
21 | 19 |
|
22 | | -term = "Microsoft" |
| 20 | +query = "Microsoft" |
23 | 21 |
|
24 | | -# Construct the request. |
| 22 | +# Construct a request |
| 23 | +mkt = 'en-US' |
| 24 | +params = {'q': query, 'mkt': mkt} |
25 | 25 | headers = {'Ocp-Apim-Subscription-Key': subscriptionKey} |
26 | | -conn = http.client.HTTPSConnection(host) |
27 | | -query = urllib.parse.quote(term) |
28 | | -print('Searching news for: ', term) |
29 | | -conn.request("GET", path + "?q=" + query, headers=headers) |
30 | | -response = conn.getresponse() |
31 | | -headers = [k + ": " + v for (k, v) in response.getheaders() |
32 | | - if k.startswith("BingAPIs-") or k.startswith("X-MSEdge-")] |
33 | | - |
34 | | -# Print search results. |
35 | | -print("\nRelevant HTTP Headers:\n") |
36 | | -print("\n".join(headers)) |
37 | | -print("\nJSON Response:\n") |
38 | | -print(json.dumps(json.loads(response.read()), indent=4)) |
| 26 | + |
| 27 | +# Call the API |
| 28 | +try: |
| 29 | + response = requests.get(endpoint, headers=headers, params=params) |
| 30 | + response.raise_for_status() |
| 31 | + |
| 32 | + print("\nHeaders:\n") |
| 33 | + print(response.headers) |
| 34 | + |
| 35 | + print("\nJSON Response:\n") |
| 36 | + pprint(response.json()) |
| 37 | +except Exception as ex: |
| 38 | + raise ex |
0 commit comments