You are on page 1of 20

Running a REST Server from 4D

By Tai Bui, Technical Services Engineer, 4D Inc.

Technical Note 17-19

1
Table of Contents
------------------------------------------------------------------------------------------------------------------------------------------------------------------

Table of Contents .......................................................................................... 2


Abstract ....................................................................................................... 3
Introduction.................................................................................................. 3
REST ........................................................................................................... 3
How REST is Typically Served ....................................................................... 3
How to use REST from a Client ..................................................................... 4
Benefits of using REST ................................................................................ 4
Implementing a 4D REST Server ..................................................................... 5
Handling Requests ...................................................................................... 5
Providing Responses ................................................................................... 6
Handling REST Request Parameters ............................................................... 6
Error Handling ............................................................................................ 7
Authentication ............................................................................................ 8
Sample Database and Examples ...................................................................... 9
Basic REST Method ..................................................................................... 9
Handling HTTP GET Parameters REST Method ............................................... 10
Handling HTTP POST Parameters REST Method ............................................. 13
Access Control for REST ............................................................................. 15
Conclusion .................................................................................................. 20

2
Abstract
------------------------------------------------------------------------------------------------------------------------------------------------------------------

Being connected to the web is a very common privilege that many technologies are
incorporating. From the more common cell/smartphone to even refrigerators, web
technology is found everywhere. 4D can make use of web technology by being able
to run a REST Server providing REST services over the internet. This technical note
will go over the basic steps to build a REST server from 4D and provide examples
and additional methods to run one from any 4D database.

Introduction
------------------------------------------------------------------------------------------------------------------------------------------------------------------

The internet is a largely growing technology that is becoming more and more easily
accessible to everyone. In many developed countries, technology is taking
advantage of being connected to the internet for many of their features. Many
home products like smart home hubs and security systems are now connected to
the internet, and even when on the go smartphones and wearable technology are
connected to the internet. 4D can run a web server allowing all these potential
customers to connect to it. Taking it a step further, the 4D web server can also be
used as a REST server to allow REST requests to be made from these technologies.
This technical note will provide insight on how to run a REST server from 4D by
investigating what a REST server is and how it works and then providing a simple
technique for implementing a REST server in a 4D database. Familiarity with HTML
and JavaScript can be helpful in understanding the demo but is not necessary.

REST
------------------------------------------------------------------------------------------------------------------------------------------------------------------

REST is an acronym for Representational State Transfer which can also be referred
to as RESTful web services. REST allows multiple systems to operate in conjunction
with the use of the internet; this is usually through a client and a server. It relies
on a stateless, client-server, and cacheable protocol. Most RESTful applications use
HTTP requests to interact with data and are able to perform create, read, update,
and delete operations.

How REST is Typically Served

To provide REST services, there is no need for learning complex new technology.
At the core, a REST server is just an HTTP Server. If available on an HTTP
Server, a REST service will answer requests with raw text when used through
the HTTP protocol. The HTTP server receives a REST request from a client, it
then runs the function based on the request, and then returns a response
sometime during the process. The data sent and returned can be formatted in
any way the provider desires, from XML format to JSON and even encrypted
data. This allows REST to be a very flexible and powerful tool.

3
How to use REST from a Client

As explained, when an HTTP server receives a REST service request the server
will respond with a JSON format answer. To use REST, the client makes a typical
HTTP request such as:

http://www.SomeURL.com/contacts/getcellnum/

Instead of generating a request body, sending it to the server, and then having
the server parse the body, a REST request is simply and URL. The example URL
is a simple GET request and the response is raw text data.

More complex requests are done by adding additional HTTP GET parameters in
the URL, such as:

http://www.SomeURL.com/contacts/getcellnum/FirstName=John&LastName
=Doe

With complex requests, HTTP POST requests are usually used for more secure
data and it is also suggested that HTTP GET requests should only be used for
read-only functions with HTTP POST requests for any type of function.

REST can also be carried over secure sockets using the HTTPS protocol and
contents can be encrypted with any preferred method. This allows REST to be as
secure as other web services which can be as insecure with no encryption.

Benefits of using REST

Providing REST services allows organized interactions between independent


systems in a simple way. The service also injects very minimal overhead and is
compatible with a variety of clients from mobile phone browsers to other
websites.

Since REST was inspired by HTTP it can be used wherever HTTP can and can
play to its strengths compared to other services which may need XML and other
technologies. These features make REST a lightweight and simpler alternative to
other web services like SOAP, WSDL, and Remote Procedure Calls. Although it is
lightweight, REST can practically perform anything that Web Services can.

As it is named, REST is stateless, which means that the necessary state to


handle the request is contained in the request itself. Being stateless allows for
scalability as the server does not have to maintain the session state and load
balancers do not have to consider the session either.

There are a number of benefits to implementing REST services and the degree
of difficulty is not too high depending on what functions are desired. HTTP
knowledge is helpful and depending on formats and needs additional knowledge
can be helpful.

4
Implementing a 4D REST Server
------------------------------------------------------------------------------------------------------------------------------------------------------------------

With knowledge of what REST is and how it works, it can also be implemented as
part of a 4D Web Server. The following section will go over some methods to
implement a 4D REST Server, but it can be modified to fit other situations and
needs.

Handling Requests

Requests come in as HTTP GET or HTTP POST from a client calling a URL. With
4D, 4D methods can automatically be executed by 4DAction. By default,
methods are not available for REST services as this can be a security flaw.
Instead, the method must be enabled to be used for a REST service. After
creating a 4D Method that will be an available REST function, go to its Method
Properties and enable the setting for “4D tags and URLs (4DACTION…)” as
shown below.

5
Image 1: “4D tags and URLs (4DACTION…)” enabled for “Test” method.

The method can be called through the expected was of calling a REST function
using an HTTP GET or HTTP POST. Using 4DAction a sample HTTP GET request
would look like:

http://localhost/4DAction/cellphone

When creating a REST request, it can be beneficial to follow a general structure,


especially if the request is going to be publicized for others to use. URLs should
be as short as possible, so creating a method with a well self-defining name that
is short is suggested. The primary four verbs for databases that can provide
clarity are GET, PUT, DELETE, and POST. Case sensitivity should not be an issue
since URLs are typically displayed in lowercase.

Providing Responses

The response can be formatted in any desired way. Simpler responses can be
easier to work with, but having a structured or secure format is typically
preferred. Responses are sent to the client by executing a WEB SEND TEXT
command in the process. When the command is called, HTML formatted raw text
data in how the method built the response. For example, a simple JSON format
answer could be:

$answerText:=”{cellphone: \”123-456-7890\”}”

Then to send the response:

WEB SEND TEXT($answerText;”application/json”)

WEB SEND TEXT should only be called once.

Between receiving a Request and sending the Response, anything can be done
within the 4D method. The method can perform a query to generate a dataset
and format it into the response and perform cleanup code after to log and finish
up the method. Requests can be provided in multiple formats, however using a
standard and readable format can be helpful.

This is all that is basically needed to run a REST Server from 4D. The following
are more in-depth topics that will allow greater control over REST services.

Handling REST Request Parameters

HTTP GET and HTTP POST requests can contain parameters for more complex
REST requests such as querying a table for a certain string. The simplest way of
handling the parameters are by using WEB GET VARIABLES. By using the
WEB GET VARIABLES command, the names and values of each parameter are
parsed into two correlated text arrays. This data can then be used in the REST

6
method for some more specific functions. For a sample 4D REST Method
“cellphone”:

ARRAY TEXT($arrNames;0)
ARRAY TEXT($arrValues;0)
WEB GET VARIABLES($arrNames;$arrValues)

If the request is:

http://localhost/4DAction/cellphone?firstName=John&lastName=Doe

The results would be

$arrNames{1}=”firstName”
$arrNames{2}=”lastName”

and

$arrValues{1}=”John”
$arrValues{2}=”Doe”

If the request contains content in the body such as a JSON format data the WEB
GET HTTP BODY can also be used to extract and use data. In some cases, data
can be contained in the parameters and/or in the body. To allow more flexibility
a method can be created to handle both in the following fashion:

ARRAY TEXT($arrNames;0)
ARRAY TEXT($arrValues;0)
C_TEXT($varBody)
WEB GET VARIABLES($arrNames;$arrValues)
WEB GET HTTP BODY($body)

When a method is called through REST the parameters are also passed into the
Method’s first parameters ($1) as a whole string. While it is not as easy to work
with, requiring additional parsing and such it can also be useful if needed. With
the request above $1=”?firstName=John&lastName=Doe”.

Error Handling

4D REST methods typically will encounter two types of errors that can and
should be handled by defensive programming. The first type of errors is 4D
coding errors which can also be considered as unexpected errors. Although they
are not expected, safe practice is to use an error handler. An error handler will
also trap 4D error messages. If a 4D error message appears, then the process
will be blocked waiting for user interaction and the client will not receive a
response until the error message is handled.
7
There are a number of ways to design an error handler, but to trap an error
handling method, even an empty one, must be applied to the process using the
ON ERR CALL command. Applying an error handling method to the start of the
method and then removing it at the end would be the most optimal way to
prevent a coding error from freezing up the web process. This practice can also
be expanded to all 4D programming in general.

The other type of errors is REST API errors. These errors can be formed by
invalid requests due malformed or incorrect parameters. The REST methods
should be designed so that it can handle these types of situations. Basic checks
would be to check if the names of the parameters are correct, other checks
would be to see if any functions performed successfully occurred such as an
attempted change on a locked record. Another error handling technique is to
add restrictions to prevent disasters from happening.

To handle these errors the 4D REST methods should be expecting a specifically


structured set of parameters. With the WEB GET VARIABLES command,
confirming that the variable names are correct and the number of parameters
sent is a simple check to implement. Values can be expected to be a limited set
of choices or should be of a specific format or type can also be checked.

With errors, a response should still be sent to the client. The response can be
anything desired but the most effective way to provide a response would be a
descriptive short explanation along with an error code. HTTP status codes can be
useful as they are a predefined standard that provides a searchable value for
them to get feedback and information online. A typical error message for
incorrectly formatted parameters would be a 400 Bad Request Error. More
information on HTTP status codes can be found at the following link:

http://www.ietf.org/assignments/http-status-codes/http-status-codes.xml

Authentication

When a 4D REST server is hosted it is available for use to anyone that can
contact the server. This may not be preferred for some methods. A method
implement access control is by implementing a custom login system. Since REST
is stateless and therefore no session is established, it is not recommended to
use the 4D login system. Instead, a login system can be implemented to provide
a token to the client so that the client can make a request and include the token
for authentication.

In short, the client will log in sending their credentials in the request. The server
will validate the credentials and send a token. Then the client will maintain that
token and send it with every restricted request. The credentials should not be in
plain text specifically the password. The token should be sent in the HTTP
header and not in the parameters list to prevent stored browser history from
maintaining the value. Additional safety measures are to add a timeout to the
token and tying the token to a specific IP address.

8
Sample Database and Examples
------------------------------------------------------------------------------------------------------------------------------------------------------------------

A sample database is provided to accompany this Technical Note. A walkthrough of


the database along with it, code will be explained in this section. The
implementation will follow the strategies explained in the last section. The 4D
database will start the 4D Web Server on startup using port 80. Modify the settings
and firewall if needed to start up the web server.

Basic REST Method

The first example is an implementation of a simple REST method is the


rs_getTimeText method. The method will get the current time and return the
value in the response to the client in plaintext.

// Method:
// rs_GetTimeText
//
// Description:
// Returns current time in Plain Text format
//
// --------------------------------------------------

C_TEXT($1)
C_TEXT($answer_t)
$answer_t:=String(Current time)
WEB SEND TEXT($answer_t;"text/html")

Connecting to the following (if the port was not changed):

http://localhost/4daction/rs_getTimeText

will run the method in a Web Process. The web process will execute in 4D and to
allow it to communicate with the client, the WEB SEND TEXT command is used
to send a response in text format.

The other two methods are similar in returning the current time but formatted
the response differently. The method rs_getTimeJSON returns the time in
JSON format and rs_GetTimeXML returns the time in XML format.

// Method:
// rs_GetTimeJSON
//
// Description:
// Returns current time in JSON format
//
// --------------------------------------------------

9
C_OBJECT($object_o)
C_TEXT($answer_t)
OB SET($object_o;"time";String(Current date))
$answer_t:=JSON Stringify($object_o)
WEB SEND TEXT($answer_t;"text/html")

// Method:
// rs_GetTimeXML
//
// Description:
// Returns current time in XML format
//
// --------------------------------------------------

C_TEXT($1)
C_TEXT($answer_t)
$answer_t:="<root><time>"+String(Current time)+"</time></root>"
WEB SEND TEXT($answer_t;"text/xml")

Handling HTTP GET Parameters REST Method

The next example method is rs_GetTime_HTTPGet. The method expands on


the first example methods and combines them into one and uses a HTTP GET
parameter to select which format the Time should be displayed in. The
parameter name expected is “format” and the possible values are “text”,”json”,
or “xml”. The parameters are obtained using the WEB GET VARIABLES
command and then using 4D code to parse and validate the values to respond
with the correct format.

// Method:
// rs_GetTime_HTTPGet
//
// Description:
// Returns current time in requested format
//
// HTTP GET Parameters
// "format":"text","json", or "xml"
//
// --------------------------------------------------

C_TEXT($1)
C_LONGINT($position_l)
ARRAY TEXT($vNames_at;0)
ARRAY TEXT($vValues_at;0)
ARRAY TEXT($hNames_at;0)
ARRAY TEXT($hValues_at;0)
C_OBJECT($object_o)
C_TEXT($answer_t)
C_TEXT($format_t)
10
WEB GET VARIABLES($vNames_at;$vValues_at)
$format_t:="text/html"

If (Size of array($vNames_at)>0)
$position_l:=Find in array($vNames_at;"format")
If ($position_l>0)
Case of
: ($vValues_at{$position_l}="text")
$answer_t:=String(Current time)
: ($vValues_at{$position_l}="json")
OB SET($object_o;"time";String(Current date))
$answer_t:=JSON Stringify($object_o)
: ($vValues_at{$position_l}="xml")
$answer_t:="<root><time>"+String(Current
time)+"</time></root>"
$format_t:="text/xml"
End case
End if
End if
WEB SET HTTP HEADER($hNames_at;$hValues_at)
WEB SEND TEXT($answer_t;$format_t)

To prevent any incorrect parameters, error handling was added to respond with
a 400 Error Code along with a short message of what was wrong. In addition to
relaying a response the headers were also formed to set the status code to 400.
This is done by using the WEB SET HTTP HEADER command to pass an array
of header names and an associated array of values to build the header. The
status header is named “STATUS” and the value set to “400 BAD REQUEST”.
Inspecting the page will show the status as so:

Image 2: Chrome Inspector Showing a Red Mark Stating a Bad Request

Image 3: Chrome Inspector Showing a Green Mark Stating Request was OK

11
Below is the updated HTTP GET Method with error handling:

// Method:
// rs_GetTime_HTTPGet
//
// Description:
// Returns current time in requested format
//
// HTTP GET Parameters
// "format":"text","json", or "xml"
//
// --------------------------------------------------

ON ERR CALL("errHandler")

C_TEXT($1)
C_LONGINT($position_l)
ARRAY TEXT($vNames_at;0)
ARRAY TEXT($vValues_at;0)
ARRAY TEXT($hNames_at;0)
ARRAY TEXT($hValues_at;0)
C_OBJECT($object)
C_TEXT($answer_t)
C_TEXT($format_t)

WEB GET VARIABLES($vNames_at;$vValues_at)


$format_t:="text/html"

If (Size of array($vNames_at)>0)
$position_l:=Find in array($vNames_at;"format")
If ($position_l>0)
Case of
: ($vValues_at{$position_l}="text")
$answer_t:=String(Current time)
: ($vValues_at{$position_l}="json")
OB SET($object;"time";String(Current date))
$answer_t:=JSON Stringify($object)
: ($vValues_at{$position_l}="xml")
$answer_t:="<root><time>"+String(Current
time)+"</time></root>"
$format_t:="text/xml"
Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")
$answer_t:="Error 400: Bad Request <br/>Invalid Parameter
Value"
End case
Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")

12
$answer_t:="Error 400: Bad Request <br/>Invalid Parameter
Name"
End if
Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")
$answer_t:="Error 400: Bad Request <br/>Incorrect Number of
Parameters"
End if
WEB SET HTTP HEADER($hNames_at;$hValues_at)
WEB SEND TEXT($answer_t;$format_t)

ON ERR CALL("")

Handling HTTP POST Parameters REST Method

As explained a POST method can be more secure as parameters are sent in the
body of the request and not in the URI. But a body does not come in a standard
format and as such will benefit from an error handler. The next sample method,
rs_GetTime_HTTPPost, will be set up to expect a JSON format HTTP body.
The method starts off by applying the err_handler, error handling method,
which will mainly be used to capture the error for when the body is not in JSON
format and is passed through the JSON Parse command. The body is then
parsed and passed into two sets of arrays for names and values and then
passed through the process as rs_GetTime_HTTPGet.

// Method:
// rs_GetTime_HTTPPost
//
// Description:
// Returns current time in requested format
//
// HTTP POST Parameters
// "format":"text","json", or "xml"
//
// --------------------------------------------------

ON ERR CALL("errHandler")

C_TEXT($1)
C_LONGINT($position_l)
ARRAY TEXT($vNames_at;0)
ARRAY TEXT($hNames_at;0)
ARRAY TEXT($hValues_at;0)
C_OBJECT($object_o)
C_OBJECT($body_o)
C_TEXT($answer_t)
C_TEXT($value_t)
C_TEXT($format_t)
C_TEXT($body_t)

13
WEB GET HTTP BODY($body_t)
$body_o:=JSON Parse($body_t)
OB GET PROPERTY NAMES($body_o;$vNames_at)
$format_t:="text/html"

If (Size of array($vNames_at)>0)
$position_l:=Find in array($vNames_at;"format")
If ($position_l>0)
$value_t:=OB Get($body_o;"format")
Case of
: ($value_t="text")
$answer_t:=String(Current time)
: ($value_t="json")
OB SET($object_o;"time";String(Current date))
$answer_t:=JSON Stringify($object)
: ($value_t="xml")
$answer_t:="<root><time>"+String(Current
time)+"</time></root>"
$format_t:="text/xml"

Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")
$answer_t:="Error 400: Bad Request <br/>Invalid Parameter
Value"
End case
Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")
$answer_t:="Error 400: Bad Request <br/>Invalid Parameter
Name"
End if
Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")
$answer_t:="Error 400: Bad Request <br/>Incorrect Number of
Parameters"
End if
WEB SET HTTP HEADER($hNames_at;$hValues_at)
WEB SEND TEXT($answer_t;$format_t)

ON ERR CALL("")

Because an HTTP POST contains a body, the request cannot simply be called
through a browsers address bar. To test these REST methods a 4D Method could
be used to make an HTTP REQUEST call or a third party tool like Postman can
be used.

14
Access Control for REST

The next example is how to set up access control for REST methods. Since the
4D REST Server is a Web Server that can allow numbers of connections if the
REST API is made widely available to numbers of users it would be best to
create 4D data tables to keep track of the users.

Image 4: Users Table to Contain Login Credentials.

Then a second table for the tokens should be created as many tokens will be
created as a timeout will be applied and IP checks will be included for further
security. Being a very volatile table, it should be kept separately from the less
volatile Users table.

Image 5: Tokens Table to Contain token information.

The demo uses a simple website to demonstrate a simple implementation of


access control. The files are in the WebFolder. The entry site is the demo.html
file and the rest of the page is generated by running JavaScript functions from
the /js/script.js file and html code sent by the 4D REST methods’ responses. The
web page is:

http://localhost/demo.html

15
Image 6: Login page of Demo Website

This page will display a very simple login. To log in the credentials are:

Username: user

Password: pass

The “Login” button will run a JavaScript function, “onSubmit”, to format an HTTP
POST request by first encrypting the password using SHA1. Passwords should
never be sent as plaintext and this is done using the “SHA1” function. Then
formatting the username and encrypted password into a JSON format body of

“Username”: plaintext_username_value,

”Password”: SHA1_encrypted_password

This is then sent as the body to the following rs_login 4D REST method as:

http://localhost/4daction/rs_login

// Method:
// rs_Login
//
// Description:
// Generates an authorization token if passed login
// credentials are valid.
//
// HTTP POST Parameters
// "Username":{user name}
// "Password":{SHA1 encrypted password}
// --------------------------------------------------

16
ON ERR CALL("errHandler")

C_TEXT($1)
ARRAY TEXT($vNames_at;0)
ARRAY TEXT($hNames_at;0)
ARRAY TEXT($hValues_at;0)
C_OBJECT($body_o)
C_TEXT($answer_t)
C_TEXT($body_t)

WEB GET HTTP BODY($body_t)


$body_o:=JSON Parse($body_t)
OB GET PROPERTY NAMES($body_o;$vNames_at)

APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")

If (Size of array($vNames_at)>1)
If (Find in array($vNames_at;"Username")>0)
If (Find in array($vNames_at;"Password")>0)
QUERY([Users];[Users]name=OB Get($body_o;"Username");*)
QUERY([Users]; & ;[Users]password=OB
Get($body_o;"Password"))
$hValues_at{Size of array($hValues_at)}:="200 OK"
If (Records in selection([Users])=1)
CREATE RECORD([Tokens])
[Tokens]token:=Generate UUID
[Tokens]timeout_t:=Current time
[Tokens]timeout_d:=Current date
SAVE RECORD([Tokens])
$answer_t:="{\"html\":\"<button type=\\\"button\\\"
onclick=\\\"return getTime()\\\">Get Current Time and
Date</button>\",\"token\":\""+[Tokens]token+"\"}"

Else
APPEND TO ARRAY($hNames_at;"Content-Type")
APPEND TO
ARRAY($hValues_at;"application/json;charset=UTF-8")
$answer_t:="{\"para\":\"Incorrect Username or
Password\"}"
End if
Else
$answer_t:="{\"html\":\"Error 400: Bad Request <br/>Invalid
Parameter Name\"}"
End if
Else
$answer_t:="{\"html\":\"Error 400: Bad Request <br/>Invalid
Parameter Name\"}"
End if

17
Else
$answer_t:="{\"html\":\"Error 400: Bad Request <br/>Invalid
Parameters Sent\"}"
End if
$format_t:="application/json"
WEB SET HTTP HEADER($hNames_at;$hValues_at)
WEB SEND TEXT($answer_t;$format_t)

ON ERR CALL("")

The method confirms the credentials and sends back, in JSON format, a token
and HTML to format the page if valid or an error message if not. The token is
then stored into a global variable on the client side and the page is reloaded to
display a button.

Image 7: Page After Successfully Logging In

The button will execute another JavaScript function, “getTime” that sends an
HTTP POST request to the rs_GetTimeDate 4D REST method with the token as
a parameter. If the token is not older than 30 seconds old, a response with the
current date and time in JSON format will be sent as a response if not a
message stating the token has expired will be sent.

// Method:
// rs_GetTimeDate
//
// Description:
// Returns current time and date in JSON format if
// valid token and correct format is passed. If not
// returns descriptive error.
//
// --------------------------------------------------

ON ERR CALL("errHandler")

C_TEXT($1)
ARRAY TEXT($vNames_at;0)
ARRAY TEXT($hNames_at;0)
ARRAY TEXT($hValues_at;0)
C_OBJECT($body_o)
C_TEXT($answer_t)
C_TEXT($body_t)

WEB GET HTTP BODY($body_t)

18
$body_o:=JSON Parse($body_t)
OB GET PROPERTY NAMES($body_o;$vNames_at)

$answer_t:="{\"html\":\"Token Expired: Reload Page and Log back


in\"}"

If (Size of array($vNames_at)>0)
If (Find in array($vNames_at;"token")>0)
QUERY([Tokens];[Tokens]token=OB Get($body_o;"token"))
If (Records in selection([Tokens])=1)
Case of
: ((Current date=[Tokens]timeout_d) & (Current time-
[Tokens]timeout_t<20))

$answer_t:="{\"html\":\"Date: "+String(Current
date)+"<br/>Time: "+String(Current time)+"<br/><button
type=\\\"button\\\" onclick=\\\"return getTime()\\\">Get Current
Time and Date</button>\"}"

: (((Current date-[Tokens]timeout_d)=1) &


(([Tokens]timeout_t-Current time)>Time("23:59:00")))

$answer_t:="{\"html\":\"Date: "+String(Current
date)+"<br/>Time: "+String(Current time)+"<br/><button
type=\\\"button\\\" onclick=\\\"return getTime()\\\">Get Current
Time and Date</button>\"}"

End case
End if
Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")
$answer_t:="{\"html\":\"Error 400: Bad Request <br/>Invalid
Parameter Name\"}"
End if
Else
APPEND TO ARRAY($hNames_at;"STATUS")
APPEND TO ARRAY($hValues_at;"400 BAD REQUEST")
$answer_t:="{\"html\":\"Error 400: Bad Request <br/>Invalid
Parameters Sent\"}"
End if
WEB SET HTTP HEADER($hNames_at;$hValues_at)
WEB SEND TEXT($answer_t;"application/json")

ON ERR CALL("")

19
Image 8: Results of Clicking Button Before Token Expires

Image 9: Results of Clicking Button after Token Expires

This was only one method of an authentication technique and there are a
number of others. Some other ways of adding security are to check for the IP
Address of the request or even replacing the token after each use. Implementing
access control and authentication can greatly improve the security and integrity
of an HTTP Server and is worth the additional effort.

Conclusion
------------------------------------------------------------------------------------------------------------------------------------------------------------------

This Technical Note provided information on how to implement a REST Server in


4D. Since a REST server is an HTTP Server that has REST services available a REST
Server can be hosted through 4D’s Web Server.

The REST services are accessible through HTTP GET and HTTP POST requests by
calling methods that have been made available through 4daction. HTTP GET
parameters can be parsed through the use of WEB GET VARIABLES and HTTP
POST parameters can be obtained through the WEB GET HTTP BODY command
and then used for even more complex REST Services. These REST services can also
be limited by implementing a form of access control such as a temporary token.

Since REST services are very flexible and contain very little overhead they are a
powerful way of utilizing the internet to perform actions between independent
systems.

20

You might also like