Introduction - Bing



43643559906000right25908000Migrating Bing Search API ApplicationsIntroductionThe Bing Search API enables developers and information works to embed and customize search results in applications or websites by using XML or JavaScript Object Notation (JSON). You can add search functionality to a website, create unique consumer or enterprise applications, or develop new mash-ups. The Bing Search API gives you access to web, image, news, and video results, as well as related search and spelling suggestions.The Bing Search API 2.0 is transitioning to an offering that's available in Windows Azure Marketplace via subscription. Windows Azure Marketplace is a cloud-based data service that enables developers and information workers to find, acquire, and consume published data sets and web services. Users subscribe to data sets and web services of interest and can integrate the information into their own applications via standardized data services. They can analyze the data online by using the Service Explorer tool or by using a growing body of tools like PowerPivot in Microsoft Excel.The new version of the Bing Search API includes:Metered subscription of query limits.HTTPS query URLs (sometimes called "endpoints") that provide results in either XML or JSON media formats.Open Data Protocol (OData) support for easy consumption across multiple development systems.Improved support for data types.The ability to monetize applications in the Windows Azure Marketplace.Access to fresher results and improved relevance.The move to Windows Azure Marketplace will require each customer to follow a migration process. This guide describes the migration process and gives usage samples.Migrating to the Bing Search API in Windows Azure MarketplaceTo migrate your existing application from Bing API 2.0 to the Bing Search API in Windows Azure Marketplace, complete the steps in this section.You can expect migrating to the new Bing Search API to involve the following changes in your existing application:Targeting of a new query URLModerate changes to the request and response schemasSecurity requirement to authenticate access to your data subscription1. Subscribe to a Bing Search API offeringSelect one of the following offerings.Product offeringCapabilitiesBing Search API Provides access to Bing web, image, video, news, and related search results, as well as spelling suggestionsBing Search API - Web Results OnlyProvides access to Bing web results only After you select an offering, choose an offer variant that represents the number of queries you want to subscribe to. Bing Search API comes in many variants to meet your traffic demand, including a free time-limited trial for prototyping. Select the offer variant by clicking the TRY FREE or BUY button.After you select the offer variant, you'll be asked to provide billing information, including a credit card number. For trial offers, the credit card will be used to convert the offer into a paid subscription after the trial period ends. If you don't want to convert to a paid offer, you can cancel your subscription before the trial period ends.Windows Azure Marketplace will bill the specified amount to your credit card each month, for as long as the subscription is active. You can view your active subscriptions on the My Data page in Windows Azure Marketplace.2. Change your query URLChange your Bing Search API query URL from the currently configured Bing Search API 2.0 query URL (that is, ) to one of the following, depending on which product offering you've subscribed to.Product offeringQuery URLBing Search API Search API - Web Results Only Service Explorer tool in Windows Azure Marketplace can help you experiment with the new Bing Search API and generate query URLs. You can access Service Explorer by using one of the following links, depending on which product offering you've subscribed to.Product offeringService Explorer linkBing Search API Search API - Web Results Only following illustration is an example of developing and running a query in Service Explorer.The query URL is expressed via the OData specification. The differences between this specification and Bing Search API 2.0 are as follows:Because string parameters will be used to generate a URL, they must be URL encoded. So instead of being enclosed in apostrophes ('), the string parameters are surrounded by the ASCII equivalent %27. For instance:: If the query text might contain non-alphanumeric characters, you should URL encode the entire string.The names of the count and offset parameters have been changed to comply with the OData standard. Furthermore, instead of having a different query URL for each response type (JSON versus XML), a special OData parameter is used. The following table lists the OData parameters.Reserved parameterDescriptionEquivalent in Bing Search API 2.0Default valueExample$topSpecifies the number of results to return.&count=50(50 is the maximum);$top=10$skipSpecifies the offset requested for the starting point of results returned.&offset=0;$top=10&$skip=20$formatSpecifies the format of the OData response. Current options are Atom (for XML) or JSON.Alternative formats were accomplished with different query URLs (for example, xml.aspx and json.aspx)Atom'Xbox'&$top=10&$skip=20&$format=ATOMFor more information about OData, visit the OData website.Note: The OData reserved parameters do not require that their corresponding values be URL encoded and enclosed in apostrophes ('), the ASCII equivalent %27.Bing API DataMarket supports HTTP compression to save on transfer data volume and delivery. To enable HTTP compression, add header “Accept-Encoding: gzip” to your HTTP request. 3. Append the service operation to the end of the query URLA service operation is the data source that is targeted for Bing Search API results. Bing Search API 2.0 referenced this as the &Source= parameter. For instance, if the targeted data source is "web," append the service operation Web to the end of your query URL as follows: service operations available in the Bing Search API DataMarket are listed in the following table.Service OperationEquivalent in Bing Search API 2.0ExampleWebWeb?$top=10ImageImage?$top=10VideoVideo?$top=10NewsNews?$top=10SpellingSuggestionSpell?$top=10RelatedSearchRelatedSearch?$top=10Composite;$top=1Note: To request multiple data sources in a single query, specify the service operation named “Composite” followed by its required parameter named “Sources”. The value applied to “Sources” are the name of the service operations concatenated with a + character. See the table above for an example of a single query requesting web & news. Also note that the number of results returned with the OData reserved parameter $top refer to all data sources specified in the query except News. News will always return a fixed number of 15 news results when used in a query with a Composite service operation.4. Specify required and optional parametersSpecify the required and optional parameters by appending parameterized name/value pairs to the query URL, as in common REST-like interfaces. The parameters are documented in a table under the Details tab of the offering that you've subscribed to.For instance, if you're building a query with the required parameter query of value 'XBOX' and the optional parameter market of value 'en-GB', append the parameterized name/value pairs to the end of your query URL as follows:. Obtain your account keyTo authenticate a Bing Search API request with Windows Azure Marketplace, you must obtain an account key. This mode of authentication replaces the AppID used in the Bing Search API 2.0. You can obtain your account key by using either of the following methods:Go to the Account Keys page and add a new account key for your application. This is the recommended method because you can remove this account key if it becomes compromised.Go to the Account Keys page and use the default account key.6. Insert the query URL into a browserTo issue your request for the Bing Search API, insert the query URL built from the previous steps into a browser. Windows Azure Marketplace supports Basic Authentication to authenticate requests to your data subscription. You'll be prompted for a user name and password from your browser. Leave the user-name field empty and enter your account key in the password field. The browser will display XML results returned from the Bing Search API.7. Adjust your response parsing logicAdjust your response parsing logic to match the updated response format.The following sections compare query responses between Bing Search API 2.0 and the Bing Search API that's available in Windows Azure Marketplace.Results containerSome changes were made to the elements that contain the results array. This includes the SearchResponse element, the SearchResponse/Query element, and the immediate children of the source-type-specific containers like web:Web and mms:Image.Version 2.0Windows Azure MarketplaceRequests;$top=2Response TreesSearchResponseFeed- Query - SearchTerms- link- web:Web- entry - web:Total - web:Offset - web:Results - contentNote: Other properties omitted for clarity.Removed data:SearchTerms. Because this is sent across the wire in the request, it is not necessary in the response. If some asynchronous programming pattern requires that the response be verified, the id response property can be used to obtain the full request URL.Total. If there are no more pages of results, the /feed/link[@rel=’next’] property will no longer appear, and the total is no longer needed for enabling paging.Offset. This value is used to help developers build the request URL for the next page of results. In the OData protocol, the next page of results is requested via the href property of /feed/link[@rel=’next’]. The next page of results can be obtained simply by requesting this URL.Web resultsVersion 2.0Windows Azure MarketplaceRequests;$top=2Response TreesSearchResponseFeed- web:Web - web:Results - web:WebResult- entry - content - m:properties - d:ID - web:Title - d:Title - web:Description - d:Description - web:DisplayURL - d:DisplayUrl - web:URL - d:Url - web:CacheUrl - web:DateTime - web:DeepLinks - web:SearchTagsNote: Other properties omitted for clarity. Removed data:CacheUrl. Deprecated.DateTime. Deprecated.DeepLinks. Deprecated.SearchTags. Deprecated.Added data:ID. A result set/unique ID for this row.Renamed data:URL. This property was renamed to Url.DisplayURL. This property was renamed to DisplayUrl.Image resultsVersion 2.0Windows Azure MarketplaceRequests;$top=2Response TreesSearchResponseFeed- mms:Image - mms:Results - mms:ImageResult- entry - content - m:properties - d:ID - mms:Title - d:Title - mms:MediaUrl - d:MediaUrl - mms:Url - d:SourceUrl - mms:DisplayUrl - d:DisplayUrl - mms:Width - d:Width - mms:Height - d:Height - mms:FileSize - d:FileSize - mms:ContentType - d:ContentType - mms:Thumbnail - d:Thumbnail - mms:Url - d:MediaUrl - mms:ContentType - d:ContentType - mms:Width - d:Width - mms:Height - d:Height - mms:FileSize - d:FileSizeNote: Other properties omitted for clarity. Added data:ID. A result set/unique ID for this row.Renamed data:URL. This property was renamed to SourceUrl.Video resultsVersion 2.0Windows Azure MarketplaceRequests;$top=2Response TreesSearchResponseFeed- mms:Image - mms:Results - mms:VideoResult- entry - content - m:properties - d:ID - mms:Title - d:Title - mms:PlayUrl - d:MediaUrl - mms:SourceTitle - mms:RunTime - d:RunTime - mms:ClickThroughPageUrl - d:DisplayUrl - mms:StaticThumbnail - d:Thumbnail - mms:Url - d:MediaUrl - mms:ContentType - d:ContentType - mms:Width - d:Width - mms:Height - d:Height - mms:FileSize - d:FileSizeNote: Other properties omitted for clarity. Removed data:SourceTitle. Deprecated.Added data:ID. A result set/unique ID for this row.Renamed data:PlayUrl. This property was renamed to MediaUrl.ClickThroughPageUrl. This property was renamed to DisplayUrl.StaticThumbnail. This property was renamed to Thumbnail.StaticThumbnail/Url. This property was renamed to MediaUrl.News resultsVersion 2.0Windows Azure MarketplaceRequests;$top=2Response TreesSearchResponseFeed- news:News - news:Results - news:NewsResult- entry - content - m:properties - d:ID - news:Title - d:Title - news:Url - d:Url - news:Source - d:Source - news:Snippet - d:Description - news:Date - d:Date - news:BreakingNewsNote: Other properties omitted for clarity.Removed data:BreakingNews. Deprecated.Added data:ID. A result set/unique ID for this row.Renamed data:Snippet. This property was renamed to Description.Related search resultsVersion 2.0Windows Azure MarketplaceRequests RelatedSearch?Query=%27odata%27&$top=2Response TreesSearchResponseFeed- rs:RelatedSearch - rs:Results - rs:RelatedSearchResult- entry - content - m:properties - d:ID - rs:Title - d:Title - rs:Url - d:BingUrlNote: Other properties omitted for clarity.Added data:ID. A result set/unique ID for this row. Spelling suggestion resultsVersion 2.0Windows Azure MarketplaceRequests;$top=2Response TreesSearchResponseFeed- spl:Spell - spl:Results - spl:SpellResult- entry - content - m:properties - d:ID - spl:Value - d:ValueNote: Other properties omitted for clarity.Added data:ID. A result set/unique ID for this row.Usage samplesThis section shows usage samples in a variety of languages to help developers start using the new Bing Search API.Using the API with the Microsoft .NET Framework via C#The most straightforward approach to using the API with C# is to download a service proxy from the Bing API landing page in Windows Azure Marketplace. After you subscribe to the offer, you'll see a button like this one directly below the offer variants list:If you click this button, you can download the proxy to your computer. Next, you can move this library into your project directory and add it to your project. To get started with the proxy, see the first two sections of Walkthrough: Microsoft Translator in a C# Console Application.After the proxy has been added to your project, you can start coding against it almost immediately. The following sample console application synchronously performs an image search and downloads the search results.Important: Be sure to add a reference to System.Data.Services.Client before you build your project.using?System;using?; namespace?ImageSearchConsole{????class?Program????{????????static?void?Main(string[]?args)????????{????????????var?bingContainer?=?new?Bing.BingSearchContainer( new?Uri("")); ????????????//?replace this value with your account key????????????var?accountKey?=?"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; ????????????//?the?next?line?configures?the?bingContainer?to?use?your?credentials.????????????bingContainer.Credentials?=?new?NetworkCredential(accountKey,?accountKey); ????????????//?now?we?can?build?the?query????????????var?imageQuery?=?bingContainer.Image("xbox",?null,?null,?null,?null,?null); ????????????var?imageResults?=?imageQuery.Execute(); ????????????foreach?(var?result?in?imageResults)????????????{????????????????Console.WriteLine(result.Title);????????????} ????????????Console.ReadLine();????????}????}}Using the API with the Microsoft .NET Framework via Visual BasicBecause of the popularity of working with XML content in Visual Basic, the following sample has been tailored to consume the raw Atom response from the Bing Search API directly in Visual Basic .NET. The sample aims to execute a simple image query against the Bing Search API and to print some attribute of each image response to the console. To use this sample, create a new Visual Basic console application and paste the sample code into the main .vb file.Imports?System.XmlImports?Module?Module1????Sub?Main()????????' Replace this value with your account key????????Dim?accountKey?As?String?=?"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="????????'?The?Windows?Azure?Marketplace?Service?Root?Url?for?the?Bing?Search?offer????????Dim?serviceRoot?As?String?=?""????????'?The?Query?type?we're?performing????????Dim?imageQueryRoot?As?String?=?serviceRoot?+?"Image?"????????'?The?Query?string,?surrounded?by?Url?Encoded?quotes????????Dim?imageQuery?As?String?=?imageQueryRoot?+?"Query=%27xbox%27"????????'?An?XmlDocument?we?will?use?to?read?the?results????????Dim?document?As?XmlDocument?=?New?XmlDocument()????????'?The?next?four?lines?configure?the?XmlDocument?to?use?your?credentials????????'?when?querying?the?Image?Search?API????????Dim?accountCredential?As?New?NetworkCredential(accountKey,?accountKey)????????Dim?resolver?As?New?XmlUrlResolver()????????resolver.Credentials?=?accountCredential????????document.XmlResolver?=?resolver????????'?With?credentials?configured?we?download?the?query?results????????document.Load(imageQuery)????????'?This?namespace?manager?will?assist?with?parsing?the?results????????Dim?namespaceManager?As?XmlNamespaceManager?=?New?XmlNamespaceManager(document.NameTable)????????namespaceManager.AddNamespace("atom",?"")????????namespaceManager.AddNamespace("m",? "")????????namespaceManager.AddNamespace("d",?"")????????'?This?query?gets?the?"Next"?link?for?the?result?set.?document.Load?this?value?to?get?the?next????????'?set?of?results.?If?the?value?is?Nothing?then?there?are?no?more?results.????????Dim?nextResultSet?As?String?=?document.SelectSingleNode( "/atom:feed/atom:link[@rel='next']/@href",? namespaceManager).Value????????'?This?gets?the?properties?node?for?each?Image?search?result????????Dim?imageResults?As?XmlNodeList?=?document.SelectNodes( "/atom:feed/atom:entry/atom:content/m:properties",? namespaceManager)????????For?Each?imageResult?As?XmlNode?In?imageResults????????????'?Select?the?Title?element?from?this?imageResult???????????Dim?title?As?String?=?imageResult.SelectSingleNode(".//d:Title",?namespaceManager).InnerText???????????Console.WriteLine(title)????????Next????End?SubEnd?ModuleUsing the API with SilverlightSilverlight is a Microsoft framework that enables developers to build Rich Internet Applications (RIAs) by using many of the same .NET Framework libraries and programming languages that they're accustomed to using in classic .NET applications. Because of its strong integration with browsers as well as with images and other media, it's a useful client for building applications via the Bing Search API.Like JSON applications that reside in the browser, Silverlight applications can't typically invoke services (raw HTTP or SOAP) on domains other than the domain from which the Silverlight application is downloaded. But because Windows Azure Marketplace publishes a cross-domain policy file at the root of its domain () that allows RIA platforms like Silverlight to access its query URLs, it's possible to use the API from Silverlight.Because Silverlight is really a .NET programming environment, the choices for API invocation are the same as the earlier .NET samples (although Silverlight also has a JSON-parsing object model). You can use the same proxy class that you saw in the earlier .NET samples. To help developers build very responsive applications, however, Silverlight requires that Web requests are performed asynchronously rather than synchronously.The following sample shows a Silverlight application obtaining data from the Bing Image Search service. It assumes that you have already added the Bing proxy to your application, as was shown in the C# sample.using?System;using?System.Data.Services.Client;using?System.Linq;using?;using?System.Windows;using?System.Windows.Controls; namespace?BingApp{????public?partial?class?MainPage?:?UserControl????{????????public?MainPage()????????{????????????InitializeComponent();????????} ????????private?void?button1_Click(object?sender,?RoutedEventArgs?e)????????{????????????var?bingContainer?=?new?Bing.BingSearchContainer( new?Uri("")); ????????????//?replace this value with your account key????????????var?accountKey?=?"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="; ????????????//?the?next?two?lines?configure?the?bingContainer?to?use?your?credentials.????????????bingContainer.Credentials?=?new?NetworkCredential(accountKey,?accountKey); ????????????//?note, this line was not required for the C# console app????????????bingContainer.UseDefaultCredentials?=?false; ????????????//?the?next?two?lines?define?the?request?for?data?and?????????????var?imageQuery?=?bingContainer.Image("xbox",?null,?null,?null,?null,?null); ????????????imageQuery.BeginExecute(new?AsyncCallback(this.ImageResultLoadedCallback),?imageQuery);????????} ????????private?void?ImageResultLoadedCallback(IAsyncResult?ar)????????{????????????var?imageQuery?=?(DataServiceQuery<Bing.ImageResult>)ar.AsyncState; ????????????var?enumerableImages?=?imageQuery.EndExecute(ar); ????????????var?imagesList?=?enumerableImages.ToList(); ????????????//?here?you?could?also?choose?to?simply?bind?the?results?list?to????????????//?a?control?in?your?UI.?Instead,?we?will?simply?iterate?over?the????????????//?results. ????????????foreach?(var?image?in?imagesList)????????????{????????????????//?do?something?with?the?image,?or?bind?the?image????????????}????????}????}}Using the API with PHPPHP has a powerful JSON parsing mechanism. Because PHP is a dynamic language, the parsing mechanism enables PHP developers to program against a JSON object graph in a straightforward way. The following sample shows a PHP page that sends a request to the JSON interface by using the file_get_contents function to call the JSON query URL, and the json_decode function to turn the results into an object graph that can be walked and turned into HTML.<html> <head> <link href="styles.css" rel="stylesheet" type="text/css" /> <title>PHP Bing</title> </head> <body> <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>"> Type in a search: <input type="text" id="searchText" name="searchText" value="<?php if (isset($_POST['searchText'])) { echo($_POST['searchText']); } else { echo('sushi'); } ?>" /> <input type="submit" value="Search!" name="submit" id="searchButton" /> <?php if (isset($_POST['submit'])) { // Replace this value with your account key $accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='; $ServiceRootURL = ‘'; $WebSearchURL = $ServiceRootURL . 'Image?$format=json&Query='; $context = stream_context_create(array( 'http' => array( 'request_fulluri' => true, 'header' => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey) ) )); $request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\''); echo($request); $response = file_get_contents($request, 0, $context); $jsonobj = json_decode($response); echo('<ul ID="resultList">'); foreach($jsonobj->d->results as $value) { echo('<li class="resultlistitem"><a href="' . $value->MediaURL . '">'); echo('<img src="' . $value->Thumbnail->MediaUrl. '"></li>'); } echo("</ul>"); } ?> </form> </body></html>Using the API with other development environmentsWindows Azure Marketplace exposes the Bing Search API by using the well-known and broadly supported OData protocol. In addition to providing a common language with which to expose data, OData provides Bing Search API customers with a broad set of tools and libraries that they can use to consume OData services like the Bing Search API in a variety of programming languages. To learn more about the library support available for OData, see the OData SDK.Of course, you can also use the Bing Search API to find web results for the query "odata sdk".To browse the Bing Search API OData services, you can query the OData metadata, which returns a complete description of how the service can be called, what parameters it expects, and what data structures it returns. It thus serves a roughly similar purpose as a method signature in a programming language. To access the OData metadata, append the OData keyword $metadata to the end of the query URL of the data subscription of the Bing Search API offering that you selected, as shown in the following table.Product offeringQuery URLBing Search API $metadataBing Search API - Web Results Only$metadata ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download