REST functions

How a REST call works.

If you need additional specific information about this topic or if you want to look it personally please write an email

REST is a methodology born to write simple functions accessible through the Internet and, therefore, through the most common network communication protocols.
A REST function is a function called through the HTTP (or HTTPS) protocol by merely invoking a static URL. The statis URL normally represents the name of the function.

REpresentational State Transfer (REST) is an architecture principle in which the web services are viewed as resources and can be uniquely identified by their URLs. The key characteristic of a RESTful Web service is the explicit use of HTTP methods to denote the invocation of different operations.

A REST function is a function that can be considered 'distributed', ie, not necessarily included in a single application but a component of a larger distributed application, in fact, between multiple non-resident applications on the same server or even not installed on the same Data Center.

In the panorama of this type of functions there are both state functions and functions without states (Stateless). A Stateless function is a simple function that returns one and only one answer to each call. Let's imagine, for example, a function performing a simple math additions:

Sum (a, b) = a + b

A state function is a function whose response depends not only on the request, but also on the previous state, and hence from the previous response and previous request. A nice example could be a traffic light (at least in Italy). The Orange color is only turned on by passing from green to red, otherwise no. In this case, we can imagine a function that manages the lights on:

Light (LightValue)

In order to handle the Orange lamp you will need to know the state of the previous "Green Light" and the previous situation of Red Light. This means that every time you turn Green or Red Light on, we will have to store the previous state in a variable that will be read at the time the orange light is turned on.
Obviously managing just one light is almost easy but if, instead, we are managing a distributed environment, it will be necessary, every time we call the function, to make it to understand who we are and to what extent we are processing.

In real life this problem is resolved with a session parameter. Session parameter management is much simpler in Web Services calls than in REST calls.
In a REST function a signature sent via the command line is easier to manage.

The basic REST design principle uses the HTTP protocol methods for typical CRUD operations:

POST - Create a resource
GET - Retrieve a resource
PUT – Update a resource
DELETE - Delete a resource

The major advantages of REST-services are:

They are highly reusable across platforms (Java, .NET, PHP, etc) since they rely on basic HTTP protocol
They use basic XML instead of the complex SOAP XML and are easily consumable

REST functions are thus created as remote functions to handle processes that do not require a stateless state. Another major benefit of a REST function is that it is a simple application that is managed in HTTP as if it were a simple Web page.
The function you create will take the session parameters from the get HTTP line for the call. With these parameters you will be able to access a database, make calculations, call other functions, process a result and then respond with an XML structure containing the response parameters. Nothing is easier.

If desired, you can also manage the REST function in state mode. States could be stored on the server and passed within the HTTP get or stored on the client and stored in the database. However, personally, I believe that the best way to handle a state function is to use Web services while using a REST call may be the best way to handle a one-shot state function. Another reason for my preference is perhaps that normal development environments already handle states for us when we create web services so that no manual or external management is needed for these actions. Let's build now using the REST technology a funny IOT device.
Assume you have an Arduino appliance with a GPS on board and assume that you want to store the position of this arduino "object" every 60 seconds in order to see on google map (for example) the position of your arduino during a certain interval of time. To do this using REST we will need to create a web function that once positioned in a web server folder and invoked writes on a database geographic coordinates calculated by the Arduino client.

I will not show you how to build a client function with your arduino. I assume you know how to write an arduino sketch able to:

1) Connect to the internet
2) Inizialise a GPS module
3) Retrieve GPS coordinates
4) Format a string
5) Call an URL passing the string as parameter

In this client application we will assume that function:

Getcoordinates()

can return the geographic coordinates to be written to the database. Geographic coordinates can be returned as a string of chars with the following format:

LATITUDE=1233.715480&LONGITUDE=4155.726918

At this point we can imagine a REST HTTP service which, once implemented on the web, can be activated by the following HTTP request:

http://www.test.org/Georeference.aspx?SOURCE=74KM&TIME=00:11:36&DATE=04/01/01&LATITUDE=1233.715480&LONGITUDE=4155.726918

In this get HTTP call we see that test.org is the server name that contains the aspx page while the Georeference.aspx page is the page that implements a DB access to store the coordinates received on the parameter line. In order to give some sort of simple security we can also send a sort of signature as parameter (the parameter SOURCE) and a TIMESTAMP in order to give also an order to the information received and stored into the DB by the REST application The visual studio development environment offer us a lot of facilities to build a rest function.

Here, for example, the class I wrote to store in a DB the parameters sent to my web server using the http URL you saw before:


              //GeoReferences.aspx
              //Author: Vittorio Margherita
              //Version 4.51
              public partial class WebForm1 : System.Web.UI.Page
              {
          
                  string ArduSource;
                  string ArduTime;
                  string ArduDate;
                  string ArduLatitude;
                  string ArduLongitude;
                  bool QueryMissedParam;
          
                  protected void Page_Load(object sender, EventArgs e)
                  {
                      XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
                      DateTime TimeOfTheDay, DayOfTheDate;
                      GeoReference GeoString = new GeoReference();
                      DatabaseConnectionDataContext db = new DatabaseConnectionDataContext();
                                  
                                    
          
                      ArduSource = Request.QueryString["SOURCE"];
                      ArduTime = Request.QueryString["TIME"];
                      ArduDate = Request.QueryString["DATE"];
                      ArduLatitude = Request.QueryString["LATITUDE"];
                      ArduLongitude = Request.QueryString["LONGITUDE"];
          
                      //check if the current App is authorised to work
                      var query =
                      from righe in db.AllowedPCCs
                      where
                      (righe.PCC == ArduSource)
                      
                      select righe;
          
          
                      //Initialize the Answer Node
                      writer.WriteStartDocument();
                      writer.WriteStartElement("GeoLocalization");
          
                      if (query.Count() == 0)
                      {
                          writer.WriteElementString("Insert", "False");
                          writer.WriteElementString("ReturnMessage", "ERROR: Appliance not authorised");
                      }
                      else
                      {
                          //Converting strings received to positional strings
                          //Caller
                          GeoString.Source = ArduSource;
          
                          //Time
                          TimeOfTheDay = Convert.ToDateTime(ArduTime);
                          GeoString.Time = TimeOfTheDay.TimeOfDay;
          
                          //Day
                          DayOfTheDate = Convert.ToDateTime(ArduDate);
                          GeoString.Date = DayOfTheDate.Date;
          
                          //Position
                          GeoString.Latitude = float.Parse(ArduLatitude);
                          GeoString.longitude = float.Parse(ArduLongitude);
          
                          //Enter the node
                          try
                          {
                              db.GeoReferences.InsertOnSubmit(GeoString);
                              db.SubmitChanges();
                              writer.WriteElementString("Insert", "true");
                              writer.WriteElementString("ReturnMessage", "Reference string enetered Correctly");
                          }
                          catch (Exception Exch)
                          {
                              writer.WriteElementString("Insert", "False");
                              writer.WriteElementString("ReturnMessage", "ERROR: String has not been entered");
                          }
                      }
                      writer.WriteEndElement();
                      writer.WriteEndDocument();
                      writer.Close();
                      Response.End();
                  }
              }
          

          

Leave a Comment