Quickstart: Send a search request to the Bing Entity Search REST API using Java
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 make your first call to the Bing Entity Search API and view the JSON response. This simple Java application sends a news search query to the API, and displays the response.
Although this application is written in Java, the API is a RESTful Web service compatible with most programming languages.
Prerequisites
- The Java Development Kit (JDK).
- The Gson library.
Create an Azure resource
Start using the Bing Entity Search API by creating one of the following Azure resources.
Bing Entity Search 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 Entity Search 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 and initialize a project
Create a new Java project in your favorite IDE or editor, and import the following libraries:
import java.io.*; import java.net.*; import java.util.*; import javax.net.ssl.HttpsURLConnection; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser;
In a new class, create variables for the API endpoint, your subscription key, and a search query. You can use the global endpoint in the following code, or use the custom subdomain endpoint displayed in the Azure portal for your resource.
public class EntitySearch { static String subscriptionKey = "ENTER KEY HERE"; static String host = "https://api.bing.microsoft.com"; static String path = "/v7.0/search"; static String mkt = "en-US"; static String query = "italian restaurant near me"; //...
Construct a search request string
Create a function called
search()
that returns a JSONString
. url-encode your search query, and add it to a parameters string with&q=
. Add your market to the parameter string with?mkt=
.Create a URL object with your host, path, and parameters strings.
//... public static String search () throws Exception { String encoded_query = URLEncoder.encode (query, "UTF-8"); String params = "?mkt=" + mkt + "&q=" + encoded_query; URL url = new URL (host + path + params); //...
Send a search request and receive a response
In the
search()
function created above, create a newHttpsURLConnection
object withurl.openCOnnection()
. Set the request method toGET
, and add your subscription key to theOcp-Apim-Subscription-Key
header.//... HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKey); connection.setDoOutput(true); //...
Create a new
StringBuilder
. Use a newInputStreamReader
as a parameter when instantiatingBufferedReader
to read the API response.//... StringBuilder response = new StringBuilder (); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); //...
Create a
String
object to store the response from theBufferedReader
. Iterate through it, and append each line to the string. Then, close the reader and return the response.String line; while ((line = in.readLine()) != null) { response.append(line); } in.close(); return response.toString();
Format the JSON response
Create a new function called
prettify
to format the JSON response. Create a newJsonParser
, callparse()
on the JSON text, and then store it as a JSON object.Use the Gson library to create a new
GsonBuilder()
, usesetPrettyPrinting().create()
to format the JSON, and then return it.//... 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); } //...
Call the search function
From the main method of your project, call
search()
, and useprettify()
to format the text.public static void main(String[] args) { try { String response = search (); System.out.println (prettify (response)); } catch (Exception e) { System.out.println (e); } }
Example JSON response
A successful response is returned in JSON, as shown in the following example:
{
"_type": "SearchResponse",
"queryContext": {
"originalQuery": "italian restaurant near me",
"askUserForLocation": true
},
"places": {
"value": [
{
"_type": "LocalBusiness",
"webSearchUrl": "https://www.bing.com/search?q=sinful+bakery&filters=local...",
"name": "Liberty's Delightful Sinful Bakery & Cafe",
"url": "https://www.contoso.com/",
"entityPresentationInfo": {
"entityScenario": "ListItem",
"entityTypeHints": [
"Place",
"LocalBusiness"
]
},
"address": {
"addressLocality": "Seattle",
"addressRegion": "WA",
"postalCode": "98112",
"addressCountry": "US",
"neighborhood": "Madison Park"
},
"telephone": "(800) 555-1212"
},
. . .
{
"_type": "Restaurant",
"webSearchUrl": "https://www.bing.com/search?q=Pickles+and+Preserves...",
"name": "Munson's Pickles and Preserves Farm",
"url": "https://www.princi.com/",
"entityPresentationInfo": {
"entityScenario": "ListItem",
"entityTypeHints": [
"Place",
"LocalBusiness",
"Restaurant"
]
},
"address": {
"addressLocality": "Seattle",
"addressRegion": "WA",
"postalCode": "98101",
"addressCountry": "US",
"neighborhood": "Capitol Hill"
},
"telephone": "(800) 555-1212"
},
. . .
]
}
}