Spread the love
In this tutorial we are going to see how to use the Bing Web Search API to get results. The Bing Web Search API is a RESTful service that provides instant answers to queries. Search results are easily configured to include web pages, images, videos, news, translations, and more. Besides the obvious search feature the Bing Search API supports the following features:
- Suggest search terms in real time
- Filter and restrict results by content type
- Hit highlighting for unicode characters
- Localize search results by country, region, and/or market
- Analyze search metrics with Bing Statistics
Prerequisites
To use the Bing Web Search API you need to create a Cognitive Services API account with access to the Bing Search APIs. If you don’t have an Azure subscription, you can create a free account.
Make a Search Request
To make a Search Request follow the steps below:
- Create a Console Application in Visual Studio 2017
- Add the following code:
using System; using System.Text; using System.Net; using System.IO; using System.Collections.Generic; namespace BingSearchDemo { class Program { // Replace the accessKey string value with your valid access key. const string accessKey = "enter key here"; const string uriBase = "https://api.cognitive.microsoft.com/bing/v7.0/search"; const string searchTerm = "Microsoft Cognitive Services"; // 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(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. /// </summary> 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; } } }
- Substitute the constant with the key from your Azure Subscription
- Run the code. The result is similar to the following json
eviewJSON { "Demo": { "_type": "SearchResponse", "webPages": { "webSearchUrl": "https://www.bing.com/search?q=codestories", "totalEstimatedMatches": 19000, "value": [ { "id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.0", "deepLinks": null, "dateLastCrawled": "2018-07-11T19:56:00Z", "about": null, "name": "Codestories", "url": "https://codestories.in/", "displayUrl": "https://codestories.in", "snippet": "Write an awesome description for your new site here. You can edit this line in _config.yml. It will appear in your document head meta (for Google search results) and in your feed.xml site description." }, { "id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.1", "deepLinks": [ { "name": "A New Career at 55", "url": "https://news.codecademy.com/" } ], "dateLastCrawled": "2018-08-17T22:56:00Z", "about": null, "name": "Codecademy Stories | Codecademy", "url": "https://www.codecademy.com/stories", "displayUrl": "https://www.codecademy.com/stories", "snippet": "Stories of people inspired by Codecademy to change their life through coding." }, { "id": "https://api.cognitive.microsoft.com/api/v7/#WebPages.2", "deepLinks": null, "dateLastCrawled": "2018-08-24T00:48:00Z", "about": null, "name": "Code.Stories() - girl in a binary world", "url": "http://www.codestories.gr/", "displayUrl": "www.codestories.gr", "snippet": "If you are working or want to know more about Serverless Computing check out this free e-book. Learn how to: Develop event-based handlers on a serverless architecture." }, ...