The following Python example creates and sends a request for information about "Rock of Gibraltar".
Get an access key for the free trial Cognitive Research Technologies
This example uses Python 3.6.4
The following code creates a URL Preview. It is implemented in the following steps:
- Declare variables to specify the endpoint by host and path.
- Specify the query URL to preview, and add the query parameter.
- Set the query parameter.
- Define the Search function that creates the request and adds the Ocp-Apim-Subscription-Key header.
- Set the Ocp-Apim-Subscription-Key header.
- Make the connection, and send the request.
- Print the JSON results.
The complete code for this demo follows:
import http.client, urllib.parse
import json
# Replace the subscriptionKey string value with your valid subscription key.
subscriptionKey = 'YOUR-SUBSCRIPTION-KEY'
host = 'https://api.labs.cognitive.microsoft.com'
path = '/answerSearch/v7.0/search '
query = 'Rock of Gibraltar'
params = '?q=' + urllib.parse.quote (query) + '&mkt=en-us'
def get_local():
headers = {'Ocp-Apim-Subscription-Key': subscriptionKey}
conn = http.client.HTTPSConnection (host)
conn.request ("GET", path + params, None, headers)
response = conn.getresponse ()
return response.read ()
result = get_local()
print (json.dumps(json.loads(result), indent=4))