Lecture 2: Web Services

Web Services and Mobile from Avner Solomon

Most of modern apps need at one point another to interact with WEB APIs in order to centralize data, authenticate users or even small updates. In this course we will talk only about the client side of the APIs and not the server. WEB API clients interact with WEB APIs in pretty much the same way as users interact with web sites, they access a link and they fetch certain information. The main difference would be that instead of human readable information the content is encoded in such manner to be easily processed by our code. Usually the response from an API is a text representation of an Object or Array ( it doesn't matter which coding language is used because the text representation is language independent ).

There are multiple types of WEB APIs like SOAP , REST , xml-rpc , json-rpc etc. but in order to simplify this class we will focus on REST services which handle JSON data.

REST APIs

As mentioned before accessing is very similar to viewing the web. REST APIs work over HTTP protocol and even if they support all HTTP methods: HEAD, POST, GET , PUT, DELETE, UPDATE, OPTIONS , most of the time only the main 2 ones will be used:

  • GET to retrieve data from the API
  • POST to create or update data server-side through the API

GET and POST are the 2 main methods used also when browsing:

  • your browser calls a server resource with the GET method each time you fetch a web page
  • your browser calls a server resource with the POST method when you submit a secure form

The main difference between GET and POST is that the POST request HTTP packet also contains a body with the data you want sent to the server. In a form the browser sends the form fields inside this body (example: username and password).

The rest APIs use URLs to make the structure of the API easier to understand and also. For example fetching the news for a news site can be as easy as accessing:

news.com/api/news/latest

This call would retrieve the most recent news but unlike with a human redable format where we would see images, links, pictures and other content, the response will contain only the essential information:

  [
    {
      "news_id":"1312",
      "news_title":"Title 1",
      "news_content":"Content"
    },
    {
      "news_id":"1313",
      "news_title":"Title 2",
      "news_content":"Content"
    },
    {
      "news_id":"1314",
      "news_title":"Title 3",
      "news_content":"Content"
    }
  ]

The above answer represent the JSON encoding of an array containing 3 news. We will discus about JavaScript Object Notation later in this class. If we would want to create a new news article and we assume we have the rights to do so we would most likely have to access via POST a link similar to

news.com/api/news/create

and send as payload the info for the new news article

  {
    "news_title":"New Article",
    "news_content":"News content"
  }

In response to this the server will tell us if creating the new article was successful or not.

JSON (JavaScript Object Notation)

JSON is an open standard that uses human readable text to encode Objects. It is an alternative to XML and has less overhead to represent the same information but has some limitations:

  • limited supported data types:
Data Type Notation Example
Number It can be either integer or double 2 or 3.84
String a series of characters delimited by " "word" "more words"
Boolean either true or false
Array An array can contain any type of data and the data should be delimited by , [“sting”,2,”another string”]
Object An Object is more of a dictionary which contains key pair values, the start of an object is marked by { unlike [ for Arrays {“firstname”:“Maria” ,”lastname”:“Ioana”}
null empty
  • No support for grammar definition like XML Schema or DTD which is used to validate data. DTD and Schema are resources used by independent APIs to make sure they enforce the same data format.

Example of complex JSON object representing a product in a store (the comments bellow are just for explanatory purposes, not all JSON interpreters support comments since it's not standard) :

  {
    product_id: 19, // numerical unique id of the product,
    product_SKU: "ER-271" //Storage keeaping unit, an id identifying the products in the storage,
    product_name: "Some product name",
    vendor_name: "Ana's shop",
    vendor_website: null, // Ana's shop has no website so we left the value null
    related_products: [21,173,192] // array containing ids of related products
    full_price: 200,
    sale_price: 150,
    product_tags: ["rings","gold"],
    product_reviews:[ // an array containing review objects
      { // first review object
        review_autor:"Dan",
        review_rating: 5,
        review_content: "A great product! Happy with it."
      },
      { //second review object
        review_autor:"Mark",
        review_rating: 4.5,
        review_content: "Great product but the price is a little too high."
      }
    ]
  }

jQuery and Ajax requests

In order to call an URL for a REST api from our javascript code inside the app we would need to make an AJAX call, but in order to simplify this process we included the jQuery javascript library inside the IoT template. This will allows you to write ajax get and post calls on the fly. Also jQuery will offer you a lot of tools to modify your HTML elements and the overall design of the app from the javascript code.

GET

In order to GET data from an URL all we have to do is:

  $.get("URL",function(data){
    //code runs on success and data is the response 
  })

or

  $.get("URL")
    .done(function(data){
       //code on success
    })
    .fail(function(){
       //code on fail
    })
    .always(function(){
       // code called at every end of ajax request for both success and failiure
    });

For example let's assume we want to fetch the title of the latest news presented in the theoretical REST API at the start of this lesson with the URL

  news.com/api/news/latest
  $.get("news.com/api/news/latest",function(data){
    var latest_news = JSON.parse(data); // we decode the JSON object
 
    var title = latest_news[0].news_title; 
    // we fetch the news_title property of the first news in the array
    console.log( title ); //and display the title in the javascript console of the browser
  })

POST

In order to POST data to an API

  $.post("URL",data,function(response){
    //code runs on success
  })
  /*
   URL = URL for the API
   data = the data sent to the server (optional)
  */

or

  $.post("URL",data)
    .done(function(respose){
       //code on success
    })
    .fail(function(){
       //code on fail
    })
    .always(function(){
       // code called at every end of ajax request for both success and failiure
    });

Now let's try to imagine the scenario where we want to create an article with the API presented at the start of this class at:

  news.com/api/news/create
  var new_article = { newst_title:"My article", news_content:"My content"};
  // we will be using JSON.stringify and JSON.parse to encode/decode
  // the JavaScript object into a JSON string
  $.post("news.com/api/news/create", JSON.stringify(new_article), function(result){
    result = JSON.parse(result);
    // we will assume that if the object returned by the server has
    // no "error" property the creation was a success
    if(!restul.error){
       alert("Article created!");
    }
  });
iot/courses/02.txt · Last modified: 2016/06/23 10:17 by alexandru.radovici
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0