This article shows you how use the Bing Search API, part of Microsoft Cognitive Services on Azure. While this article employs C#, the API is a RESTful Web service compatible with any programming language that can make HTTP requests and parse JSON.
The example code was written in C# as a .NET Core application, with minimal external dependencies, so you can also run it on Linux or Mac OS X using Mono.
Prerequisites
You must have a
Cognitive Services API account with
Bing Search APIs. The
free trial is sufficient for this quickstart. You will need the access key provided when you activate your free trial, or you may use a paid subscription key from your Azure dashboard.
Bing News search
What is Bing News search?
The Bing News Search API is a RESTful web service, making it easy to call from any programming language that can make HTTP requests and parse JSON. You can use the service using either the REST API, or the SDK.
-
Create a Cognitive Services API account with access to the Bing Search APIs. If you don’t have an Azure subscription, you can
create an account for free.
-
Send a request to the API, with a valid search query.
-
Process the API response by parsing the returned JSON message.
- Create a new Console solution in Visual Studio (the Community Edition is fine).
- Replace Program.cs with the code provided below.
- Replace the
accessKey value with an access key valid for your subscription.
- Run the program.
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Generic;
namespace BingNewsSearchCSharpCore
{
class Program
{
const string accessKey = "enter key here";
const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/news/search";
const string searchTerm = "Microsoft";
struct SearchResult
{
public String jsonResult;
public Dictionary relevantHeaders;
}
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("Searching news for: " + searchTerm);
SearchResult result = BingNewsSearch(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));
Console.Write("\nPress Enter to exit ");
Console.ReadLine();
}
static SearchResult BingNewsSearch(string searchQuery)
{
var uriQuery = uriBase + "?q=" + Uri.EscapeDataString(searchQuery);
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();
var searchResult = new SearchResult();
searchResult.jsonResult = json;
searchResult.relevantHeaders = new Dictionary();
foreach (String header in response.Headers)
{
if (header.StartsWith("BingAPIs-") || header.StartsWith("X-MSEdge-"))
searchResult.relevantHeaders[header] = response.Headers[header];
}
return searchResult;
}
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;
int offset = 0;
int indentLength = 3;
foreach (char ch in json)
{
switch (ch)
{
case '"':
if (!ignore) quote = !quote;
break;
case '\'':
if (quote) ignore = !ignore;
break;
}
if (quote)
sb.Append(ch);
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 (ch != ' ') sb.Append(ch);
break;
}
}
}
return sb.ToString().Trim();
}
}
}
Response
A successful response is returned in JSON, as shown in the following example:
{
"_type": "News",
"readLink": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/news\/search?q=Microsoft",
"totalEstimatedMatches": 36,
"sort": [
{
"name": "Best match",
"id": "relevance",
"isSelected": true,
"url": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/news\/search?q=Microsoft"
},
{
"name": "Most recent",
"id": "date",
"isSelected": false,
"url": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/news\/search?q=Microsoft&sortby=date"
}
],
"value": [
{
"name": "Microsoft to open flagship London brick-and-mortar retail store",
"url": "http:\/\/www.contoso.com\/article\/microsoft-to-open-flagshi...",
"image": {
"thumbnail": {
"contentUrl": "https:\/\/www.bing.com\/th?id=ON.F9E4A49EC010417...",
"width": 220,
"height": 146
}
},
"description": "After years of rumors about Microsoft opening a brick-and-mortar...",
"about": [
{
"readLink": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/entiti...",
"name": "Microsoft"
},
{
"readLink": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/entit...",
"name": "London"
}
],
"provider": [
{
"_type": "Organization",
"name": "Contoso"
}
],
"datePublished": "2017-09-21T21:16:00.0000000Z",
"category": "ScienceAndTechnology"
},
. . .
{
"name": "Microsoft adds Availability Zones to its Azure cloud platform",
"url": "https:\/\/contoso.com\/2017\/09\/21\/microsoft-adds-availability...",
"image": {
"thumbnail": {
"contentUrl": "https:\/\/www.bing.com\/th?id=ON.0AE7595B9720...",
"width": 700,
"height": 466
}
},
"description": "Microsoft has begun adding Availability Zones to its...",
"about": [
{
"readLink": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/entities\/a093e9b...",
"name": "Microsoft"
},
{
"readLink": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/entities\/cf3abf7d-e379-...",
"name": "Windows Azure"
},
{
"readLink": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/entities\/9cdd061c-1fae-d0...",
"name": "Cloud"
}
],
"provider": [
{
"_type": "Organization",
"name": "Contoso"
}
],
"datePublished": "2017-09-21T09:01:00.0000000Z",
"category": "ScienceAndTechnology"
}
]
}