31 Days of Windows Phone | Day #25: Talking To External APIs

This post is Day #25 in a series called the 31 Days of Windows Phone.

Yesterday, I wrote about embedding fonts, videos, and images into your Windows Phone application.  Today, we’re going to talk about retrieving data from a web service, and populating your application with it.

Introducing the Twitter API

If you haven’t played with this before, you’ll often hear me refer to a Twitter application as the new “Hello, world!”  The reason is simple:  nearly every application needs to connect to a web service anymore, and Twitter’s API is easy to use, available for free, and doesn’t even require registration.  In other words, there’s nearly no barrier to entry, and it’s a great way to learn a new technology.

The core of Twitter’s API can be found here: http://dev.twitter.com/

We’re specifically going to be looking at the user timeline elements of the API, leveraging this specific URL template:  http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=jeffblankenburg  where my username, jeffblankenburg, can be substituted with any Twitter username.

If you click on the URL I just provided you, you should see a pretty lengthy XML document.  This document contains the most recent messages I have posted to Twitter, with all of the wonderful metadata to go with them.  Here’s one node of that document:

  <created_at>Sun Oct 24 13:30:04 +0000 2010</created_at>
  <text>Day #24: Embedding Fonts in Windows Phone 7 http://bit.ly/wp7day24 #wp7 #wp7dev #31daysofwp7</text>
    <a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>
  <in_reply_to_status_id />
  <in_reply_to_user_id />
  <in_reply_to_screen_name />
  <retweet_count />
    <name>Jeff Blankenburg</name>
    <location>Columbus, OH</location>
    <description>I'm a passionate technologist, husband, and father in Columbus, OH. I work for a small software company located in Redmond, WA. #wp7 http://blankensoft.com</description>
    <created_at>Tue May 01 15:54:53 +0000 2007</created_at>
    <time_zone>Eastern Time (US & Canada)</time_zone>
  <geo />
  <coordinates />
  <place />
  <contributors />

The important thing to remember about this content above is that it’s just XML.  Nothing fancy, nothing different.  Most web services available on the web provide an XML feed, and we can treat them all the same way, for the most part.

Getting XML Data From the Web to our App

It’s very simple (3 lines!) to get XML data from an online data feed to our application running on a phone.  One important thing to remember is that it’s up to you to check and see if the user even had a data connection.  There’s a simple way to do this, using the Microsoft.Phone.Net.NetworkInformation assembly:

if (NetworkInterface.GetIsNetworkAvailable())

Inside that for loop, we’re going to create a new WebClient object, and make an asynchronous call out to that Twitter API that I gave you the address before.  First, I create a new event handler for when our data retrieval is complete, and second I make that asynchronous call.  (In my example, you’ll see that I retrieve the username from a textbox that the user can type into.

if (NetworkInterface.GetIsNetworkAvailable())
    WebClient twitter = new WebClient();

    twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(twitter_DownloadStringCompleted);
    twitter.DownloadStringAsync(new Uri("http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=" + TwitterNameBox.Text));

When the data returns, our event handler fires, and we need to do something with it.  Let’s take a look at that next.

Using XML in our Application

ONce we’ve got that data returned to our application, we want to actually display it on the screen.  In many of my other examples, I’ve shown how to databind a value to a XAML control.  We’re not going to focus on that in this post (though the code sample in the bottom certainly includes it), and instead, we’re going to look at parsing our XML data using LINQ.

To do this, we’ll need yet another namespace, System.Xml.Linq.  Once we’ve got this included, it’s a pretty simple process.  We need a new XElement object that holds our XML data.

XElement xmlTweets = XElement.Parse(e.Result);

Once our data is held in xmlTweets, all we have to do is bind it to our LIstBox, and use LINQ to create custom TwitterItem objects on the fly from the data.

TwitterList.ItemsSource = from tweet in xmlTweets.Descendants("status")
                            select new TwitterItem{
                                message = tweet.Element("text").Value

You’ll see in my code sample below that I have a custom TwitterItem class that has a “message” property. 

That’s it, though!  We’ve grabbed live data from an XML feed, processed it into our application, and displayed it in a ListBox.  For a full working example, check out the code below:

Download the Code

This is a fully working (but certainly not fully-featured) Twitter client.  You can type a username into a textbox, and the application will reach out to the Twitter API, grab the data, and then parse and display it in the application.


17 thoughts on “31 Days of Windows Phone | Day #25: Talking To External APIs

  1. Thanks for the intro. In general I tend to opt for parsing JSON since it's more lightweight on mobile. Haven't looked into the libraries just yet but I'm hoping there's no trade offs with parsing JSON versus XML on WP7?

  2. This post is Day #25 in a series called the 31 Days of Windows Phone. Yesterday, I wrote about embedding fonts, videos, and images into your Windows Phone application.   Today, we’re going to talk about retrieving data from a web service, and populating your application with it.

  3. Jeff, where can I find on the web specific web services to call for specific types of apps? Meaning, suppose I want to get stock quotes… what web service would I call for that?

  4. Hi Jeff,

    What about the facebook API ?
    Can you give me some informations about the future release of this API or how can implement it in the WP7 if it exists?


  5. Hi Jeff,

    This post is really very useful. But i need to download the entire code.
    Where can i download the code? There is no download link available in this site. kindly check the download link.. 🙂

  6. Pingback: Anonymous

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s