Click here to Skip to main content
15,886,737 members
Articles / Programming Languages / C# 7.0

Getting Started with the Bing Search APIs

Rate me:
Please Sign up or sign in to vote.
4.80/5 (6 votes)
8 Feb 2018MIT4 min read 18.3K   277   7  
Basic code scenarios using Bing Search API endpoints to search the Web

Introduction

Bing Search API is a set of REST interfaces that find web pages, news, images, videos, entities, related searches, spelling corrections, and more in response to queries from any programming language that can generate a web request. Applications that need information from the web use the Bing Search APIs to get results in JSON format adaptable to their requirements.

Bing Search APIs include specialized endpoints for the following types:

  • Bing Web Search API - Includes Web pages and all the other types mentioned below, 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

To experiment with the Bing Search API, you'll need an API access key, which is available at Azure: Try Cognitive Services.

Basic Programmatic Search

For simplicity, the following code sample uses the Bing Web Search API. The other endpoints use similar procedures. The Bing Web Search API is useful for finding web resources such as sites, images, videos, news, and entities for a given query. You can write code in any language that can send a 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.

With an access key, the basic code scenario in Java might look like this:

Java
// 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= "Code Project Top Articles";

// 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();

See the Java project source code for details of this excerpt.

Parsing results is discussed in the final section of this article.

The following code snippet shows the request code sequence in C#.

C#
// Replace the accessKey string value with your valid access key.
const string accessKey = "Enter key here";

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

// Replace the searchQuery below to search for your query
const string searchQuery = "Code Project Top Articles";

// Construct the URI of the search request
var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);

// Create the Web request.
WebRequest request = HttpWebRequest.Create(uriQuery);

// Set the access key header.
request.Headers["Ocp-Apim-Subscription-Key"] = accessKey;
// Send the request.
HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;

// Read the response.
string json = new StreamReader(response.GetResponseStream()).ReadToEnd();

See the C# project source code for details of this excerpt.

Parsing results is discussed in the final section of this article.

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. The web search API endpoint follows:

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, following, 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, following, 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 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:

Java
// 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 for JSON parsing:

C#
/// 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();
}

For more examples, see the following github repo: cognitive-services-REST-api-samples.

History

  • 20th December, 2017: First draft
  • Added link to access key page

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Technical Writer Steyer Associates
United States United States
http://mikedodaro.net

Comments and Discussions

 
-- There are no messages in this forum --