Bing Search API
The Bing Search API enables developers embed search results in Web sites or applications by using JSON or XML and add search functionality to your Web site. The Bing Search APIs v7 include the Bing Web Search API v7, Bing News Search API v7, Bing Video Search API v7, Bing Image Search API v7, Bing Autosuggest API v7, and Bing Spell Check API v7.
Bing Search API v7 includes the following services:
- Bing Web Search API gives enhanced search details of Web documents.
- Bing Image Search API can include image metadata, publishing Web site info, thumbnails, full image URLs, and more.
- Bing Video Search API includes metadata such as view count, video length, encoding format, the creator, and more.
- Bing News Search API includes trending topics, dates images were added, authoritative images of the news article, related news and categories, provider information, and article URLs.
- Bing Autosuggest API adds intelligent type-ahead capabilities to an app or Web site.
- Bing Spell Check API helps correct spelling errors as well as recognizing the difference among names, brand names, and slang.
Bing Web Search API
The Bing Web Search API gives enhanced search details of Web documents. It retrieves Web pages that are indexed by the Bing Web Search API and narrows down the results by freshness and result type.
Bing Image Search API
The Bing Image Search API can include image metadata, publishing Web site info, thumbnails, full image URLs, and more. Bing Image Search API scours the Web for images with new sorting and filtering options that simplify finding results in image searches.
Bing Video Search API
The Bing Video Search API finds videos across the Web. The Bing Video Search API includes metadata such as view count, video length, encoding format, the creator, and more.
Bing News Search API
The Bing News Search API includes trending topics, dates images were added, authoritative images of the news article, related news and categories, provider information, and article URLs. The Bing News Search API includes new sorting and filtering options that simplify finding specific results in trending news topics.
Bing Autosuggest API
The Bing Autosuggest API helps users complete queries faster by adding intelligent type-ahead capabilities to your app or Web site.
Bing Spell Check API
The Bing Spell Check API helps correct spelling errors as well as recognize the difference among names, brand names, and slang.
Getting Started with the Bing Search APIs
To get started with the Bing Search APIs v7, navigate to Microsoft Azure:
Figure 1: The Bing Search APIs on Azure
Click the Get API Key button on the right side. A window similar to what’s shown in Figure 2 will pop up and you would have to agree and accept the terms and conditions for Microsoft Cognitive Services. For more information regarding Cognitive Services, read through these earlier articles of mine:
Figure 2: Cognitive Services
You then will be given the appropriate API Keys and Endpoints to use in your .NET apps on the next page.
Open Visual Studio and create either a C# or VB.NET Console application.
Add the following namespaces to your class. I’ll show you both the C# and Visual Basic versions of all the following code snippets.
C#:
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text;
VB.NET:
Imports System Imports System.Collections.Generic Imports System.IO Imports System.Net Imports System.Text
Add the following objects to your class. They represent the API key, the correct endpoint for whichever Bing Search API you want to use, and the search term.
C#:
const string strKey = "548347d13550423799f328245051dee4"; const string strURL = "https://api.cognitive.microsoft.com/ bing/v7.0/suggestions"; const string strSearch = "CodeGuru";
VB.NET:
Const strKey As String = "548347d13550423799f328245051dee4" Const strURL As String = _ "https://api.cognitive.microsoft.com/bing/v7.0/suggestions" Const strSearch As String = "CodeGuru"
Add a structure to hold the Result:
C#:
struct SearchResult { public String strJSON; public Dictionary<String, String> dcHeaders; }
VB.NET:
Structure SearchResult Public strJSON As String Public dcHeaders As Dictionary(Of String, String) End Structure
Add the function to search Bing for the specified item.
C#:
static SearchResult SearchBing(string strQuery) { var uriQuery = strURL + "?q=" + Uri.EscapeDataString(strQuery); WebRequest wbReq = HttpWebRequest.Create(uriQuery); wbReq.Headers["Ocp-Apim-Subscription-Key"] = strKey; HttpWebResponse hResp = (HttpWebResponse)wbReq.GetResponseAsync().Result; string strJSON = new StreamReader(hResp.GetResponseStream()).ReadToEnd(); var varRes = new SearchResult() { strJSON = strJSON, dcHeaders = new Dictionary<String, String>() }; foreach (String strHead in hResp.Headers) { if (strHead.StartsWith("BingAPIs-") || strHead.StartsWith("X-MSEdge-")) { varRes.dcHeaders[strHead] = hResp.Headers[strHead]; } } return varRes; }
VB.NET:
Private Function SearchBing(ByVal strQuery As String) As _ SearchResult Dim uriQuery = strURL & "?q=" + _ Uri.EscapeDataString(strQuery) Dim wbReq As WebRequest = HttpWebRequest.Create(uriQuery) wbReq.Headers("Ocp-Apim-Subscription-Key") = strKey Dim hResp As HttpWebResponse = CType _ (wbReq.GetResponseAsync().Result, HttpWebResponse) Dim strJSON As String = New StreamReader _ (hResp.GetResponseStream()).ReadToEnd() Dim varRes = New SearchResult() With {.strJSON = strJSON, _ .dcHeaders = New Dictionary(Of String, String)()} For Each strHead As String In hResp.Headers If strHead.StartsWith("BingAPIs-") OrElse _ strHead.StartsWith("X-MSEdge-") Then varRes.dcHeaders(strHead) = hResp.Headers(strHead) End If Next Return varRes End Function
Display the JSON result properly.
C#:
static string PrintResult(string strInput) { if (string.IsNullOrEmpty(strInput)) { return string.Empty; } strInput = strInput.Replace(Environment.NewLine, "") .Replace("\t", ""); StringBuilder sbResult = new StringBuilder(); bool blnQuote = false; bool blnIgnore = false; char chLast = ' '; int intStart = 0; int intIndent = 2; foreach (char chr in strInput) { switch (chr) { case '"': if (!blnIgnore) blnQuote = !blnQuote; break; case '\\': if (blnQuote && chLast != '\\') blnIgnore = true; break; } if (blnQuote) { sbResult.Append(chr); if (chLast == '\\' && blnIgnore) blnIgnore = false; } else { switch (chr) { case '{': case '[': sbResult.Append(chr); sbResult.Append(Environment.NewLine); sbResult.Append(new string(' ', ++intStart * intIndent)); break; case '}': case ']': sbResult.Append(Environment.NewLine); sbResult.Append(new string(' ', --intStart * intIndent)); sbResult.Append(chr); break; case ',': sbResult.Append(chr); sbResult.Append(Environment.NewLine); sbResult.Append(new string(' ', intStart * intIndent)); break; case ':': sbResult.Append(chr); sbResult.Append(' '); break; default: if (blnQuote || chr != ' ') { sbResult.Append(chr); } break; } } chLast = chr; } return sbResult.ToString().Trim(); }
VB.NET:
Private Function PrintResult(ByVal strInput As String) As String If String.IsNullOrEmpty(strInput) Then Return String.Empty End If strInput = strInput.Replace(Environment.NewLine, "") _ .Replace(vbTab, "") Dim sbResult As StringBuilder = New StringBuilder() Dim blnQuote As Boolean = False Dim blnIgnore As Boolean = False Dim chLast As Char = " "c Dim intStart As Integer = 0 Dim intIndent As Integer = 2 For Each chr As Char In strInput Select Case chr Case """" If Not blnIgnore Then blnQuote = Not blnQuote Case "\"c If blnQuote AndAlso chLast <> "\"c Then _ blnIgnore = True End Select If blnQuote Then sbResult.Append(chr) If chLast = "\"c AndAlso blnIgnore Then blnIgnore = _ False Else Select Case chr Case "{"c, "["c sbResult.Append(chr) sbResult.Append(Environment.NewLine) sbResult.Append(New String(" "c, _ System.Threading.Interlocked.Increment(intStart) _ * intIndent)) Case "}"c, "]"c sbResult.Append(Environment.NewLine) sbResult.Append(New String(" "c, System.Threading. _ Interlocked.Decrement(intStart) * intIndent)) sbResult.Append(chr) Case ","c sbResult.Append(chr) sbResult.Append(Environment.NewLine) sbResult.Append(New String(" "c, intStart * _ intIndent)) Case ":"c sbResult.Append(chr) sbResult.Append(" "c) Case Else If blnQuote OrElse chr <> " "c Then sbResult.Append(chr) End If End Select End If chLast = chr Next Return sbResult.ToString().Trim() End Function
Put all into motion.
C#:
static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; if (strKey.Length == 32) { Console.WriteLine("Search for: " + strSearch + " in progress"); SearchResult strRes = SearchBing(strSearch); Console.WriteLine(PrintResult(strRes.strJSON)); } else { Console.WriteLine("Invalid Bing Search API key"); } Console.ReadLine(); }
VB.NET:
Sub Main() Console.OutputEncoding = System.Text.Encoding.UTF8 If strKey.Length = 32 Then Console.WriteLine("Search for: " & strSearch & " _ in progress") Dim strRes As SearchResult = SearchBing(strSearch) Console.WriteLine(PrintResult(strRes.strJSON)) Else Console.WriteLine("Invalid Bing Search API key") End If Console.ReadLine() End Sub
The code for this article is available on GitHub:
Conclusion
From a personal perspective: I wasn’t a big fan of Bing, but Bing and Microsoft keep making it more and more enticing to switch to it. With the AI, capabilities in Bing Microsoft are miles ahead of other search engines. In a few years’ time, all of these functionalities included in Bing will become commonplace in all search engines.