Monday, March 24, 2014

Microsoft 70-480: Consume data

Exam Objectives


Consume JSON and XML data; retrieve data by using web services; load data or get data from other sources by using XMLHTTPRequest


Quick Overview of Training Materials

MSDN forum - How to parse XML file(from web api) in metrostyle application with javascript
SOAP vs REST - Oracle Video on Youtube (10min)



What is a web service?


A web service is a system designed to allow machine to machine communication over the web.  Two major classes of web services exist: RESTful services, and arbitrary services. RESTful services use REST (REpresentational State Transfer) to pass XML or JSON messages in a stateless fashion using URIs and HTTP commands, typically GET, POST, PUT, and DELETE.  Because some proxies and firewalls won't allow HTTP commands other than GET and POST, it is sometimes necessary to specify the action to take in the query string. An example of a simple REST call is to enter the URL http://graph.facebook.com/100  into the browser, which will send a GET request to the facebook Graph API (which is RESTful). It will return the following JSON data:

{
   "id": "100",
   "name": "Andrew Brunner",
   "first_name": "Andrew",
   "last_name": "Brunner",
   "gender": "male",
   "locale": "en_US",
   "username": "ambrunner"
}

Artibrary services may use SOAP (Simple Object Access Protocol) to pass formated XML messages. Arbitrary services do not use HTTP commands but instead expose their own operations. SOAP messages are passed in xml format, in a structure known as a SOAP envelope.  This envelope includes a head and body, and looks a bit like an HTML web page. Because SOAP messages are so verbose, they introduce additional overhead compared to REST. SOAP does offer some features, such as transactions, high reliability, and added security, that may make it more appropriate for enterprise solutions.

Using AJAX with a REST service is simple, since all it entails is getting the method to the appropriate HTTP "verb" (i.e. GET, POST, whatever) and pointing the call to the URL.  I covered basic AJAX in a previous post, so I won't rehash it here. I think I will cover the XMLHTTPRequest object in a little more detail though, just to be sure...

XMLHTTPRequest (XHR) Object


The XHR is an API for fetching resouces over the web, and is central to making AJAX work. It supports any text format, including (but not limited to) XML, and it can operate over HTTP and HTTPS.  The following methods and attributes are defined in the spec (and explained on MozDN):
  • Request object:
    • open() - initializes a request
    • setRequestHeader() - sets request headers (Accept-Encoding, Connection, Host, User-Agent, etc.). You will always need at least one header for POST requests to set the content type.
    • timeout - how long the request can take, in milliseconds, before being terminated.
    • withCredentials - boolean value indicates if cross-site Access-Control requests include authorization information. No effect on same site requests.
    • upload - possible to monitor the upload progress by adding an event listener to upload.
    • send() - sends the request. If asynchronous, returns immediately (the request happens in another thread and triggers onreadystatechange events when the status changes.
    • abort() - cancels a request that has been sent.
  • Response object:
    • status - status of the request according to HTTP response code (200 for OK, 401 for not found, etc.)
    • statusText - the entire text of the status message (so "200 OK" rather than just "200")
    • getResponseHeader() - gets a specific response header
    • getAllResponseHeaders() - gets ALL response headers
    • overrideMimeType() - treats the response as the specified MIME type rather than what the response header indicates the MIME type is.
    • responseType - type of data in response. Can be string, arraybuffer, blog, document, json. Cant be used on synchronous requests in FF and Chrome
    • response - The entity body of the response according to its type.
    • responseText - The response interpreted as text.
    • responseXML - The response interpreted as an XML Document

Parsing JSON and XML


The JSON.parse() function makes consuming JSON data trivial. The function takes a JSON string as a required parameter, and has an optional parameter called a reviver, which is a function that transforms every parsed JSON member.  The MSDN article on JSON.parse() includes an example of using a reviver to convert date strings into proper Date objects. Any member who is run through the reviver and causes it to return undefined (or otherwise causes the function to fail) is deleted from the result.

Parsing XML can also be quite simple. If using the responseXML property to access the response data, then the data can be traversed the same way as the DOM (.getElementById(), etc.). Another method of consuming XML data is with XPath (XML Path Language). The syntax of this language resembles a combination of file system syntax and CSS selectors.  If the response is a string containing XML data, however, the DOMParser object will parse XML (and HTML) strings into DOM trees. 

No comments:

Post a Comment