The Bing Image Search API provides an experience similar to Bing.com/Images by letting you send a user search query to Bing and get back a list of relevant images.
This walkthrough demonstrates a simple example of calling into the Bing Image Search API and post-processing the resulting JSON object. For more information, see Bing Image Search documentation.
You can run this example as a Jupyter notebook on MyBinder by clicking on the launch Binder badge:
You must have a Cognitive Services API account with Bing Search APIs. The free trial is sufficient for this quickstart. You need the access key provided when you activate your free trial, or you may use a paid subscription key from your Azure dashboard.
To continue with the walkthrough, set subscription_key
to your API key for the Bing API service.
subscription_key = None
assert subscription_key
Next, verify that the search_url
endpoint is correct. At this writing, only one endpoint is used for Bing search APIs. If you encounter authorization errors, double-check this value against the Bing search endpoint in your Azure dashboard.
search_url = "https://api.cognitive.microsoft.com/bing/v7.0/images/search"
Set search_term
to look for images of puppies.
search_term = "puppies"
The following block uses the requests
library in Python to call out to the Bing search APIs and return the results as a JSON object. Observe that we pass in the API key via the headers
dictionary and the search term via the params
dictionary. To see the full list of options that can be used to filter search results, refer to the REST API documentation.
import requests
headers = {"Ocp-Apim-Subscription-Key" : subscription_key}
params = {"q": search_term, "license": "public", "imageType": "photo"}
response = requests.get(search_url, headers=headers, params=params)
response.raise_for_status()
search_results = response.json()
The search_results
object contains the actual images along with rich metadata such as related items. For example, the following line of code can extract the thumbnail URLS for the first 16 results.
thumbnail_urls = [img["thumbnailUrl"] for img in search_results["value"][:16]]
Then, we can use the PIL
library to download the thumbnail images and the matplotlib
library to render them on a $4 \times 4$ grid.
%matplotlib inline
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
f, axes = plt.subplots(4, 4)
for i in range(4):
for j in range(4):
image_data = requests.get(thumbnail_urls[i+4*j])
image_data.raise_for_status()
image = Image.open(BytesIO(image_data.content))
axes[i][j].imshow(image)
axes[i][j].axis("off")
[!div class="nextstepaction"] Bing Image Search single-page app tutorial
Bing Image Search overview
Try it
Get a free trial access key
Bing Image Search API reference