|
3 | 3 |
|
4 | 4 | # -*- coding: utf-8 -*- |
5 | 5 |
|
| 6 | +import json |
| 7 | +import os |
| 8 | +import requests |
| 9 | +from pprint import pprint |
| 10 | + |
6 | 11 | ''' |
7 | 12 | This sample uses the Bing Autosuggest API to check the spelling of query words and then suggests corrections. |
8 | 13 | Bing Spell Check API: https://docs.microsoft.com/en-us/rest/api/cognitiveservices-bingsearch/bing-autosuggest-api-v7-reference57855119bca1df1c647bc358 |
9 | 14 | ''' |
10 | 15 |
|
11 | | -import http.client |
12 | | -import json |
13 | | -import os |
14 | | -import urllib.parse |
15 | | - |
16 | | -# Add your Bing Autosuggest subscription key to your environment variables. |
17 | | -subscriptionKey = os.environ['BING_AUTOSUGGEST_SUBSCRIPTION_KEY'] |
18 | | - |
19 | | -# Add your Bing Autosuggest endpoint to your environment variables. |
20 | | -host = os.environ['BING_AUTOSUGGEST_ENDPOINT'] |
21 | | -host = host.replace('https://', '') |
22 | | -path = '/bing/v7.0/Suggestions' |
| 16 | +# Add your Bing Autosuggest subscription key and endpoint to your environment variables. |
| 17 | +subscription_key = os.environ['BING_AUTOSUGGEST_SUBSCRIPTION_KEY'] |
| 18 | +endpoint = os.environ['BING_AUTOSUGGEST_ENDPOINT'] + '/bing/v7.0/Suggestions/' |
23 | 19 |
|
| 20 | +# Construct the request |
24 | 21 | mkt = 'en-US' |
25 | 22 | query = 'sail' |
| 23 | +params = { 'q': query, 'mkt': mkt } |
| 24 | +headers = { 'Ocp-Apim-Subscription-Key': subscription_key } |
26 | 25 |
|
27 | | -params = '?mkt=' + mkt + '&q=' + query |
28 | | - |
29 | | -def get_suggestions (): |
30 | | - "Gets Autosuggest results for a query and returns the information." |
| 26 | +# Call the API |
| 27 | +try: |
| 28 | + response = requests.get(endpoint, headers=headers, params=params) |
| 29 | + response.raise_for_status() |
31 | 30 |
|
32 | | - headers = {'Ocp-Apim-Subscription-Key': subscriptionKey} |
33 | | - conn = http.client.HTTPSConnection(host) |
34 | | - conn.request ("GET", path + params, None, headers) |
35 | | - response = conn.getresponse () |
36 | | - return response.read () |
| 31 | + print("\nHeaders:\n") |
| 32 | + print(response.headers) |
37 | 33 |
|
38 | | -result = get_suggestions () |
39 | | -print (json.dumps(json.loads(result), indent=4)) |
| 34 | + print("\nJSON Response:\n") |
| 35 | + pprint(response.json()) |
| 36 | +except Exception as ex: |
| 37 | + raise ex |
0 commit comments