The following Python example creates a Url Preview for the SwiftKey Web site: https://swiftkey.com/en.
Get an access key for the free trial Cognitive Research Technologies
This example uses Python 3.6.
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 = 'api.labs.cognitive.microsoft.com'
path = '/urlpreview/v7.0/search'
query = 'https://SwiftKey.com'
params = '?q=' + urllib.parse.quote (query)
def get_preview ():
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_preview ()
print (json.dumps(json.loads(result), indent=4))