Quickstart: Use the Bing Custom Search client library

Get started with the Bing Custom Search client library for C#. Follow these steps to install the package and try out the example code for basic tasks. The Bing Custom Search API enables you to create tailored, ad-free search experiences for topics that you care about. The source code for this sample can be found on GitHub.

Use the Bing Custom Search client library for C# to:

  • Find search results on the web, from your Bing Custom Search instance.

Reference documentation | Library source code | Package (NuGet) | Samples

Prerequisites

  • A Bing Custom Search instance. See Quickstart: Create your first Bing Custom Search instance for more information.
  • Microsoft .NET Core
  • Any edition of Visual Studio 2017 or later
  • If you are using Linux/MacOS, this application can be run using Mono.
  • The Bing Custom Search NuGet package.
    • From Solution Explorer in Visual Studio, right-click your project and select Manage NuGet Packages from the menu. Install the Microsoft.Azure.CognitiveServices.Search.CustomSearch package. Installing the NuGet Custom Search package also installs the following assemblies:
      • Microsoft.Rest.ClientRuntime
      • Microsoft.Rest.ClientRuntime.Azure
      • Newtonsoft.Json

Create an Azure resource

Start using the Bing Custom 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 a Bing Custom Search 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 C# console application in Visual Studio. Then add the following packages to your project.

    using System;
    using System.Linq;
    using Microsoft.Azure.CognitiveServices.Search.CustomSearch;
    
  2. In the main method of your application, instantiate the search client with your API key.

    var client = new CustomSearchAPI(new ApiKeyServiceClientCredentials("YOUR-SUBSCRIPTION-KEY"));
    

Send the search request and receive a response

  1. Send a search query using your client's SearchAsync() method, and save the response. Be sure to replace your YOUR-CUSTOM-CONFIG-ID with your instance's configuration ID (you can find the ID in the Bing Custom Search portal). This example searches for "Xbox".

    // This will look up a single query (Xbox).
    var webData = client.CustomInstance.SearchAsync(query: "Xbox", customConfig: Int32.Parse("YOUR-CUSTOM-CONFIG-ID")).Result;
    
  2. The SearchAsync() method returns a WebData object. Use the object to iterate through any WebPages that were found. This code finds the first webpage result and prints the webpage's Name and URL.

    if (webData?.WebPages?.Value?.Count > 0)
    {
        // find the first web page
        var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();
    
        if (firstWebPagesResult != null)
        {
            Console.WriteLine("Number of webpage results {0}", webData.WebPages.Value.Count);
            Console.WriteLine("First web page name: {0} ", firstWebPagesResult.Name);
            Console.WriteLine("First web page URL: {0} ", firstWebPagesResult.Url);
        }
        else
        {
            Console.WriteLine("Couldn't find web results!");
        }
    }
    else
    {
        Console.WriteLine("Didn't see any Web data..");
    }
    

Next steps

Get started with the Bing Custom Search client library for Java. Follow these steps to install the package and try out the example code for basic tasks. The Bing Custom Search API enables you to create tailored, ad-free search experiences for topics that you care about. The source code for this sample can be found on GitHub

Use the Bing Custom Search client library for Java to:

  • Find search results on the web, from your Bing Custom Search instance.

Reference documentation | Library source code | Artifact (Maven) | Samples

Prerequisites

Create an Azure resource

Start using the Bing Custom 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 a Bing Custom Search 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.

After you get a key from your trial subscription or resource, create an environment variable for the key, named AZURE_BING_CUSTOM_SEARCH_API_KEY.

Create a new Gradle project

Tip

If you're not using Gradle, you can find the client library details for other dependency managers on the Maven Central Repository.

In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.

mkdir myapp && cd myapp

Run the gradle init command from your working directory. This command creates essential build files for Gradle, including a build.gradle.kts file that is used at runtime to configure your application.

gradle init --type basic

When prompted to choose a DSL, select Kotlin.

Install the client library

Locate build.gradle.kts and open it with your preferred IDE or text editor. Then copy in this build configuration. Be sure to include the client library under dependencies:

plugins {
    java
    application
}
application {
    mainClassName = "main.java.BingCustomSearchSample"
}
repositories {
    mavenCentral()
}
dependencies {
    compile("org.slf4j:slf4j-simple:1.7.25")
    compile("com.microsoft.azure.cognitiveservices:azure-cognitiveservices-customsearch:1.0.2")
}

Create a folder for your sample app. From your working directory, run the following command:

mkdir src/main/java

Navigate to the new folder and create a file called BingCustomSearchSample.java. Open it and add the following import statements:

package main.java;

import com.microsoft.azure.cognitiveservices.search.customsearch.BingCustomSearchAPI;
import com.microsoft.azure.cognitiveservices.search.customsearch.BingCustomSearchManager;
import com.microsoft.azure.cognitiveservices.search.customsearch.models.SearchResponse;
import com.microsoft.azure.cognitiveservices.search.customsearch.models.WebPage;

Create a class named BingCustomSearchSample

public class BingCustomSearchSample {
}

In the class, create a main method and a variable for your resource's key. If you created the environment variable after you launched the application, close and reopen the editor, IDE, or shell running it to access the variable. You will define the methods later.

public static void main(String[] args) {
    try {

        // Set the BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY and AZURE_BING_SAMPLES_CUSTOM_CONFIG_ID environment variables, 
        // then reopen your command prompt or IDE. If not, you may get an API key not found exception.
        final String subscriptionKey = System.getenv("BING_CUSTOM_SEARCH_SUBSCRIPTION_KEY");
        // If you do not have a customConfigId, you can also use 1 as your value when setting your environment variable.
        final String customConfigId = System.getenv("AZURE_BING_SAMPLES_CUSTOM_CONFIG_ID");

        BingCustomSearchAPI client = BingCustomSearchManager.authenticate(subscriptionKey);

        runSample(client, customConfigId);
    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

Object model

The Bing Custom Search client is a BingCustomSearchAPI object that's created from the BingCustomSearchManager object's authenticate() method. You can send a search request using the client's BingCustomInstances.search() method.

The API response is a SearchResponse object containing information on the search query, and search results.

Code examples

These code snippets show you how to do the following tasks with the Bing Custom Search client library for Java:

Authenticate the client

Your main method should include a BingCustomSearchManager object that takes your key, and calls its authenticate().

BingCustomSearchAPI client = BingCustomSearchManager.authenticate(subscriptionKey);

Get search results from your custom search instance

Use the client's BingCustomInstances.search() function to send a search query to your custom instance. Set the withCustomConfig to your custom configuration ID, or default to 1. After getting a response from the API, check if any search results were found. If so, get the first search result by calling the response's webPages().value().get() function and print the result's name, and URL.

public static boolean runSample(BingCustomSearchAPI client, String customConfigId) {
    try {

        // This will search for "Xbox" using Bing Custom Search 
        //and print out name and url for the first web page in the results list

        System.out.println("Searching for Query: \"Xbox\"");
        SearchResponse webData = client.bingCustomInstances().search()
            .withCustomConfig(customConfigId != null ? Long.valueOf(customConfigId) : 0)
            .withQuery("Xbox")
            .withMarket("en-us")
            .execute();

        if (webData != null && webData.webPages() != null && webData.webPages().value().size() > 0)
        {
            // find the first web page
            WebPage firstWebPagesResult = webData.webPages().value().get(0);

            if (firstWebPagesResult != null) {
                System.out.println(String.format("Webpage Results#%d", webData.webPages().value().size()));
                System.out.println(String.format("First web page name: %s ", firstWebPagesResult.name()));
                System.out.println(String.format("First web page URL: %s ", firstWebPagesResult.url()));
            } else {
                System.out.println("Couldn't find web results!");
            }
        } else {
            System.out.println("Didn't see any Web data..");
        }

        return true;
    } catch (Exception f) {
        System.out.println(f.getMessage());
        f.printStackTrace();
    }
    return false;
}

Run the application

Build the app with the following command from your project's main directory:

gradle build

Run the application with the run goal:

gradle run

Clean up resources

If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.

Next steps

Get started with the Bing Custom Search client library for Python. Follow these steps to install the package and try out the example code for basic tasks. The Bing Custom Search API enables you to create tailored, ad-free search experiences for topics that you care about.The source code for this sample can be found on GitHub.

Use the Bing Custom Search client library for Python to:

  • Find search results on the web, from your Bing Custom Search instance.

Reference documentation | Library source code | Package (PyPi) | Samples

Prerequisites

Create an Azure resource

Start using the Bing Custom 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 a Bing Custom Search 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.

Install the Python client library

Install the Bing Custom Search client library with the following command.

python -m pip install azure-cognitiveservices-search-customsearch

Create a new application

Create a new Python file in your favorite editor or IDE, and add the following imports.

from azure.cognitiveservices.search.customsearch import CustomSearchClient
from msrest.authentication import CognitiveServicesCredentials

Create a search client and send a request

  1. Create a variable for your subscription key and endpoint.

    subscription_key = 'your-subscription-key'
    endpoint = 'your-endpoint'
    
  2. Create an instance of CustomSearchClient, using a CognitiveServicesCredentials object with the subscription key.

    client = CustomSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  3. Send a search request with client.custom_instance.search(). Append your search term to the query parameter, and set custom_config to your Custom Configuration ID to use your search instance. You can get your ID from the Bing Custom Search portal, by clicking the Production tab.

    web_data = client.custom_instance.search(query="xbox", custom_config="your-configuration-id")
    

View the search results

If any web page search results were found, get the first one and print its name, URL, and total web pages found.

if web_data.web_pages.value:
    first_web_result = web_data.web_pages.value[0]
    print("Web Pages result count: {}".format(len(web_data.web_pages.value)))
    print("First Web Page name: {}".format(first_web_result.name))
    print("First Web Page url: {}".format(first_web_result.url))
else:
    print("Didn't see any web data..")

Next steps