Skip to content

Commit e2f752c

Browse files
authored
Updated library
1 parent 84e3a3e commit e2f752c

File tree

1 file changed

+21
-23
lines changed

1 file changed

+21
-23
lines changed

python/Search/BingAutosuggestv7.py

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,37 +3,35 @@
33

44
# -*- coding: utf-8 -*-
55

6+
import json
7+
import os
8+
import requests
9+
from pprint import pprint
10+
611
'''
712
This sample uses the Bing Autosuggest API to check the spelling of query words and then suggests corrections.
813
Bing Spell Check API: https://docs.microsoft.com/en-us/rest/api/cognitiveservices-bingsearch/bing-autosuggest-api-v7-reference57855119bca1df1c647bc358
914
'''
1015

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/'
2319

20+
# Construct the request
2421
mkt = 'en-US'
2522
query = 'sail'
23+
params = { 'q': query, 'mkt': mkt }
24+
headers = { 'Ocp-Apim-Subscription-Key': subscription_key }
2625

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()
3130

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)
3733

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

Comments
 (0)