Quickstart: Send a query to the Bing Local Business Search API in Python
Warning
On October 30, 2020, the Bing Search APIs moved from Azure AI services to Bing Search Services. This documentation is provided for reference only. For updated documentation, see the Bing search API documentation. For instructions on creating new Azure resources for Bing search, see Create a Bing Search resource through the Azure Marketplace.
Use this quickstart to learn how to send requests to the Bing Local Business Search API, which is an Azure Cognitive Service. Although this simple application is written in Python, the API is a RESTful Web service compatible with any programming language capable of making HTTP requests and parsing JSON.
This example application gets local response data from the API for a search query.
Prerequisites
- An Azure subscription - Create one for free
- Python 2.x or 3.x.
- Once you have your Azure subscription, create a Bing Search resource in the Azure portal to get your key and endpoint. After it deploys, click Go to resource.
Run the complete application
The following example gets localized results, which are implemented in the following steps:
- Declare variables to specify the endpoint by host and path.
- Specify 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 is as follows:
import http.client, urllib.parse
import json
# Replace the subscriptionKey string value with your valid subscription key.
subscriptionKey = 'YOUR-SUBSCRIPTION-KEY'
host = 'api.cognitive.microsoft.com'
path = '/bing/v7.0/localbusinesses/search'
query = 'restaurant in Bellevue'
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))