Today, we are proud and happy to unveil to our developer community our new search brand, Bing. Bing is a powerful new Decision Engine designed to help consumers accomplish tasks and make faster, more informed decisions. For more details on Bing, check out the main Bing blog. Bing.com will be available to the world in the coming days; in the meantime visit http://www.decisionengine.com and follow us on Twitter (@Bing) for all the latest news.
So what does this mean to you? The API provides developers programmatic access to Bing, offering flexible options for building or enhancing your site or applications. You can learn more about the API here. And try your hand developing new search apps and saving money, the planet, or both in our Will Code for Green contest!
A couple of important notes:
- All applications that worked yesterday will work today with no changes required
- All use of the Bing API will have to reflect brand attribution by August 30th, 2009. If you are interested in using the API, please familiarize yourself with the amended terms of use.
-- Alessandro Catorcini, Lead Program Manager, Bing API
We have observed that it is a very frequent need to restrict a search to RSS feeds. This is possible on the Live.com homepage by using the feed: keyword in your query.
While using this operator in an API query does not work, you can achieve the same result by specifying web.filetype=feed as a parameter in the request.
The following examples illustrate how to do this using XML, JSON, and SOAP.
XML Sample Request
http://api.search.live.net/xml.aspx?query=nba&sources=web&appid=YOUR_APPID&web.filetype=feed
JSON Sample Request
http://api.search.live.net/json.aspx?AppId=YOUR_APPID&Query=nba&Sources=web&web.filetype=feed&JsonType=raw
SOAP Sample Request
using (LiveSearchService service = new LiveSearchService())
{
// Build request
SearchRequest request = new SearchRequest();
request.AppId = AppId;
request.Query = "nba";
request.Sources = new SourceType[] { SourceType.Web };
request.Web = new WebRequest();
request.Web.FileType = "feed";
// Send the request
SearchResponse response = service.Search(request);
// Display feed results
Console.WriteLine("Web results for " + response.Query.SearchTerms);
foreach (WebResult result in response.Web.Results)
{
Console.WriteLine("Title: {0}", result.Title);
Console.WriteLine("Description: {0}", result.Description);
Console.WriteLine("Url: {0}", result.Url);
Console.WriteLine();
}
}
-- Beatrice Oltean, Program Manager, Live Search API
A while back, we published a whitepaper on MSDN that provides what we called a "tour de ease" of some basic API features. Subsequently, some of you have requested that we offer this useful doc in a more portable format, so - voila! It's done and downloadable at our Developer Center from the API Basics link, under "Useful Resources." Click it, download it, develop an app or two with it.
One of the most satisfying aspects of managing the Live Search API is helping our team expand the already-rich diversity of programming opportunities that our multiple protocols and SourceTypes provide. This particular paper illustrates how you can leverage the appropriate combination of these protocols and SourceTypes to create applications that grow your business, yet enable you to code at the level of complexity with which you're comfortable.
Beyond growing your business, the new Will Code for Green contest offers you incentives to put the API to broader uses. Five developers will take home cash from this contest - will one of them be you? The contest runs until August 12 - use the whitepaper to get started today!
-- Alessandro Catorcini, Lead Program Manager, Live Search API
The Live Search team has announced a contest that enables you to compete with other developers for thousands of dollars in prizes. The idea: Use the Live Search API to create apps that either (1) Help people deal with the worsening economy, or (2) Improve the ecology of the planet. For details, see
Will You Code for Green This Spring?
Good luck!
-- The Live Search API Team
It's spring in the northern hemisphere, and the Live Search API team is celebrating with features that grow the API and the services you can use it to provide. Our SDK was ahead of the curve: It went live with new documentation and code samples on MSDN and our download center last week. Whether you're getting hotter in the north or getting colder in the south, we've got new features to make your search applications better all around.
We debuted all the new features last week at MIX09 - for more on the goings-on there, see the Live Search blog. In this post, you'll find an overview of the new API features, plus a shout out to a new member of the Live Search team, Microsoft Translator, and a look at the first Live Search API PowerToys codeplex.
New API features
- Video - public at last!
After determined negotiations, we've achieved sufficient symbiosis with content providers to make the Video SourceType available to you with minimal restriction. You'll be able to access Video the same as you would Image, Web, and the rest of our burgeoning crop of SourceTypes.
- MobileWeb - you asked for it.
The second new SourceType of the spring is MobileWeb, which returns results from the increasingly growing resource of Extensible Hypertext Markup Language (XHTML), Wireless Markup Language (WML) and other mobile Web pages. Functionally, this highly-demanded SourceType gives you everything you get from the Web SourceType, its static sibling - but with content from the mobile world.
- Image Filters
Many developers have told us that they would benefit from a means of restricting Image SourceType results to those that have specific characteristics - for example, size, aspect, or style. The ImageRequest.Filters Property enables you to use these and more to get exactly the kind of images you want; the new Video SourceType has an analagous VideoRequest.Filters Property.
Microsoft Translator
We're happy to give a shout out to the Microsoft Translator team, which showed off great new features at MIX, such as:
- Microsoft Translator web page widget
The Microsoft Translator web page widget allows you to bring real-time, in-place translations to your web site. Users can see your pages in their own language, without having to go to a separate translation web site, and share your page with friends in multiple languages. You can learn more about how to use the widget, get help or interact with other website owners on the Microsoft Translator forums. 2
- Microsoft Translator AJAX API
The Microsoft Translator AJAX API allows you to easily integrate translation functionality into your web applications and sites. You can learn more about the API on MSDN, try out the interactive SDK or interact with other developers on the Microsoft Translator forums.
For more information, check out the Translator team's blog.
PowerToys Codeplex
And, completing this Equinox treasure trio, a PowerToy* for the Live Search API. This PowerToy consists of sample code that demonstrates the ease with which a developer can create a control that takes advantage of Live Search API capabilities, as well as the ease with which such a control can be deployed on a page.
You can see an example of such a control in the Washington on the Web section in the lower right of this outdoor-recreation-website-in-progress. The control plays a slideshow based on images returned from a query sent to the API's Image SourceType . The control is written in C#, and the aspx page can be set up at design time to use the ImageRequest.Filters Property to filter the images based on query term, size, color and style.
To get started, download the sample code from Silk Road PowerToys.
* PowerToys are Microsoft product productivity tools developed after a release. They are not an official part of the product and are not supported by Microsoft.
Happy Equinox and Happy Developing - The Live Search API Team
This is the final post in our series that shows how you can use the API with Java. As promised, we've packaged the instructions and code from the first two posts in the series with code and instructions for two new applications and made the package available on
our download site. Thus, the package includes code and instructions for creating:
- A console application using Java and the API's XML interface
- A console application using Java and the API's SOAP interface
- A search box application using Java, Java Server Pages, and the API's XML interface
- A search box application using Java, Servlets, and the API's SOAP interface
Enjoy!
-- Roopali Kaujalgi
Progam Manager, Live Search API team
Mark Johnson from the Powerset team has posted on the Powerset blog regarding Ubiquity commands for Powerset and highlighted some commands for Live Search as well. Ubiquity is a research project from Mozilla Labs that has a lot in common with Powerset: the goal of the project is to reinvent the user interface through natural language. Ubiquity uses a command-line interface to allow you to get tasks done quicker by typing in exactly what you want.
Powerset is excited to have written a few Ubiquity commands that you might find useful. Once you have the commands installed, you can just type in "powerset " and you'll get a full Powerset Wikipedia search of the topic you enter. As a bonus, they've also included commands from Live Search.
For example, try typing "live sean penn" to get Live Search results for Sean Penn. You can also type "live images sean penn" to get a list of images or "live xrank sean penn" to get Sean Penn's xRank answer. It was really simple to do this thanks to the Live Search API's JSON interface.
In case you don’t have Ubiquity and you’re wondering what it's about, here's a brief video of the Live Ubiquity commands.
Check out the post for more details!
This is the second of a series of posts that show how you can use the API with Java. This post shows how you can use Java to create a console application that sends a request to the API's SOAP interface and displays the results. The last post in the series will include a pointer to a site from which you can download all instructions and code associated with each post in the series.
-- Roopali Kaujalgi
Requirements
Demonstrates
This code sample demonstrates how to:
- Send a request to the Live Search SOAP interface and the Web SourceType
- Display the Live Search response as results
To run the sample
- Set the AXIS2_HOME environment variable to the directory where you have installed Axis2.
- From any directory, run %AXIS2_HOME%\bin\wsdl2java -uri http://api.search.live.net/search.wsdl?AppId=<Insert your AppID here> to create the web service proxy classes. For the rest of this procedure, we refer to the directory in which you run this procedure as directory X.
- The classes will be generated with a folder structure as X\src\com\microsoft\schemas\livesearch\_2008\_03\search.
- Create a text file and save it as WebSample.java in X\src.
- Copy the code under "Example" below, and save it in WebSample.java.
- Insert your AppId into the WebSample class in the BuildRequest method.
- Make sure your CLASSPATH environment variable contains all jar files from AXIS2_HOME\lib directory.
- Compile Websample and the proxy classes.
- Run WebSample, using the command java WebSample.
Example
import java.rmi.RemoteException;
import java.util.Iterator;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.databinding.types.UnsignedInt;
import org.apache.axis2.transport.http.HTTPConstants;
import com.microsoft.schemas.livesearch._2008._03.search.LiveSearchServiceStub;
import com.microsoft.schemas.livesearch._2008._03.search.LiveSearchServiceStub.*;
public class WebSample
{
static LiveSearchServiceStub stub = null;
public static void main( String [] args ) throws RemoteException
{
try
{
// Initialize the service
stub = new LiveSearchServiceStub();
stub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED,
false);
// Build the request
LiveSearchServiceStub.SearchRequest searchRequest= BuildRequest();
// Get the response
SearchResponseE response = GetResponse(searchRequest);
// Display the response
DisplayResponse(response);
}
catch (AxisFault e)
{
DisplayErrors(e);
}
}
private static SearchRequest BuildRequest()
{
SearchRequest request = new SearchRequest();
// Common request fields (required)
request.setAppId("Insert your AppID here");
request.setQuery("msdn blogs");
ArrayOfSourceType param = new ArrayOfSourceType();
param.addSourceType(SourceType.Web);
request.setSources(param);
// Common request fields (optional)
request.setVersion("2.0");
request.setMarket("en-us");
request.setAdult(AdultOption.Moderate);
// Web-specific request fields (optional)
WebRequest web = new WebRequest();
request.setWeb(web);
web.setCount(new UnsignedInt("10"));
web.setOffset(new UnsignedInt("0"));
web.setFileType("DOC");
ArrayOfWebSearchOption options = new ArrayOfWebSearchOption();
options.addWebSearchOption(WebSearchOption.DisableHostCollapsing);
options.addWebSearchOption(WebSearchOption.DisableQueryAlterations);
web.setOptions(options);
return request;
}
private static SearchResponseE GetResponse(SearchRequest searchRequest) throws RemoteException
{
SearchRequestE searchRequestE = new SearchRequestE();
searchRequestE.setParameters(searchRequest);
return stub.Search(searchRequestE);
}
private static void DisplayResponse(SearchResponseE responseE)
{
SearchResponse response = responseE.getParameters();
int startIndex = response.getWeb().getOffset().intValue() + 1;
int endIndex = response.getWeb().getOffset().intValue() +
response.getWeb().getResults().getWebResult().length;
// Display the results header.
System.out.println("Live Search API Version " + response.getVersion());
System.out.println("Web results for " + response.getQuery().getSearchTerms());
System.out.println("Displaying " + (startIndex) + " to " + (endIndex) + " of " +
response.getWeb().getTotal() + " results ");
System.out.println();
// Display the Web results.
StringBuilder builder = new StringBuilder();
WebResult[] results = response.getWeb().getResults().getWebResult();
for(int i =0 ; i < results.length; i++)
{
builder.setLength(0);
builder.append(results[i].getTitle());
builder.append("\n");
builder.append(results[i].getDescription());
builder.append("\n");
builder.append(results[i].getUrl());
builder.append("\n");
builder.append("Last Crawled: ");
builder.append(results[i].getDateTime());
builder.append("\n");
System.out.println(builder.toString());
}
System.out.println();
}
@SuppressWarnings("unchecked")
private static void DisplayErrors(AxisFault e)
{
System.out.println("Live Search API errors.\n");
System.out.println("FaultString:" + e.getReason());
System.out.println("FaultDetails:\n");
OMElement element = e.getDetail();
Iterator iterator = element.getChildElements();
while(iterator.hasNext())
{
OMElement childElement = (OMElement) iterator.next();
Iterator childIterator = childElement.getChildElements();
while(childIterator.hasNext())
{
OMElement ele = (OMElement)childIterator.next();
System.out.println("\t" + ele.getLocalName() + " : " + ele.getText());
}
}
}
}
This is the first of a series of posts that show how you can use the API with Java. This post shows how you can use Java to create a console application that sends a request to the API's XML interface and displays the results. The last post in the series will include a pointer to a site from which you can download all instructions and code associated with each post in the series.
Coming next: Using the API with Java and the SOAP interface
-- Roopali
Requirements
Demonstrates
These code samples demonstrates how to:
- Send a request to the Live Search XML interface and the Web SourceType
- Display the Live Search response as results
To run the sample
- Create files named WebSample.java and APINameSpaceContext.java.
- Copy "File 1 Content: WebSample.java" from the section of that name in this post to WebSample.java.
- Copy "File 2 Content: APINameSpaceContext.java" from the section of that name in this post to APINameSpaceContext.java.
- In WebSample.java, substitute your AppId for Insert your AppId here.
- Edit your computer's PATH environment variable to include the bin directory of the JAVA installation.
- Compile the 2 files.
- Run the sample (for example, typing java WebSample from the command line in the directory containing WebSample.java).
File Content
The remainder of this post consists of the content (in the form of code) that you will copy in Steps 2 and 3 of "To Run the Sample."
File 1 Content: WebSample.java
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
//Live Search API 2.0 code sample demonstrating the use of the
//Web SourceType over the XML Protocol.
class WebSample
{
static XPathFactory factory = null;
static XPath xpath = null;
static XPathExpression expr = null;
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException,
XPathExpressionException
{
// Build the request.
String requestURL = BuildRequest();
// Send the request to the Live Search Service and get the response.
Document doc = GetResponse(requestURL);
if(doc != null)
{
// Display the response obtained from the Live Search Service.
DisplayResponse(doc);
}
}
private static String BuildRequest()
{
// Replace the following string with the AppId you received from the
// Live Search Developer Center.
String AppId = "Insert your AppId here.";
String requestString = "http://api.search.live.net/xml.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=msdn blogs"
+ "&Sources=Web"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Adult=Moderate"
// Web-specific request fields (optional)
+ "&Web.Count=10"
+ "&Web.Offset=0"
+ "&Web.FileType=DOC"
+ "&Web.Options=DisableHostCollapsing+DisableQueryAlterations";
return requestString;
}
private static Document GetResponse(String requestURL) throws ParserConfigurationException, SAXException,
IOException
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = null;
DocumentBuilder db = dbf.newDocumentBuilder();
if (db != null)
{
doc = db.parse(requestURL);
}
return doc;
}
private static void DisplayResponse(Document doc) throws XPathExpressionException
{
factory = XPathFactory.newInstance();
xpath = factory.newXPath();
xpath.setNamespaceContext(new APINameSpaceContext());
NodeList errors = (NodeList) xpath.evaluate("//api:Error",doc,XPathConstants.NODESET);
if(errors != null && errors.getLength() > 0 )
{
// There are errors in the response. Display error details.
DisplayErrors(errors);
}
else
{
DisplayResults(doc);
}
}
private static void DisplayResults(Document doc) throws XPathExpressionException
{
String version = (String)xpath.evaluate("//@Version",doc,XPathConstants.STRING);
String searchTerms = (String)xpath.evaluate("//api:SearchTerms",doc,XPathConstants.STRING);
int total = Integer.parseInt((String)xpath.evaluate("//web:Web/web:Total",doc,XPathConstants.STRING));
int offset = Integer.parseInt((String)xpath.evaluate("//web:Web/web:Offset",doc,
XPathConstants.STRING));
NodeList results = (NodeList)xpath.evaluate"//web:Web/web:Results/web:WebResult",doc,
XPathConstants.NODESET);
// Display the results header.
System.out.println("Live Search API Version " + version);
System.out.println("Web results for " + searchTerms);
System.out.println("Displaying " + (offset+1) + " to " + (offset +
results.getLength()) + " of " + total + " results ");
System.out.println();
// Display the Web results.
StringBuilder builder = new StringBuilder();
for(int i = 0 ; i < results.getLength(); i++)
{
NodeList childNodes = results.item(i).getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++)
{
if(!childNodes.item(j).getLocalName().equalsIgnoreCase("DisplayUrl"))
{
String fieldName = childNodes.item(j).getLocalName();
if(fieldName.equalsIgnoreCase("DateTime"))
{
fieldName = "Last Crawled";
}
builder.append(fieldName + ":" + childNodes.item(j).getTextContent());
builder.append("\n");
}
}
builder.append("\n");
}
System.out.println(builder.toString());
}
private static void DisplayErrors(NodeList errors)
{
System.out.println("Live Search API Errors:");
System.out.println();
for (int i = 0; i < errors.getLength(); i++)
{
NodeList childNodes = errors.item(i).getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++)
{
System.out.println(childNodes.item(j).getLocalName() + ":" + childNodes.item(j).getTextContent());
}
System.out.println();
}
}
}
File 2 Content: APINameSpaceContext.java
import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
// Map prefixes to Namespace URIs
public class APINameSpaceContext implements NamespaceContext
{
static final String WEB_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web";
static final String API_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element";
static final String SPELL_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/spell";
static final String RS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/relatedsearch";
static final String PB_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/phonebook";
static final String MM_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia";
static final String AD_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/ads";
static final String IA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/instantanswer";
static final String NEWS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/news";
static final String ENCARTA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/encarta";
public String getNamespaceURI(String prefix)
{
if (prefix == null) throw new NullPointerException("Null prefix");
else if ("api".equals(prefix)) return API_NAMESPACE;
else if ("web".equals(prefix)) return WEB_NAMESPACE;
return XMLConstants.NULL_NS_URI;
}
// This method isn't necessary for XPath processing.
public String getPrefix(String uri)
{
throw new UnsupportedOperationException();
}
public Iterator getPrefixes(String arg0)
{
throw new UnsupportedOperationException();
}
}
Yesterday we posted Introducing Live Search API Version 2.0 Beta on MSDN. This whitepaper provides a tour de ease through some basic API features, such as:
Getting Started: Using the Live Search API from a Browser
Incorporating Advertisements into Results
Using the API from Programmable Environments
Terms of Use Overview
Whether you're building your first search application, surfing for tips to tune up existing apps, or looking to harness the power of the new version, this whitepaper's worth a peruse.
-- Alessandro
Here's an example of good ole ASP+XSL.
It should run on Internet Information Server 4 or any more recent version, and Windows NT4 or any more recent version of Windows (with ASP on, of course).
--Alessandro
<%@ Language=VBScript %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<body>
<%query = request("query") %>
<%AppID = "YourAppID" %>
<form name="xmlForm" action="filename.asp" method="post">
<input type="text" name="query" value="<%= query %>"/>
<input type="submit" name="searchBtn" value="Search"/>
<%
If query<>"" Then
xslt = "webLS.xslt"
Set xsldoc = Server.CreateObject("MSXML2.DOMDocument")
fullurl = "http://api.search.live.net/xml.aspx?sources=web&appid=" & AppID & "&query=" & query
Set webreq = Server.CreateObject("MSXML2.XMLHTTP.3.0")
webreq.Open "GET", fullurl, False 'synchronous request
webreq.send
If webreq.status = 200 Then
xsldoc.async = false
boolXSLLoad = xsldoc.load(server.mappath(xslt))
If boolXSLLoad = False Then
response.write "Cannot load XSL sheet"
Else
response.write webreq.responseXML.transformNode(xsldoc)
End If
End If
End If
%>
</form>
</body>
</html>
webLS.xslt:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
xmlns:web="http://schemas.microsoft.com/LiveSearch/2008/04/XML/web"
xmlns:srch="http://schemas.microsoft.com/LiveSearch/2008/04/XML/element"
>
<xsl:output method="html" indent="yes"/>
<xsl:template match="/">
<xsl:apply-templates select="srch:SearchResponse/web:Web"/>
</xsl:template>
<xsl:template match="web:Web">
<p>displaying result <xsl:value-of select="web:Offset+1"/> to <xsl:value-of select="count(//web:WebResult)+web:Offset"/> out of <xsl:value-of select="web:Total"/>
</p>
<xsl:apply-templates select="web:Results"/>
</xsl:template>
<xsl:template match="web:Results">
<ul>
<xsl:apply-templates select="web:WebResult"/>
</ul>
</xsl:template>
<xsl:template match="web:WebResult">
<li>
<a>
<xsl:attribute name="href">
<xsl:value-of select="web:Url"/>
</xsl:attribute>
<xsl:value-of select="web:Title"/>
</a>
<br/>
<xsl:value-of select="web:Description"/>
</li>
</xsl:template>
</xsl:stylesheet>
This post demonstrates using the API with good old ASP - plus a little XPATH magic.
-- Alessandro
<%@ Language=VBScript %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
</head>
<body>
<%query = request("query") %>
<%AppID = "your AppID here" %>
<form name="xmlForm" action="LSAPI2noXSL.asp" method="post">
<input type="text" name="query" value="<%= query %>"/>
<input type="submit" name="searchBtn" value="Search"/>
<%
If query<>"" Then
fullurl = "http://api.search.live.net/xml.aspx?sources=web&appid=" & AppID & "&query=" & query
Set webreq = Server.CreateObject("MSXML2.XMLHTTP.4.0")
webreq.Open "GET", fullurl, False 'synchronous request
webreq.send
If webreq.status = 200 Then
Response.Write "<ul>"
Set results = webreq.responseXML.selectNodes("//*[local-name(.)='WebResult']")
For Each result in results
Response.Write "<il><a href='"
Response.Write result.selectSingleNode("*[local-name(.)='Url']").text
Response.Write "'><h3>"
Response.Write result.selectSingleNode("*[local-name(.)='Title']").text
Response.Write "'</h3></a><p>"
Response.Write result.selectSingleNode("*[local-name(.)='Description']").text
Response.Write "</p></li>"
Next
Response.Write "</ul>"
End If
End If
%>
</form>
</body>
</html>
We continue now with the second in this series of samples demonstrating the use of Live Search API, Version 2.0 Beta with PHP.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Live Search API 2.0 through PHP and XML</title>
</head>
<body>
<?php
$APPID = "Your AppID here";
>
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="text" id="searchBox" name="searchBox" value="<?php
if (isset($_POST['searchBox'])){
echo($_POST['searchBox']);
}
?>"/>
<input type="submit" value="Search" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit']))
{
$request = 'http://api.search.live.net/xml.aspx?Appid=' . $APPID . '&sources=web&query=' .
urlencode( $_POST["searchBox"]);
$response = new DOMDocument();
//echo $request . "<br/>";
$response->load($request);
$webResults = $response->getElementsByTagName("WebResult");
if ($webResults->length<>0)
{
echo('<ul ID="resultList">');
foreach($webResults as $value)
{
/*
Sample response from Live Searh XML API for Web:
<?xml version="1.0" encoding="utf-8" ?>
<?pageview_candidate ?>
<SearchResponse xmlns="http://schemas.microsoft.com/LiveSearch/2008/04/XML/element" Version="2.0">
<Query>
<SearchTerms>microsoft</SearchTerms>
</Query>
<web:Web xmlns:web="http://schemas.microsoft.com/LiveSearch/2008/04/XML/web">
<web:Total>255000000</web:Total>
<web:Offset>0</web:Offset>
<web:Results>
<web:WebResult>
<web:Title>Microsoft Corporation</web:Title>
<web:Description>Get product information, support, and news from Microsoft. ...
Microsoft Silverlight delivers a new generation of high-quality audio and video, engaging media experiences,
and ...</web:Description>
<web:Url>http://www.microsoft.com/</web:Url>
<web:DisplayUrl>http://www.microsoft.com/</web:DisplayUrl>
<web:DateTime>2008-11-07T08:51:18Z</web:DateTime>
</web:WebResult>
</web:Results>
</web:Web>
</SearchResponse>
The interesting fields (Title, Description and Url are at position 0,1 and 2 as children
of WebResult.
The API result is strongly typed and the order of these elements is guaranteed
*/
echo('<li class="resultlistitem"><a href="' . $value->childNodes->item(2)->nodeValue . '">'); //Url
echo('<h3>' . $value->childNodes->item(0)->nodeValue . '</h3></a>'); //Title
echo('<p>' . $value->childNodes->item(1)->nodeValue . '</p>'); //Description
}
echo("</ul>");
} else
{
echo "<p>No results for query</p><b>" . $_POST["searchBox"] . "</b><p>please modify your query
and try again</p>";
} }
?>
</form>
</body>
</html>
As part of our commitment to the online community through Project Silk Road, we want to make it easy for you to use our API in a way that works best for your needs. The new interfaces exposed by version 2.0 of Live Search API make it very simple to consume results in a variety of environments.
For the near future we plan to use this blog to release reusable code snippets in a variety of environments and languages.
Let’s start with a widely used web programming technology, PHP. From PHP the most straightforward way to call the Live Search API Version 2.0 is to use the API’s JSON interface.
This code snippet shows how to build a basic PHP page that uses the JSON interface to get web search results by using the file_get_contents function to call the interface, and the json_decode function to turn the results into an object that can be processed. In this sample, we use PHP and JSON to send a request to the API’s Web SourceType, but the concept in the sample can be used in any other SourceType or any combination.
In the next blog: PHP and XML
Note: While we have, to this point, focused these samples on Microsoft technology, we are aware that a large number of websites are based on the Linux/Apache/MySQL/PHP (LAMP) stack. While it is very straightforward to use version 2.0 of the API from PHP, a bug in the SOAP extension of PHP in version 5.2.6 and subsequent versions prevented the Live Search API Version 1.1b’s SOAP from being used by a PHP client. This issue has been addressed in Version PHP 5.3.
-- Alessandro
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Live Search API 2.0 through PHP</title>
</head>
<body>
<?php
"Your AppID here";
?>
<form "post" action="<?php echo $PHP_SELF;?>">
<input type="text" id="searchBox" name="searchBox" value="<?php
if (isset($_POST['searchBox'])){
echo($_POST['searchBox']);
}
else {
echo('Microsoft');
}
?>"/>
<input type="submit" value="Search" name="submit" id="searchButton" />
<?php
if (isset($_POST['submit']))
{
$request = 'http://api.search.live.net/json.aspx?Appid=' . $APPID . '&sources=web&query=' . urlencode($_POST["searchBox"]);
$response = file_get_contents($request);
$jsonobj = json_decode($response);
echo('<ul ID="resultList">');
foreach($jsonobj->SearchResponse->Web->Results as $value)
{
echo('<li class="resultlistitem"><a href="' . $value->Url . '">');
echo('<h3>' . $value->Title . '</h3></a>');
echo('<p>' . $value->Description . '</p>');
}
echo("</ul>");
}
?>
</form>
</body>
</html>
If you've been wondering what was simmering in the Live Search API pot these past months, wonder no more! Today we officially launched our beta for the new generation of search engine API.
Live Search API version 2.0 beta, announced this morning at PubCon in Las Vegas, is now just a click away from being live in your development environment.
There's a lot that’s new in this version:
- We now offer access through new interfaces: JSON, and XML over HTTP. Of course, you can still use our SOAP interface. But now you have options.
- You said you were spinning cycles parsing out non-web results that had been shoehorned into a one-size-fits-all response structure, and we heard you. The new API is strongly typed and offers access to seven different types of results (web, news, images, phonebook, spell-checker, related queries, and Encarta instant answer).
- We’ve opened up our Terms of Use, eliminating the pre-set usage quota. We do require that you use this API for user-facing applications only. But that’s reasonable, right?
- We’ve retained the popular capability to batch as many SourceTypes as you want into a single request with a single query string.
Exciting? What if I told you that you can apply for a pilot program that will allow you to incorporate advertisements seamlessly into your results pages, retrieving them as one more SourceType in a request? Well, you can!
To top it off, we’ve restructured our RSS interface. Now we offer the ability to use a 100% OpenSearch compliant RSS format to send requests to our web, news, images and phonebook SourceTypes.
Live Search API, version 2.0 beta is what you need to develop search applications that transcend the old-school ten-blue-results-on-a-page.
To get started, go to the Live Search Developer Center and get your AppID today!
-Alessandro Catorcini, Lead Program Manager for APIs