Quickstart: Use the Bing Image Search client library

Use this quickstart to make your first image search using the Bing Image Search client library, which is a wrapper for the API and contains the same features. This simple C# application sends an image search query, parses the JSON response, and displays the URL of the first image returned.

The source code for this sample is available on GitHub with additional error handling and annotations.

Prerequisites

To install the Bing Image Search client library in Visual Studio, use the Manage NuGet Packages option from Solution Explorer.

Create an Azure resource

Start using the Bing Image Search API by creating one of the Azure resources below.

  • Create a trial resource:

    • No Azure subscription needed.
    • Valid for seven days, for free. After signing up, a trial key and endpoint will be available on the Azure website.
  • Create Bing Search v7 resource:

    • Available through the Azure portal until you delete the resource.
    • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.
  • Create a Multi-Service resource:

    • Available through the Azure portal until you delete the resource.
    • Use the same key and endpoint for your applications, across multiple Cognitive Services.

See also Cognitive Services Pricing - Bing Search API.

Create and initialize the application

First, create a new C# console application in Visual Studio. Then add the following packages to your project.

using System;
using System.Linq;
using Microsoft.Azure.CognitiveServices.Search.ImageSearch;
using Microsoft.Azure.CognitiveServices.Search.ImageSearch.Models;

In the main method of your project, create variables for your valid subscription key, the image results to be returned by Bing, and a search term. Then instantiate the image search client using the key.

//IMPORTANT: replace this variable with your Cognitive Services subscription key
string subscriptionKey = "ENTER YOUR KEY HERE";
//stores the image results returned by Bing
Images imageResults = null;
// the image search term to be used in the query
string searchTerm = "canadian rockies";

//initialize the client
//NOTE: If you're using version 1.2.0 or below for the Bing Image Search client library, 
// use ImageSearchAPI() instead of ImageSearchClient() to initialize your search client.

var client = new ImageSearchClient(new ApiKeyServiceClientCredentials(subscriptionKey));

Send a search query using the client

Use the client to search with a query text:

// make the search request to the Bing Image API, and get the results"
imageResults = client.Images.SearchAsync(query: searchTerm).Result; //search query

Parse and view the first image result

Parse the image results returned in the response. If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL,along with the total number of returned images.

if (imageResults != null)
{
    //display the details for the first image result.
    var firstImageResult = imageResults.Value.First();
    Console.WriteLine($"\nTotal number of returned images: {imageResults.Value.Count}\n");
    Console.WriteLine($"Copy the following URLs to view these images on your browser.\n");
    Console.WriteLine($"URL to the first image:\n\n {firstImageResult.ContentUrl}\n");
    Console.WriteLine($"Thumbnail URL for the first image:\n\n {firstImageResult.ThumbnailUrl}");
    Console.ReadKey();
}

Next steps

See also

Use this quickstart to make your first image search using the Bing Image Search client library, which is a wrapper for the API and contains the same features. This simple Java application sends an image search query, parses the JSON response, and displays the URL of the first image returned.

The source code for this sample is available on GitHub with additional error handling and annotations.

Prerequisites

The latest version of the Java Development Kit (JDK)

Install the Bing Image Search client library dependencies by using Maven, Gradle, or another dependency management system. The Maven POM file requires the following declaration:

 <dependencies>
    <dependency>
      <groupId>com.microsoft.azure.cognitiveservices</groupId>
      <artifactId>azure-cognitiveservices-imagesearch</artifactId>
      <version>1.0.1</version>
    </dependency>
 </dependencies>

Create an Azure resource

Start using the Bing Image Search API by creating one of the Azure resources below.

  • Create a trial resource:

    • No Azure subscription needed.
    • Valid for seven days, for free. After signing up, a trial key and endpoint will be available on the Azure website.
  • Create Bing Search v7 resource:

    • Available through the Azure portal until you delete the resource.
    • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.
  • Create a Multi-Service resource:

    • Available through the Azure portal until you delete the resource.
    • Use the same key and endpoint for your applications, across multiple Cognitive Services.

Create and initialize the application

  1. Create a new Java project in your favorite IDE or editor, and add the following imports to your class implementation:

    import com.microsoft.azure.cognitiveservices.search.imagesearch.BingImageSearchAPI;
    import com.microsoft.azure.cognitiveservices.search.imagesearch.BingImageSearchManager;
    import com.microsoft.azure.cognitiveservices.search.imagesearch.models.ImageObject;
    import com.microsoft.azure.cognitiveservices.search.imagesearch.models.ImagesModel;
    
  2. In your main method create variables for your subscription key, and search term. Then instantiate the Bing Image Search client.

    final String subscriptionKey = "COPY_YOUR_KEY_HERE";
    String searchTerm = "canadian rockies";
    //Image search client
    BingImageSearchAPI client = BingImageSearchManager.authenticate(subscriptionKey);
    

Send a search request to the API

  1. Using bingImages().search(), send the HTTP request containing the search query. Save the response as a ImagesModel.

     ImagesModel imageResults = client.bingImages().search()
                 .withQuery(searchTerm)
                 .withMarket("en-us")
                 .execute();
    

Parse and view the result

Parse the image results returned in the response. If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL, along with the total number of returned images.

if (imageResults != null && imageResults.value().size() > 0) {
    // Image results
    ImageObject firstImageResult = imageResults.value().get(0);

    System.out.println(String.format("Total number of images found: %d", imageResults.value().size()));
    System.out.println(String.format("First image thumbnail url: %s", firstImageResult.thumbnailUrl()));
    System.out.println(String.format("First image content url: %s", firstImageResult.contentUrl()));
}
else {
        System.out.println("Couldn't find image results!");
     }

Next steps

See also

Use this quickstart to make your first image search using the Bing Image Search client library, which is a wrapper for the API and contains the same features. This simple JavaScript application sends an image search query, parses the JSON response, and displays the URL of the first image returned.

The source code for this sample is available on GitHub with additional error handling and annotations.

Prerequisites

Create an Azure resource

Start using the Bing Image Search API by creating one of the Azure resources below.

  • Create a trial resource:

    • No Azure subscription needed.
    • Valid for seven days, for free. After signing up, a trial key and endpoint will be available on the Azure website.
  • Create Bing Search v7 resource:

    • Available through the Azure portal until you delete the resource.
    • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.
  • Create a Multi-Service resource:

    • Available through the Azure portal until you delete the resource.
    • Use the same key and endpoint for your applications, across multiple Cognitive Services.

Create and initialize the application

  1. Create a new JavaScript file in your favorite IDE or editor, and set the strictness, https, and other requirements.

    'use strict';
    const ImageSearchAPIClient = require('@azure/cognitiveservices-imagesearch');
    const CognitiveServicesCredentials = require('ms-rest-azure').CognitiveServicesCredentials;
    
  2. In the main method of your project, create variables for your valid subscription key, the image results to be returned by Bing, and a search term. Then instantiate the image search client using the key.

    //replace this value with your valid subscription key.
    let serviceKey = "ENTER YOUR KEY HERE";
    
    //the search term for the request
    let searchTerm = "canadian rockies";
    
    //instantiate the image search client
    let credentials = new CognitiveServicesCredentials(serviceKey);
    let imageSearchApiClient = new ImageSearchAPIClient(credentials);
    
    

Create an asynchronous helper function

  1. Create a function to call the client asynchronously, and return the response from the Bing Image Search service.

    //a helper function to perform an async call to the Bing Image Search API
    const sendQuery = async () => {
        return await imageSearchApiClient.imagesOperations.search(searchTerm);
    };
    

    Send a query and handle the response

  2. Call the helper function and handle its promise to parse the image results returned in the response.

    If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL,along with the total number of returned images.

    sendQuery().then(imageResults => {
        if (imageResults == null) {
        console.log("No image results were found.");
        }
        else {
            console.log(`Total number of images returned: ${imageResults.value.length}`);
            let firstImageResult = imageResults.value[0];
            //display the details for the first image result. After running the application,
            //you can copy the resulting URLs from the console into your browser to view the image.
            console.log(`Total number of images found: ${imageResults.value.length}`);
            console.log(`Copy these URLs to view the first image returned:`);
            console.log(`First image thumbnail url: ${firstImageResult.thumbnailUrl}`);
            console.log(`First image content url: ${firstImageResult.contentUrl}`);
        }
      })
      .catch(err => console.error(err))
    

Next steps

See also

Use this quickstart to make your first image search using the Bing Image Search client library, which is a wrapper for the API and contains the same features. This simple Python application sends an image search query, parses the JSON response, and displays the URL of the first image returned.

The source code for this sample is available on GitHub with additional error handling and annotations.

Prerequisites

Create an Azure resource

Start using the Bing Image Search API by creating one of the Azure resources below.

  • Create a trial resource:

    • No Azure subscription needed.
    • Valid for seven days, for free. After signing up, a trial key and endpoint will be available on the Azure website.
  • Create Bing Search v7 resource:

    • Available through the Azure portal until you delete the resource.
    • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.
  • Create a Multi-Service resource:

    • Available through the Azure portal until you delete the resource.
    • Use the same key and endpoint for your applications, across multiple Cognitive Services.

Create and initialize the application

  1. Create a new Python script in your favorite IDE or editor, and the following imports:

    from azure.cognitiveservices.search.imagesearch import ImageSearchClient
    from msrest.authentication import CognitiveServicesCredentials
    
  2. Create variables for your subscription key and search term.

    subscription_key = "Enter your key here"
    subscription_endpoint = "Enter your endpoint here"
    search_term = "canadian rockies"
    

Create the image search client

  1. Create an instance of CognitiveServicesCredentials, and use it to instantiate the client:

    client = ImageSearchClient(endpoint=subscription_endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  2. Send a search query to the Bing Image Search API:

    image_results = client.images.search(query=search_term)
    

    Process and view the results

Parse the image results returned in the response.

If the response contains search results, store the first result and print out its details, such as a thumbnail URL, the original URL,along with the total number of returned images.

if image_results.value:
    first_image_result = image_results.value[0]
    print("Total number of images returned: {}".format(len(image_results.value)))
    print("First image thumbnail url: {}".format(
        first_image_result.thumbnail_url))
    print("First image content url: {}".format(first_image_result.content_url))
else:
    print("No image results returned!")

Next steps

See also