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:

<status>
  <created_at>Sun Oct 24 13:30:04 +0000 2010</created_at>
  <id>28594986565</id>
  <text>Day #24: Embedding Fonts in Windows Phone 7 http://bit.ly/wp7day24 #wp7 #wp7dev #31daysofwp7</text>
  <source>
    <a href="http://www.tweetdeck.com" rel="nofollow">TweetDeck</a>
  </source>
  <truncated>false</truncated>
  <favorited>false</favorited>
  <in_reply_to_status_id />
  <in_reply_to_user_id />
  <in_reply_to_screen_name />
  <retweet_count />
  <retweeted>false</retweeted>
  <user>
    <id>5688882</id>
    <name>Jeff Blankenburg</name>
    <screen_name>jeffblankenburg</screen_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>
    <profile_image_url>http://a3.twimg.com/profile_images/396764567/jeffblankenburgheadshot_normal.jpg</profile_image_url>
    <url>http://www.jeffblankenburg.com</url>
    <protected>false</protected>
    <followers_count>1962</followers_count>
    <profile_background_color>131516</profile_background_color>
    <profile_text_color>333333</profile_text_color>
    <profile_link_color>994700</profile_link_color>
    <profile_sidebar_fill_color>cccccc</profile_sidebar_fill_color>
    <profile_sidebar_border_color>999999</profile_sidebar_border_color>
    <friends_count>652</friends_count>
    <created_at>Tue May 01 15:54:53 +0000 2007</created_at>
    <favourites_count>201</favourites_count>
    <utc_offset>-18000</utc_offset>
    <time_zone>Eastern Time (US & Canada)</time_zone>
    <profile_background_image_url>http://s.twimg.com/a/1287010001/images/themes/theme14/bg.gif</profile_background_image_url>
    <profile_background_tile>true</profile_background_tile>
    <profile_use_background_image>true</profile_use_background_image>
    <notifications>false</notifications>
    <geo_enabled>true</geo_enabled>
    <verified>false</verified>
    <following>true</following>
    <statuses_count>5664</statuses_count>
    <lang>en</lang>
    <contributors_enabled>false</contributors_enabled>
    <follow_request_sent>false</follow_request_sent>
    <listed_count>151</listed_count>
    <show_all_inline_media>false</show_all_inline_media>
  </user>
  <geo />
  <coordinates />
  <place />
  <contributors />
</status>

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.

image

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

  1. Jeff, the URL for the download seems to be incorrect. :)

  2. My apologies. The link has been fixed!

  3. 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?

  4. Thanks for the link. I'll check it out.

  5. 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.

  6. 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?

  7. There is no happiness where there is no wisdom No wisdom but in submission to the gods. Big words are always punished, And proud men in old age learn to be wise.

  8. 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?

    Thanks

  9. Pingback: Getting ready for the Windows Phone 7 Exam 70-599 (Part 1)

  10. 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.. :-)

  11. Thanx for source code. I can check and test it by running application. thanx a lot for sharing your knowledge and time.

  12. Can you please suggest me a best article or e-book for learning XML Parsing?

    Thanx a lot for your time and suggestions.

  13. Pingback: 31 Days of Windows 8 | Day #4: New Controls « Blankenblog

  14. 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 )

Google+ photo

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

Connecting to %s