Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Bing

Bing Web Search SDK

5.00/5 (2 votes)
9 Feb 2018CPOL2 min read 6.8K  
How to use the Bing Search SDK to programmatically find Web pages, News, Images, Video.

Introduction

The Bing Web Search SDK makes Bing REST APIs accessible to applications in four languages:

  • C#
  • Java
  • Node.js
  • Python

Background

The SDK extends the REST interface introduced in a previous Code Project article. See Getting Started with the Bing Search APIs.

Using the Code

SDK methods create and manage Web requests. You don't have to parse JSON text as returned by the REST interface. 

To experiment with the Bing Web Search SDK, you’ll need an API access key.  A free trial key is available from Azure: Try Cognitive Services.

Building a C# Application with the Bing Web Search SDK

To install the Bing Web Search SDK in Visual Studio, right click the project in Solution Explorer, and select NuGet Package Manager. Click Browse, and enter ‘websearch’. 

Install the Microsoft.Azure.CognitiveServices.Search.WebSearch client library.

Install SDK NuGet package

Installing the WebSearch SDK package will also install dependencies:

Search SDK dependencies

  • Newtonsoft.Json
  • Microsoft.Rest.ClientRuntime.2.3.10
  • Microsoft.Rest.ClientRuntime.Azure.3.3.10

With the libraries referenced by the installation, add using directives:

C#
using Microsoft.Azure.CognitiveServices.Search.WebSearch;
using Microsoft.Azure.CognitiveServices.Search.WebSearch.Models;

Create an Instance of the WebSearchAPI

Create the search client.  The ApiKeyServiceClientCredentials constructor takes your access key as a string parameter.

C#
var client = new WebSearchAPI(new ApiKeyServiceClientCredentials("YOUR-ACCESS-KEY"));

Search for Web Page Results

Using the client created in the previous example, search for Web pages:

  1. Call the client.Web.Search method with the previously defined query
  2. Examine the results
  3. Print the number of results
  4. Print name and URL of the first web page result

Search for 'Yosemite National Park', and print results.

C#
var webData = client.Web.Search(query: "Yosemite National Park");
Console.WriteLine("Searched for Query# \" Yosemite National Park \"\r\n");

if (webData?.WebPages?.Value?.Count > 0)

{

    // find the first web page
    var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();

    if (firstWebPagesResult != null)
    {
        Console.WriteLine("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..");
     }
}

Console.WriteLine("\r\nAny key to exit... ");
Console.ReadKey();

With the previous few lines of code, you can run an application using the Bing Search API.

You can get all the web page results with the following code:

C#
static void Main(string[] args)
{
    var client = new WebSearchAPI
                 (new ApiKeyServiceClientCredentials("19aa718a79d6444daaa415981d9f54ad"));

    var webData = client.Web.Search(query: "Yosemite National Park");
    Console.WriteLine("Searched for Query# \" Yosemite National Park \" \r\n");

    //WebPages
    if (webData?.WebPages?.Value?.Count > 0)
    {
        for (int w = 0; w < webData.WebPages.Value.Count; w++)
        {
            Console.WriteLine("Webpage Results #{0}", webData.WebPages.Value.Count);
            Console.WriteLine("Web page name: {0} ", webData.WebPages.Value[w].Name);
            Console.WriteLine("Web page URL: {0} ", webData.WebPages.Value[w].Url);
        }
    }
            
    else
    {
        Console.WriteLine("Didn't see any Web data..");
    }

    Console.WriteLine("\r\nAny key to exit... ");
    Console.ReadKey();
}

Search for Images, News, Videos

The following code works the same way as the first example to find images, news, and video results.

C#
//Images
if (webData?.Images?.Value?.Count > 0)
{
    // find the first image result
    var firstImageResult = webData.Images.Value.FirstOrDefault();

    if (firstImageResult != null)
    {
        Console.WriteLine("Image Results #{0}", webData.Images.Value.Count);
        Console.WriteLine("First Image result name: {0} ", firstImageResult.Name);
        Console.WriteLine("First Image result URL: {0} ", firstImageResult.ContentUrl);
    }
    else
    {
        Console.WriteLine("Couldn't find first image results!");
    }
}
else
{
    Console.WriteLine("Didn't see any image data..");
}

//News
if (webData?.News?.Value?.Count > 0)
{
    // find the first news result
    var firstNewsResult = webData.News.Value.FirstOrDefault();

    if (firstNewsResult != null)
    {
        Console.WriteLine("\r\nNews Results #{0}", webData.News.Value.Count);
        Console.WriteLine("First news result name: {0} ", firstNewsResult.Name);
        Console.WriteLine("First news result URL: {0} ", firstNewsResult.Url);
    }
    else
    {
        Console.WriteLine("Couldn't find any News results!");
    }
}
else
{
    Console.WriteLine("Didn't see first news data..");
}

//Videos
if (webData?.Videos?.Value?.Count > 0)
{
    // find the first video result
    var firstVideoResult = webData.Videos.Value.FirstOrDefault();

    if (firstVideoResult != null)
    {
        Console.WriteLine("\r\nVideo Results #{0}", webData.Videos.Value.Count);
        Console.WriteLine("First Video result name: {0} ", firstVideoResult.Name);
        Console.WriteLine("First Video result URL: {0} ", firstVideoResult.ContentUrl);
    }
    else
    {
        Console.WriteLine("Couldn't find first video results!");
    }
}
else
{
    Console.WriteLine("Didn't see any video data..");
}

Count and Offset

This example searches for 'Best restaurants in Seattle' with an offset and limit to the number of results. Then it verifies number of results, and prints, name and URL of the first result.

C#
public static void WebResultsWithCountAndOffset(WebSearchAPI client)
{
    try
    {
        var webData = client.Web.SearchAsync
              (query: "Best restaurants in Seattle", offset: 10, count: 20).Result;
        Console.WriteLine("\r\nSearched for Query# \" Best restaurants in Seattle \"");

        if (webData?.WebPages?.Value?.Count > 0)
        {
            // find the first web page
            var firstWebPagesResult = webData.WebPages.Value.FirstOrDefault();

            if (firstWebPagesResult != null)
            {
                Console.WriteLine("Web 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 first web result!");
            }
        }
        else
        {
            Console.WriteLine("Didn't see any Web data..");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Encountered exception. " + ex.Message);
    }
}

Filters

This example searches on query 'school choice' with a response filter for news and then prints details.

C#
public static void WebSearchWithResponseFilter(WebSearchAPI client)
{

    try
    {
        IList<string> responseFilterstrings = new List<string>() { "news" };
        var webData = client.Web.SearchAsync
                      (query: "School choice", responseFilter: responseFilterstrings).Result;
        Console.WriteLine("\r\nSearched for Query# \" School choice \" with response filters \"news\"");

        //News
        if (webData?.News?.Value?.Count > 0)
        {
            // find the first news result
            var firstNewsResult = webData.News.Value.FirstOrDefault();

            if (firstNewsResult != null)
            {
                Console.WriteLine("News Results #{0}", webData.News.Value.Count);
                Console.WriteLine("First news result name: {0} ", firstNewsResult.Name);
                Console.WriteLine("First news result URL: {0} ", firstNewsResult.Url);
            }
            else
            {
                Console.WriteLine("Couldn't find first News results!");
            }
        }
        else
        {
            Console.WriteLine("Didn't see any News data..");
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine("Encountered exception. " + ex.Message);
    }
}

Answer Count and Promote Parameters

This example searches on query 'susan sarandon' with answerCount and promote parameters and prints details.

C#
public static void WebSearchWithAnswerCountPromoteAndSafeSearch(WebSearchAPI client)
{

    try
    {
        IList<string> promoteAnswertypeStrings = new List<string>() { "videos" };
        var webData = client.Web.SearchAsync(query: "susan sarandon", 
         answerCount: 2, promote: promoteAnswertypeStrings, safeSearch: SafeSearch.Strict).Result;
        Console.WriteLine("\r\nSearched for Query# \" susan sarandon \"");

        if (webData?.Videos?.Value?.Count > 0)
        {
            var firstVideosResult = webData.Videos.Value.FirstOrDefault();

            if (firstVideosResult != null)
            {
                Console.WriteLine("Video Results #{0}", webData.Videos.Value.Count);
                Console.WriteLine("First Video result name: {0} ", firstVideosResult.Name);
                Console.WriteLine("First Video result URL: {0} ", firstVideosResult.ContentUrl);
            }
            else
            {
                Console.WriteLine("Couldn't find videos results!");
            }
        }
        else
        {
            Console.WriteLine("Didn't see any data..");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Encountered exception. " + ex.Message);
    }
}

Next Steps

For more examples and code in other programming languages, see Bing Search SDK preview.

History

  • First edition

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)