RESTful Web Service?

RESTful web services (representational state transfer) is a different architecture for web services than SOAP. RESTful services have a lot less transmission overhead and in general are a lot easier to create and consume.

Most development is going the direction of RESTful services over SOAP.

DataFlex currently only supports SOAP web services out of the box. In this blog post we show an example on how to call a RESTful service.

RESTful services use the standard HTTP protocol (the same we have to view pages on the internet).

HTTP Verbs

The HTTP protocol uses so-called verbs to tell the server what type of request it is making. For example a GET request will tell the server that data is requested. A POST request is used to post data to the server. There are other verbs such as PUT, DELETE, etc.

In order to show how to call a simple RESTful web service we built a small sample service using Visual Studio and Microsofts Web API. The sample service has the following URL

http://localhost/api/customer

we implemented the GET method so calling the above URL will return all customers in the database

Our customer database is actually an in memory cached data set that simply has an Id and a Name field.

we also implemented a POST method so we can create a simple HTML form that allows the user to enter a new customer

here is what our simple HTML page looks like

webapipage

And here is the javascript code that allows is to get the list of customers and save a customer

 

 

 

$(function()
{
        $.getJSON('/api/customer', function(customersJsonPayload)
        {
            $(customersJsonPayload).each(function(i, item)
            {
                $('#customers').append('<li>' + item.Name + '</li>');
            });
        });
});

$('#saveCustomer').click(function () {
    $.post("api/customer",
            $("#saveCustomerForm").serialize(),
            function (value) {
                $('#customers').append('<li>' + value.Name + '</li>');
            },
            "json"
    );
});

this all works fine of course and is not the part we are really interested in.

What is interesting is how can we call a RESTful web service from a DataFlex application

As mentioned earlier RESTful web services simply use the HTTP protocol. DataFlex has the cHTTPTransfer class that can be use to call RESTful services

so in our test view we can simple use the cHTTPTransfer package and create an object based on the class as follows

Use Windows.pkg
Use DFClient.pkg
Use cHttpTransfer.pkg

Deferred_View Activate_oWebAPITest for ;
Object oWebAPITest is a dbView

    Set Border_Style to Border_Thick
    Set Size to 200 300
    Set Location to 2 2
    Set Label to "Web API Test"
    
    Object oHTTPTransfer is a cHttpTransfer   
        Set psRemoteHost to "localhost"
        Set piRemotePort to 60387
        Set pbShowErrorDialog to True
    End_Object

We have to set the psRemoteHost property to the host name or ip address of the server the web service is running on. In our case we are using a local Visual Studio service so the psRemoteHost is localhost and the piRemotePort is 60387. The port also depends on your  service and could be 80 for the standard HTTP port or anything the service publisher uses to publish the service.

The way the cHTTPTransfer class works is that it has an event called OnDataReceived that is called when data is returned from the server. So we have to implement this event

    Object oHTTPTransfer is a cHttpTransfer   
        Set psRemoteHost to "localhost"
        Set piRemotePort to 60387
        Set pbShowErrorDialog to True
          
        Procedure OnDataReceived String sContentType String sData
            Showln sContentType 
            Showln "-----------------------------------------------"
            Showln sData
            Showln "-----------------------------------------------"
            
        End_Procedure
    End_Object

we simply show the content type and the data

Now lets see what it takes to call the GET verb to get all the customers

Lets add a button and add the following code to the OnClick procedure

Procedure OnClick
    Integer iRetVal
    Get HttpGetRequest of oHTTPTransfer "/api/customer" to iRetVal
End_Procedure

This will call the url /api/customer with GET request which in turn will then call the OnDataReceived event

Here is the data we receive back

webapigetshowln

the data type received is a JSON data type (application/json)

the data itself is as follows

[
  {
     "Id":1,
     "Name":"StarZen Technologies, Inc"
  },
  {
     "Id":2,
     "Name":"Palms West Photo"
  }
]

which is essentially a JSON array containing two customer records with each having an Id and a Name field

All we have to do now is to parse the JSON data and use it in our application

Now what if we wanted to save a new customer. This would require the use of a POST. In our simple example we used a standard web form with a POST request.

We can do the same from DataFlex

Lets add two forms and a button as follows

webapipostscr

We also need to add some code to the OnClick procedure in the button of course

        Procedure OnClick
            Integer iRetVal
            String sID sName

            Get Value of oID to sID
            Get Value of oName to sName
            
            String sData
            Append sData ("Id="+Trim(sID)+"&Name="+trim(sName)) 
            
            Integer bOK
            Send ClearHeaders to oHTTPTransfer 
            Get AddHeader of oHTTPTransfer "Content-Type" "application/x-www-form-urlencoded" to bOK
                        
            Get HTTPPostRequest of oHTTPTransfer "/api/customer" sData False to iRetVal            
        End_Procedure

Again very simple.

We get the values from our forms. Then because we are passing the data as form url encoded data we create a string as follows

Id=identered&Name=nameEntered

Then we call ClearHeaders on the HTTP Transfer object to clear all the default headers.

We then set the Content-Type header which is important as it will tell the web service what type of data we are sending

In this case we are sending form url encoded data so the content type is set to

"application/x-www-form-urlencoded"

Then we are calling the HTTPPostRequest method passing the url and the data.

webapipostresp

as you can see the web service responded by sending back the new customer record

if we click the GET button again we receive the data set including the new customer we just created

This post shows the basics of calling RESTful web services.

In future posts we will dive deeper into the more detailed aspects.

Michael Salzlechner is the CEO of StarZen Technologies, Inc.

He was part of the Windows Team at Data Access Worldwide that created the DataFlex for Windows Product before joining StarZen Technologies. StarZen Technologies provides consulting services as well as custom Application development and third party products specifically for DataFlex developers