Quickstart: Use the Bing Autosuggest 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.
Get started with the Bing Autosuggest client library for .NET. Follow these steps to install the package and try out the example code for basic tasks.
Use the Bing Autosuggest client library for .NET to get search suggestions based on partial query strings.
Reference documentation | Library source code | Package (NuGet) | Sample code
Prerequisites
- An Azure subscription. If you don't already have an Azure subscription, you can create one for free.
- The current version of .NET Core.
Create an Azure resource
Start using the Bing Autosuggest API by creating one of the following Azure resources.
Bing Autosuggest 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.
- Bing Autosuggest is also offered in paid tiers of the Bing Search v7 resource.
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 environment variables
Note
The endpoints for resources created after July 1, 2019 use the custom subdomain format shown below. For more information and a complete list of regional endpoints, see Custom subdomain names for Azure AI services.
Using your key and endpoint from the resource you created, create two environment variables for authentication:
AUTOSUGGEST_SUBSCRIPTION_KEY
: The resource key for authenticating your requests.AUTOSUGGEST_ENDPOINT
: The resource endpoint for sending API requests. It should look like this:https://<your-custom-subdomain>.api.cognitive.microsoft.com
.
Use the instructions for your operating system.
setx AUTOSUGGEST_SUBSCRIPTION_KEY <replace-with-your-autosuggest-api-key>
setx AUTOSUGGEST_ENDPOINT <replace-with-your-autosuggest-api-endpoint>
After you add the environment variable, restart the console window.
Create a new C# application
Create a new .NET Core application in your preferred editor or IDE.
In a console window (such as cmd, PowerShell, or Bash), use the dotnet new
command to create a new console app with the name bing-autosuggest-quickstart
. This command creates a simple "Hello World" C# project with a single source file: program.cs.
dotnet new console -n bing-autosuggest-quickstart
Change your directory to the newly created app folder. You can build the application with:
dotnet build
The build output should contain no warnings or errors.
...
Build succeeded.
0 Warning(s)
0 Error(s)
...
From the project directory, open the program.cs file in your preferred editor or IDE. Add the following using
directives:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
In the Program
class, create variables for your resource's Azure endpoint and key. If you created the environment variable after you launched the application, you'll need to close and reopen the editor, IDE, or shell running it to access the variable.
private const string key_var = "AUTOSUGGEST_SUBSCRIPTION_KEY";
private static readonly string subscription_key = Environment.GetEnvironmentVariable(key_var);
// Note you must use the same region as you used to get your subscription key.
private const string endpoint_var = "AUTOSUGGEST_ENDPOINT";
private static readonly string endpoint = Environment.GetEnvironmentVariable(endpoint_var);
In the application's Main
method, add the following method calls, which you'll define later.
static void Main(string[] args)
{
Task.WaitAll(RunQuickstart());
Console.WriteLine("Press any key to exit.");
Console.Read();
}
Install the client library
Within the application directory, install the Bing Autosuggest client library for .NET with the following command:
dotnet add package Microsoft.Azure.CognitiveServices.Search.AutoSuggest --version 2.0.0
If you're using the Visual Studio IDE, the client library is available as a downloadable NuGet package.
Code examples
These code snippets show you how to do the following tasks with the Bing Autosuggest client library for .NET:
Authenticate the client
Note
This quickstart assumes you've created an environment variable for your Bing Autosuggest key, named AUTOSUGGEST_SUBSCRIPTION_KEY
, and one for your endpoint, named AUTOSUGGEST_ENDPOINT
.
In a new asynchronous method, instantiate a client with your endpoint and key. Create an ApiKeyServiceClientCredentials object with your key, and use it with your endpoint to create an AutosuggestClient object.
async static Task RunQuickstart()
{
// Generate the credentials and create the client.
var credentials = new Microsoft.Azure.CognitiveServices.Search.AutoSuggest.ApiKeyServiceClientCredentials(subscription_key);
var client = new AutoSuggestClient(credentials, new System.Net.Http.DelegatingHandler[] { })
{
Endpoint = endpoint
};
}
Send an Autosuggest request
In the same method, use the client's AutoSuggestMethodAsync method to send a query to Bing. Then, iterate over the Suggestions response, and print the first suggestion.
var result = await client.AutoSuggestMethodAsync("xb");
var groups = result.SuggestionGroups;
if (groups.Count > 0) {
var group = groups[0];
Console.Write("First suggestion group: {0}\n", group.Name);
var suggestions = group.SearchSuggestions;
if (suggestions.Count > 0)
{
Console.WriteLine("First suggestion:");
Console.WriteLine("Query: {0}", suggestions[0].Query);
Console.WriteLine("Display text: {0}", suggestions[0].DisplayText);
}
else
{
Console.WriteLine("No suggestions found in this group.");
}
}
else
{
Console.WriteLine("No suggestions found.");
}
Run the application
Run the application from your application directory with the dotnet run
command.
dotnet run
Clean up resources
If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it:
Next steps
See also
Get started with the Bing Autosuggest client library for Go. Follow these steps to install the library and try out our examples for basic tasks.
Use the Bing Autosuggest client library for Go to get search suggestions based on partial query strings.
Reference documentation | Sample code
Prerequisites
- An Azure subscription. If you don't already have an Azure subscription, you can create one for free.
- The latest version of Go.
Begin using the Bing Autosuggest client library by creating an Azure resource. Choose the resource type below that's right for you:
Create an Azure resource
Start using the Bing Autosuggest API by creating one of the following Azure resources.
Bing Autosuggest 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.
- Bing Autosuggest is also offered in paid tiers of the Bing Search v7 resource.
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 environment variables
Note
The endpoints for resources created after July 1, 2019 use the custom subdomain format shown below. For more information and a complete list of regional endpoints, see Custom subdomain names for Azure AI services.
Using your key and endpoint from the resource you created, create two environment variables for authentication:
AUTOSUGGEST_SUBSCRIPTION_KEY
: The resource key for authenticating your requests.AUTOSUGGEST_ENDPOINT
: The resource endpoint for sending API requests. It should look like this:https://<your-custom-subdomain>.api.cognitive.microsoft.com
Use the instructions for your operating system.
setx BING_AUTOSUGGEST_SUBSCRIPTION_KEY <replace-with-your-autosuggest-api-key>
setx BING_AUTOSUGGEST_ENDPOINT <replace-with-your-autosuggest-api-endpoint>
After you add the environment variable, restart the console window.
Create a new Go project
In a console window (cmd, PowerShell, Terminal, Bash), create a new workspace for your Go project and navigate to it. Your workspace will contain three folders:
- src: This directory contains source code and packages. Any packages installed with the
go get
command will reside here. - pkg: This directory contains the compiled Go package objects. These files all have an
.a
extension. - bin: This directory contains the binary executable files that are created when you run
go install
.
Tip
Learn more about the structure of a Go workspace. This guide includes information for setting $GOPATH
and $GOROOT
.
Let's create a workspace called my-app
and the required sub directories for src
, pkg
, and bin
:
$ mkdir -p my-app/{src, bin, pkg}
$ cd my-app
Install the client library for Go
Now, let's install the client library for Go:
$ go get -u <library-location-or-url>
or if you use dep, within your repo run:
$ dep ensure -add <library-location-or-url>
Create your Go application
Next, let's create a file named src/sample-app.go
:
$ cd src
$ touch sample-app.go
Open sample-app.go
, add the package name, and then import the following libraries:
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/services/cognitiveservices/v1.0/autosuggest"
"github.com/Azure/go-autorest/autorest"
"log"
"os"
)
Create a function named main
. Then, create environment variables for your Bing Autosuggest key and endpoint:
func main() {
// Add your Bing Autosuggest subscription key to your environment variables.
if "" == os.Getenv("BING_AUTOSUGGEST_SUBSCRIPTION_KEY") {
log.Fatal("Please set/export the environment variable BING_AUTOSUGGEST_SUBSCRIPTION_KEY.")
}
// Add your Bing Autosuggest endpoint to your environment variables.
var subscription_key string = os.Getenv("BING_AUTOSUGGEST_ENDPOINT")
if "" == os.Getenv("BING_AUTOSUGGEST_ENDPOINT") {
log.Fatal("Please set/export the environment variable BING_AUTOSUGGEST_ENDPOINT.")
}
var endpoint string = os.Getenv("BING_AUTOSUGGEST_ENDPOINT")
}
Code examples
These code samples show you how to complete basic tasks using the Bing Autosuggest client library for Go:
Authenticate the client
Note
This quickstart assumes you've created an environment variable for your Bing autosuggest key, named BING_AUTOSUGGEST_SUBSCRIPTION_KEY
, and one for your endpoint named BING_AUTOSUGGEST_ENDPOINT
.
In the main()
function, instantiate a client with your endpoint and key.
// Get the context, which is required by the SDK methods.
ctx := context.Background()
client := autosuggest.New()
// Set the subscription key on the client.
client.Authorizer = autorest.NewCognitiveServicesAuthorizer(subscription_key)
client.Endpoint = endpoint
Send an API request
In the same method, use the client's AutoSuggestMethodAsync method to send a query to Bing. Then, iterate over the Suggestions response, and print the first suggestion.
// This should return the query suggestion "xbox."
result, err := client.AutoSuggest (ctx, "xb", "", "", "", "", "", "", "", "", "", "", []autosuggest.ResponseFormat{"Json"})
if nil != err {
log.Fatal(err)
}
groups := *result.SuggestionGroups
if len(groups) > 0 {
group, _ := groups[0].AsSuggestionsSuggestionGroup()
fmt.Printf ("First suggestion group: %s\n", (*group).Name)
suggestions := *(*group).SearchSuggestions
if len(suggestions) > 0 {
fmt.Println("First suggestion:")
fmt.Printf("Query: %s\n", *suggestions[0].Query)
fmt.Printf("Display text: %s\n", *suggestions[0].DisplayText)
} else {
fmt.Println("No suggestions found in this group.")
}
} else {
fmt.Println("No suggestions found.")
}
Run the application
Run your Go application with the go run [arguments]
command from your application directory.
go run sample-app.go
Clean up resources
If you want to clean up and remove an Azure AI services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.