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