RESTful Web Services and .NET

Monday, February 1, 2010

Up until this point I had never worked with RESTful Web services.  I had heard lots about them from my friends in the java world, but hadn’t had a need to use them.  I wanted to connect to a REST web service in the simplest way possible. Here are 2 ways to easily connect to a RESTful web service and parse the reply.

For the example I will be using the FAA’s Airport Service. The FAA Airport Service serves airport status and delay information from the Air Traffic Control System Command Center (ATCSCC) as displayed on http://fly.faa.gov/.

The url of the web service is http://services.faa.gov/airport/status/SFO?format=application/xml. It is currently set up to return delay information about San Francisco’s airport. To retrieve information for a different airport remove the San Francisco airport code (SFO) and replace it with another airport code. For example if you would like information on Chicago’s O’Hare airport replace (SFO) with (ORD).

XmlTextReader

This is the simplest way to connect and parse the response. Pass in the Url of the web service you would like to use. Then use the read() method of the reader to move through each element. This is the fastest way to parse the response, but only provides one way parsing through each node. This poses problems with responses that are nested.

Example

   1:  // Retrieve XML document
   2:  var url = "http://services.faa.gov/airport/status/SFO?format=application/xml"; 
   3:  var reader = new XmlTextReader(url);  
   4:     
   5:  // Skip non-significant whitespace  
   6:  reader.WhitespaceHandling = WhitespaceHandling.Significant;  
   7:     
   8:  // Read nodes one at a time  
   9:  while (reader.Read())  
  10:  {  
  11:      // Read Nodes into PONO 
  12:  }

XmlDocument

The XmlDocument takes a little bit longer to load, but gives a lot more options when parsing. XDoc can be used to get nodes out of the XmlDocument.

Example

   1:  // Retrieve XML document
   2:  var url = "http://services.faa.gov/airport/status/SFO?format=application/xml"; 
   3:  var doc = new XmlDocument();     
   4:          
   5:  // Load data  
   6:  doc.Load(url);
   7:   
   8:  // Get a list of the top level nodes
   9:  var nodes = doc.GetElementsByTagName(rootNode);
  10:   
  11:  // Loop through the root nodes
  12:  foreach (XmlNode node in nodes)
  13:  {
  14:      //Parse the Xml nodes into PONOs
  15:  }

Both of these methods provide easy ways to parse the response of a RESTful Web Service.

Top