Share via


Quickstart: Use the Bing News Search client library

Warning

On October 30, 2020, the Bing Search APIs moved from Azure AI services to Bing Search Services. This documentation is provided for reference only. For updated documentation, see the Bing search API documentation. For instructions on creating new Azure resources for Bing search, see Create a Bing Search resource through the Azure Marketplace.

Use this quickstart to begin searching for news with the Bing News Search client library for C#. While Bing News Search has a REST API compatible with most programming languages, the client library provides an easy way to integrate the service into your applications. The source code for this sample can be found on GitHub.

Prerequisites

To set up a console application using the Bing News Search client library, browse to the Manage NuGet Packages option from the Solution Explorer in Visual Studio. Add the Microsoft.Azure.CognitiveServices.Search.NewsSearch package.

Create an Azure resource

Start using the Bing News Search API by creating one of the following Azure resources:

Bing Search v7 resource

  • Available through the Azure portal until you delete the resource.
  • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.

Multi-service resource

  • Available through the Azure portal until you delete the resource.
  • Use the same key and endpoint for your applications, across multiple Azure AI services.

Create and initialize a project

  1. Create a new C# console solution in Visual Studio. Then add the following into the main code file.

    using System;
    using System.Linq;
    using Microsoft.Azure.CognitiveServices.Search.NewsSearch;
    
  2. Create a variable for your API key, a search term, and then instantiate the news search client with it.

    var key = "YOUR-ACCESS-KEY";
    var searchTerm = "Quantum Computing";
    var client = new NewsSearchClient(new ApiKeyServiceClientCredentials(key));
    

Send a request, and parse the result

  1. Use the client to send a search request to the Bing News Search service:

    var newsResults = client.News.SearchAsync(query: searchTerm, market: "en-us", count: 10).Result;
    
  2. If any results were returned, parse them:

    if (newsResults.Value.Count > 0)
    {
        var firstNewsResult = newsResults.Value[0];
    
        Console.WriteLine($"TotalEstimatedMatches value: {newsResults.TotalEstimatedMatches}");
        Console.WriteLine($"News result count: {newsResults.Value.Count}");
        Console.WriteLine($"First news name: {firstNewsResult.Name}");
        Console.WriteLine($"First news url: {firstNewsResult.Url}");
        Console.WriteLine($"First news description: {firstNewsResult.Description}");
        Console.WriteLine($"First news published time: {firstNewsResult.DatePublished}");
        Console.WriteLine($"First news provider: {firstNewsResult.Provider[0].Name}");
    }
    
    else
    {
        Console.WriteLine("Couldn't find news results!");
    }
    Console.WriteLine("Enter any key to exit...");
    Console.ReadKey();
    

Next steps

Use this quickstart to begin searching for news with the Bing News Search client library for Java. While Bing News Search has a REST API compatible with most programming languages, the client library provides an easy way to integrate the service into your applications. The source code for this sample can be found on GitHub.

Prerequisites

Install the Bing News Search client library dependencies using Maven, Gradle, or another dependency management system. The Maven POM file requires the following declaration:

    <dependencies>
    <dependency>
        <groupId>com.microsoft.azure.cognitiveservices</groupId>
        <artifactId>azure-cognitiveservices-newssearch</artifactId>
        <version>0.0.1-beta-SNAPSHOT</version>
    </dependency>
    </dependencies>

Create an Azure resource

Start using the Bing News Search API by creating one of the following Azure resources:

Bing Search v7 resource

  • Available through the Azure portal until you delete the resource.
  • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.

Multi-service resource

  • Available through the Azure portal until you delete the resource.
  • Use the same key and endpoint for your applications, across multiple Azure AI services.

Create and initialize a project

Create a new Java project in your favorite IDE or editor, and import the following libraries.

import com.microsoft.azure.cognitiveservices.newssearch.*;
import com.microsoft.azure.cognitiveservices.newssearch.implementation.NewsInner;
import com.microsoft.azure.cognitiveservices.newssearch.implementation.NewsSearchAPIImpl;
import com.microsoft.azure.cognitiveservices.newssearch.implementation.TrendingTopicsInner;
import com.microsoft.rest.credentials.ServiceClientCredentials;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;

Create a search client and store credentials

  1. Create a method called getClient() that returns a new NewsSearchAPIImpl search client. Add your endpoint as the first parameter for the newNewsSearchAPIImpl object, and a new ServiceClientCredentials object to store your credentials.

    public static NewsSearchAPIImpl getClient(final String subscriptionKey) {
        return new NewsSearchAPIImpl("https://api.cognitive.microsoft.com/bing/v7.0/",
                new ServiceClientCredentials() {
                });
    }
    
  2. To create the ServiceClientCredentials object, override the applyCredentialsFilter() function. Pass a OkHttpClient.Builder to the method, and use the builder's addNetworkInterceptor() method to create your credentials for the client library call.

    new ServiceClientCredentials() {
        @Override
        public void applyCredentialsFilter(OkHttpClient.Builder builder) {
            builder.addNetworkInterceptor(
                    new Interceptor() {
                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = null;
                            Request original = chain.request();
                            // Request customization: add request headers.
                            Request.Builder requestBuilder = original.newBuilder()
                                    .addHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
                            request = requestBuilder.build();
                            return chain.proceed(request);
                        }
                    });
        }
    });
    

Send and receive a search request

  1. Create a method that calls getClient() and sends a search request to the Bing News Search service. Filter the search with the market and count parameters, then print information about the first news result: name, URL, publication date, description, provider name, and total number of estimated matches for your search.

    public static void newsSearch(String subscriptionKey)
    {
        NewsSearchAPIImpl client = getClient(subscriptionKey);
        String searchTerm = "Quantum Computing";
    
        NewsInner newsResults = client.searchs().list(searchTerm, null, null, null,
                null, null, 100, null, "en-us",
                null, null, null, null, null,
                null, null);
    
        if (newsResults.value().size() > 0)
        {
            NewsArticle firstNewsResult = newsResults.value().get(0);
    
            System.out.println(String.format("TotalEstimatedMatches value: %d", newsResults.totalEstimatedMatches()));
            System.out.println(String.format("News result count: %d", newsResults.value().size()));
            System.out.println(String.format("First news name: %s", firstNewsResult.name()));
            System.out.println(String.format("First news url: %s", firstNewsResult.url()));
            System.out.println(String.format("First news description: %s", firstNewsResult.description()));
            System.out.println(String.format("First news published time: %s", firstNewsResult.datePublished()));
            System.out.println(String.format("First news provider: %s", firstNewsResult.provider().get(0).name()));
        }
        else
        {
            System.out.println("Couldn't find news results!");
        }
    
    }
    
    
  2. Add your search method to a main() method to execute the code.

    public static void main(String[] args) {
        String subscriptionKey = "YOUR-SUBSCRIPTION-KEY";
        NewsSearchSDK.newsSearch(subscriptionKey);
    }
    

Next steps

Use this quickstart to begin searching for news with the Bing News Search client library for JavaScript. While Bing News Search has a REST API compatible with most programming languages, the client library provides an easy way to integrate the service into your applications. The source code for this sample can be found on GitHub.

Prerequisites

  • The latest version of Node.js.
  • The Bing News Search SDK for JavaScript
    • To install, run npm install @azure/cognitiveservices-newssearch
  • The CognitiveServicesCredentials class from @azure/ms-rest-azure-js package to authenticate the client.
    • To install, run npm install @azure/ms-rest-azure-js

Create an Azure resource

Start using the Bing News Search API by creating one of the following Azure resources:

Bing Search v7 resource

  • Available through the Azure portal until you delete the resource.
  • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.

Multi-service resource

  • Available through the Azure portal until you delete the resource.
  • Use the same key and endpoint for your applications, across multiple Azure AI services.

Create and initialize the application

  1. Create an instance of the CognitiveServicesCredentials. Create variables for your subscription key, and a search term.

    const CognitiveServicesCredentials = require('@azure/ms-rest-azure-js').CognitiveServicesCredentials;
    let credentials = new CognitiveServicesCredentials('YOUR-ACCESS-KEY');
    let search_term = 'Winter Olympics'
    
  2. instantiate the client:

    const NewsSearchAPIClient = require('@azure/cognitiveservices-newssearch');
    let client = new NewsSearchAPIClient(credentials);
    

Send a search query

  1. Use the client to search with a query term, in this case "Winter Olympics":

    client.newsOperations.search(search_term).then((result) => {
        console.log(result.value);
    }).catch((err) => {
        throw err;
    });
    

The code prints result.value items to the console without parsing any text. The results, if any per category, will include:

  • _type: 'NewsArticle'
  • _type: 'WebPage'
  • _type: 'VideoObject'
  • _type: 'ImageObject'

Next steps

Use this quickstart to begin searching for news with the Bing News Search client library for Python. While Bing News Search has a REST API compatible with most programming languages, the client library provides an easy way to integrate the service into your applications. The source code for this sample can be found on GitHub.

Prerequisites

It is recommended to use a virtual environment for your Python development. You can install and initialize the virtual environment with the venv module. You must install a virtualenv for Python 2.7. You can create a virtual environment with:

python -m venv mytestenv

You can install the Bing News Search client library dependencies with this command:

python -m pip install azure-cognitiveservices-search-newssearch

Create an Azure resource

Start using the Bing News Search API by creating one of the following Azure resources:

Bing Search v7 resource

  • Available through the Azure portal until you delete the resource.
  • Use the free pricing tier to try the service, and upgrade later to a paid tier for production.

Multi-service resource

  • Available through the Azure portal until you delete the resource.
  • Use the same key and endpoint for your applications, across multiple Azure AI services.

Create and initialize the application

  1. Create a new Python file in your favorite IDE or editor, and import the following libraries. Create a variable for your subscription key, and your search term.

    from azure.cognitiveservices.search.newssearch import NewsSearchClient
    from msrest.authentication import CognitiveServicesCredentials
    subscription_key = "YOUR-SUBSCRIPTION-KEY"
    endpoint = "YOUR-ENDPOINT"
    search_term = "Quantum Computing"
    

Initialize the client and send a request

  1. Create an instance of CognitiveServicesCredentials.

    client = NewsSearchClient(endpoint=endpoint, credentials=CognitiveServicesCredentials(subscription_key))
    
  2. Send a search query to the News Search API, store the response.

    news_result = client.news.search(query=search_term, market="en-us", count=10)
    

Parse the response

If any search results are found, print the first webpage result:

if news_result.value:
    first_news_result = news_result.value[0]
    print("Total estimated matches value: {}".format(
        news_result.total_estimated_matches))
    print("News result count: {}".format(len(news_result.value)))
    print("First news name: {}".format(first_news_result.name))
    print("First news url: {}".format(first_news_result.url))
    print("First news description: {}".format(first_news_result.description))
    print("First published time: {}".format(first_news_result.date_published))
    print("First news provider: {}".format(first_news_result.provider[0].name))
else:
    print("Didn't see any news result data..")

Next steps