Bing Search API Tutorial

Bing Search APIs include specialized endpoints for the following types:

  • Bing Web Search API - Includes Web pages and related types, such as images, videos, news, related searches, spelling corrections, etc.
  • Bing News Search API - Provides news items relevant to user's query. It also provides news for specific categories, such as health, sports, etc., and news trending at any point in time.
  • Bing Video Search API - Returns relevant videos. It also provides endpoints for similar videos and trending videos.
  • Bing Image Search API - Similar to video search API, this API has 3 endpoints: image search, similar images, and trending images.
  • Bing Entity Search API - Summary information about people, places, organizations, products, and other concepts.
  • Bing Custom Search API - Supports customized search to get results from specific sources on the web: domains, subsites, or webpages.
  • Bing Autosuggest API - Provides query completion capability for partial strings.
  • Bing Spell Check API - Provides spelling and Grammar correction for short strings or large paragraphs

Basic Programmatic Search

The Bing Web Search API uses methods that are similar to other Bing endpoints. The Web Search API finds web resources such as sites, images, videos, news, and entities for a given query. You can write code in any language that can send an HTTP GET request to the following endpoint:

https://api.cognitive.microsoft.com/bing/v7.0/search?q=<searchString>

Every request to the Bing Web Search API must include a header that contains the Ocp-Apim-Subscription-Key, which is your private access key. Access Keys are available for exploring these APIs.

The following example in Java shows the basic request scenario:

// Replace the accessKey string value with your valid access key.
static String accessKey = "Enter key here";

static String host = "https://api.cognitive.microsoft.com";
static String path = "/bing/v7.0/search";

// Replace the following searchQuery with your query string.
static String searchQuery= "YOUR QUERY TEXT HERE";

// construct URL of search request (endpoint + query string)
URL url = new URL(host + path + "?q=" +  URLEncoder.encode(searchQuery, "UTF-8"));
HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();

// Set the access key header.
connection.setRequestProperty("Ocp-Apim-Subscription-Key", accessKey);

// Receive JSON body
InputStream stream = connection.getInputStream();
String response = new Scanner(stream).useDelimiter("\\A").next();

// Construct result object for return.
SearchResults results = new SearchResults(new HashMap<String, String>(), response);
stream.close();

The complete Java source code is available. Parsing results is discussed in a following section of this article.

AngularJS News Search

In contrast to the Java above, the following complete code example uses the Bing News Search API to generate the request and parse the results with the AngularJS framework:

'use strict';

let https = require('https');

// Replace the subscriptionKey string value with your valid subscription key.
let subscriptionKey = 'Your-subscription-key';

let host = 'api.cognitive.microsoft.com';
let path = '/bing/v7.0/news/search';

// Query text
let term = 'YOUR QUERY TEXT HERE';

let bing_news_search = function (search) {
    console.log('Searching news for: ' + term);
    let request_params = {
        method: 'GET',
        hostname: host,
        path: path + '?q=' + encodeURIComponent(search),
        headers: {
            'Ocp-Apim-Subscription-Key': subscriptionKey,
        }
    };

    let req = https.request(request_params, response_handler);
    req.end();
}

// Set up response_handler identified by the parameter of the request initialized previously.
let response_handler = function (response) {
    let body = '';
    response.on('data', function (d) {
        body += d;
    });
    // On return of the response, this function parses and logs results to the console.
    response.on('end', function () {
        console.log('\nRelevant Headers:\n');
        for (var header in response.headers)   // Step through the headers.
            // header keys are lower-cased by Node.js
            if (header.startsWith("bingapis-") || header.startsWith("x-msedge-"))
                console.log(header + ": " + response.headers[header]);  // Log response headers to the console.
        body = JSON.stringify(JSON.parse(body), null, '  ');  // Parse the JSON text of body of the response.
        console.log('\nJSON Response:\n');
        console.log(body);  // Print response body to the console.
    });
    response.on('error', function (e) {
        console.log('Error: ' + e.message);  // On the event of an error, log the message to the console.
    });
};

bing_news_search(term);

Endpoints for other Bing APIs

This section summarizes endpoints for various Bing Search APIs.

Bing Web Search API

As discussed in the previous example, the web search endpoint returns webpages, news, images, videos, entities, and related searches along with spelling corrections. Here's an example of an HTTP GET request to the Bing web search API endpoint:

GET https://api.cognitive.microsoft.com/bing/v7.0/search?q="Code+Project+Top+Articles"

Bing News Search API

The Bing News Search API supports three endpoints.

The following endpoint returns news articles for a given query:

GET https://api.cognitive.microsoft.com/bing/v7.0/news/search?q="Artificial+Intelligence"

The second endpoint returns news articles for a given category such as health, business, sports, etc:

GET https://api.cognitive.microsoft.com/bing/v7.0/news?category="health"

Finally, the third endpoint returns news topics that are currently trending on social networks:

GET https://api.cognitive.microsoft.com/bing/v7.0/news/trendingtopics

Bing Video Search API

The Bing Video Search API has three endpoints. The following endpoint returns videos for a given query:

GET https://api.cognitive.microsoft.com/bing/v7.0/videos/search?q="sushi+recipe"

The second video endpoint can be used to get videos similar to the one identified by Your_Video_Id. The "Modules" parameter is used to get the videos related to the video mentioned in the "id" parameter.

GET https://api.cognitive.microsoft.com/bing/v7.0/videos/details?modules="RelatedVideos" &id="Your_Video_Id"

The final video endpoint returns videos that are trending at the moment. Results are separated into different categories, for example, based on noteworthy people or events.

GET https://api.cognitive.microsoft.com/bing/v7.0/videos/trending

Bing Image Search API

Bing Image Search API has three endpoints, which are similar in functionality to the Bing Video Search endpoints The following endpoint returns images relevant to a given query.

GET https://api.cognitive.microsoft.com/bing/v7.0/images/search?q="Quantum+Computer"

The second endpoint provides insights about a given image, such as similar images or the source of a given image. The "Modules" parameter can be used to derive various insights. The following request searches for images similar to that at a given image URL.

GET https://api.cognitive.microsoft.com/bing/v7.0/images/details?Modules="SimilarImages"&imgURL="YOUR_URL"

The final image endpoint returns trending images.

GET https://api.cognitive.microsoft.com/bing/v7.0/images/trending

Bing Entity Search

Bing Entity Search returns results about a person, place, thing, or conceptual identity. To request entity search results, send a request to the following endpoint. Use the headers and the URL parameter ?q=" ".

GET https://api.cognitive.microsoft.com/bing/v7.0/entities?q="Yosemite+National+Park"

Bing Custom Search

Bing Custom Search returns results based on sources specified by the user. For information about defining sources, see Bing Custom Search. As with other endpoints, the query is defined by the URL parameter: ?q=" ".

GET https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?q="Redmond+Real+Estate"

Bing Autosuggest

Bing Autosuggest takes a partial query and returns suggestions for other queries based on the user's past queries or tending queries. The results can be used to autocomplete phrases or terms.

GET https://api.cognitive.microsoft.com/bing/v7.0/Suggestions?q="cognitive"

Bing Spell Check

Bing Spell Check takes a text and checks spelling and grammar. The response returned by the following endpoint includes the original text and token suggestions that correct it.

GET https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?text="Th is contains erroneous spll ing and grammer"

JSON Search Results

The Bing Search API returns results as JSON objects to be parsed as text. You can use the following code to parse the JSON responses for console display:

Java sample for JSON parsing:

// pretty-printer for JSON; uses GSON parser to parse and re-serialize results.
public static String prettify(String json_text) {
    JsonParser parser = new JsonParser();
    JsonObject json = parser.parse(json_text).getAsJsonObject();
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    return gson.toJson(json);
}

C# sample JSON Parsing

The following C# example uses the web search endpoint and includes code that parses JSON results.

using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;

namespace BingSearchApisQuickstart
{
    class Program
    {
        // Replace the accessKey string value with your valid access key.
        const string accessKey = "Your-subscription-key";

        // Query string:
        const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/search";

        const string searchTerm = "Yosemite National Park";

        // Used to return search results including relevant headers
        struct SearchResult
        {
            public String jsonResult;
            public Dictionary<String, String> relevantHeaders;
        }

        static void Main()
        {
            Console.OutputEncoding = System.Text.Encoding.UTF8;

            if (accessKey.Length == 32)
            {
                Console.WriteLine("Searching the Web for: " + searchTerm);

                SearchResult result = BingWebSearch(searchTerm);

                Console.WriteLine("\nRelevant HTTP Headers:\n");
                foreach (var header in result.relevantHeaders)
                    Console.WriteLine(header.Key + ": " + header.Value);

                Console.WriteLine("\nJSON Response:\n");
                Console.WriteLine(JsonPrettyPrint(result.jsonResult));
            }
            else
            {
                Console.WriteLine("Invalid Bing Search API subscription key!");
                Console.WriteLine("Please paste yours into the source code.");
            }

            Console.Write("\nPress Enter to exit ");
            Console.ReadLine();
        }

        /// <summary>
        /// Performs a Bing Web search and return the results as a SearchResult.
        /// </summar>
        static SearchResult BingWebSearch(string searchQuery)
        {
            // Construct the URI of the search request
            var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);

            // Perform the Web request and get the response
            WebRequest request = HttpWebRequest.Create(uriQuery);
            request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
            HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
            string json = new StreamReader(response.GetResponseStream()).ReadToEnd();

            // Create result object for return
            var searchResult = new SearchResult()
            {
                jsonResult = json,
                relevantHeaders = new Dictionary<String, String>()
            };

            // Extract Bing HTTP headers
            foreach (String header in response.Headers)
            {
                if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
                    searchResult.relevantHeaders[header] = response.Headers[header];
            }

            return searchResult;
        }

        ///  <summary >
        /// Formats the given JSON string by adding line breaks and indents.
        ///  </summary>
        ///  <param name="json">The raw JSON string to format. </param>
        /// <returns>The formatted JSON string. </returns>
        static string JsonPrettyPrint(string json)
        {
            if (string.IsNullOrEmpty(json))
                return string.Empty;

            json = json.Replace(Environment.NewLine, "").Replace("\t", "");

            StringBuilder sb = new StringBuilder();
            bool quote = false;
            bool ignore = false;
            char last = ' ';
            int offset = 0;
            int indentLength = 2;

            foreach (char ch in json)
            {
                switch (ch)
                {
                    case '"':
                        if (!ignore) quote = !quote;
                        break;
                    case '\\':
                        if (quote  & & last != '\\') ignore = true;
                        break;
                }

                if (quote)
                {
                    sb.Append(ch);
                    if (last == '\\' & & ignore) ignore = false;
                }
                else
                {
                    switch (ch)
                    {
                        case '{':
                        case '[':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', ++offset * indentLength));
                            break;
                        case '}':
                        case ']':
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', --offset * indentLength));
                            sb.Append(ch);
                            break;
                        case ',':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', offset * indentLength));
                            break;
                        case ':':
                            sb.Append(ch);
                            sb.Append(' ');
                            break;
                        default:
                            if (quote || ch != ' ') sb.Append(ch);
                            break;
                    }
                }
                last = ch;
            }

            return sb.ToString().Trim();
        }
    }
}
 

Comments (1)