Getting Started with the Bing Search APIs

View: 140    Dowload: 0   Comment: 0   Post by: admin   Category: Javascript   Fields: Other

Download  getting-started-with-the-bing.rar (594.60 KB)

You need to Sign In to download the file getting-started-with-the-bing.rar
If you do not have an account then Sign up for free here

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:

// 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#.

// 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:

// 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:

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

 

Getting Started with the Bing Search APIs

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.

Posted on 08-03-2018 

Comment:

To comment you must be logged in members.

Files with category

  • Angular 6 Starter with Laravel 5.6 API Service

    Angular 6 Starter with Laravel 5.6 API Service

    View: 5    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    Angular 6 and Laravel 5.6 This project is a starter for creating interface with Angular using bootstrap && css && sass and using Laravel 5.6 for api requests. Demo Installation This project is divided in two parts (projects) and before use them you...

  • Simple Richtext Editor Based on pellJS

    Simple Richtext Editor Based on pellJS

    View: 5    Download: 0   Comment: 0

    Category: Javascript     Fields: none

    A simple visual editor for websites using the pell javascipt. It also has the option to switch between visual editor mode and source code mode. I will upload an update for new functionality soon. Source Code Editor Visual Editor

  • Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    Data Visualization for BI: How to Design Layouts for .NET Financial Reports

    View: 15    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    With the Active Reports Server, you can have a multi-tenant environment where users from various departments, companies, or other specifications can log in, view their reports (and only their reports), export the data, or set up a distribution...

  • AngularJS and REST API

    AngularJS and REST API

    View: 179    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    This is a tutorial for those interested in a quick introduction to AngularJS and REST API. We will build the familiar Periodic Table of the Elements found in every chemistry textbook, and allow the user to select a Chemical Element by clicking on...

  • Collective Intelligence, Recommending Items Based on Similar Users' Taste

    Collective Intelligence, Recommending Items Based on Similar Users' Taste

    View: 143    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Using Collaborative Filtering to find people who share tastes, and for making automatic recommendations based on things that other people like.

  • Think Like a Bird for Better Parallel Programming

    Think Like a Bird for Better Parallel Programming

    View: 134    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Coding an application to run in parallel is hard, right? I mean, it must be hard or we’d see parallel programs everywhere. All we'd see are slick parallel apps that use every available core effortlessly. Instead multi-threaded apps are the exception...

  • Getting Started with the Bing Search APIs

    Getting Started with the Bing Search APIs

    View: 140    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    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...

  • Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    Brief Introduction of SocketPro High Performance and Scalable Persistent Message Queue

    View: 458    Download: 0   Comment: 0

    Category: Javascript     Fields: Other

    Continuous in-line request/result batching, real-time stream sending/processing, asynchronous data transferring and parallel computation for best performance and scalability

 
File suggestion for you
File top downloads
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd