Tutorial 1 e 2
Tutorial 1 e 2
A fast way to serve and consume data with Delphi and Lazarus
PART I, II of V
2019
I have skipped the installation instructions, If you have some question have a look at
installation guide, otherwise you can send to me an e-mail at ricardodarocha@outlook.com.
In development…
I’m Ricardo da Rocha, an industrial designer and programmer with focus in design of
interfaces and development of software for Industry and for Business Intelligence. I have
practice the volunteer teaching to improve my methodologies to solve Real World
Challenges. I love to learn with the community and with my students.
I’m graduated as Industrial Designer, have been worked at UEMG as a Volunteer Professor,
and as product designer at Estudio Miron. After, I went to Austria to study Master Course of
Material Engineering, as part of UFOP and ThyssenKrupp partnership. I’ve experienced a
large project of steel scrap classification, which inspired myself to keep studying and
working with software, data structure and data visualization. Today my major is to help
people to understand their business, and to help developers to do best software’s.
This is a small contribution for Delphi-Lazarus Rest Data Ware Community, which doesn't
measures efforts on the development of stable and secures version of Rest Dataware, and
for the people around the world that want to learn and to use Rest Data Ware in their way.
ÉNóix
Acknowledgment ................................................................................................................... 5
Step 1 RestServicePooler.................................................................................................... 7
Chapter 2 .......................................................................................................................... 11
Request ................................................................................................................................... 14
Response ................................................................................................................................ 15
Contact ................................................................................................................................. 20
Step 1 RestServicePooler
In a new application just grab the component RestServicePooler from the pallete
Rest Dataware Service.
This component will control a Port of your Server. To configure this component is very easy.
Set the ServicePort you want to control.
If you want to create a secure connection just set True the parameter
“ServerParams>HasAuthentication”.
You can change the user and password at its respective properties.
7
Step 2 Configure your DWDatamodule Instance
I recommend you add the unit “uDWDatamodule.pas” into your project, but however you
need to be shure you will never change the uDWDatamodule.pas, because when you update
Restdw installation we will lose those changes.
TServerMethodDataModule uDWDatamodule.pas
DMServer1 uDmServer.pas
Finding DWDatamodule.pas
8
Creating inherited datamodule
Now go to File> New> Other and choose the option “Inherited Item”, choose
ServerMethodDatamodule and click OK.
We are creating a new datamodule you will put all resource we share with client: Connections,
Events, WebPascal etc.
I suggest you to rename the Datamodule1 as DMServer1 and the unit as UDmServer.pas
9
Step 3 Activate and run
I changed the form 1 to frmFirstServer and created a button1 with instruction
That is all. You can compile and run your first server, and to prove you are a server running, go
to Webbrowser and type “localhost:8082”
10
Chapter 2
11
Chapter 2
Create your own resources
In my new tutorial you will learn more about how to serve data using resources in Rest-
Dataware.
There are three components that will provide resources from the Server side to the clients.
It means there are three kinds of resources you can share, that you need to know.
12
Resource 1 RestDwPoolerDb
This component is pretty simple and will empower your Delphi Client to see the connection
of other side of server. Also, it will allow you create your own SQL instructions in the CLIENT
side, without the need of recompile the server.
b) Use one of those Drivers you installed. Look at pallete Rest Dataware – Core Drivers.
In this example I’m using TRestDWDriverFD (Firedac Driver)
This component is visible only if you create a Delphi Client. For that reason I will
cover this component in details next tutorial (4-Create your First Database Client)
To understand the use of DW Events you need to know the basics of json (java script object
notation). In abstract this is a way to transmit objects from different applications, usually
thought HTTP protocol. The json looks like a structured database, which allows creating
nested objects too.
13
For example, suppose you have an API schema that provides the following resources:
We can configure each resource to return its respective json, using variable result
Understanding API
Request
Run your server at port 8082. Go to your web browser and type the route
localhost:8082/api/Version
14
As long as you created your resources on the server, the api localhost: 8082/ will responds
to your request using routes that you give implemented: 1
Ps. When you type /ServerTime in the browser you are calling the method GET
Response
The server would returns the following structure if you set up the variable result with the
json string:
{“name”: “RDW Server 1”, “version”: “1.0”, “title”: “tutorial 2”, “student”: “yourname”}
Result := ‘1.0’;
Uses SysUtils;
Result := ‘{‚result‛: ‚’ + formatdatetime(‘dd/mm/yyyy hh:nn:ss.zzz’, now) + ‘‛}’;
1
We will use just the notation after the baseurl localhost:8082/api
Example: /ServerTime
15
4. Create the resource ServerIP
Supose you have a most sophisticated method you want to treat some information, or
process something, you can create other units and use the method “OnReplyEvent” to
centralize the responses.
In this example I will keep the methods at the same reply. That reply uses INDY to access
another API at internet
Procedure TDMServer1.APIEventsServerTimeReplyEvent(…
Var Response: IHTTPResponse;
Ip: String;
Begin
Response := NETHttpClient1.Get(‘Http://checkup.dyndns.org/’);
IP := Response.ContentAsString;
Result := format(‘{‚ip‛: ‚’%s’‛}’, [IP]);
End;
Furthermore
The techniques I have been shown to you despite RDW ServerEvents looks very simple.
Indeed they are simple, however they are very powerful. For example, let me show how to
easily serialize an object to json, using a Model (the class of the object) and one line of code.
Type
TFood = class
Category: String;
Name: String;
Description: String;
Price: String;
Constructor Create(Category, Name, Description: String; Price: Currency);
End;
Implementation
Procedure TDMServer1.APIDisOfDayReplyEvent(…
Var Dish: TFood;
Begin
Dish := TFood.Create(‘Indonesian’, ‘Ayam goreng’, ‘Indonesian fried chicken’, 10000.00);
Result := TJson.ObjectToJsonObject(Dish).ToString;
FreeAndNil(Dish);
End;
16
Look this amazing 1:N Collection and its behavior;
Type
TFood = class
Category: String;
Name: String;
Description: String;
Price: String;
Constructor Create(Category, Name, Description: String; Price: Currency);
End;
Implementation
Procedure TDMServer1.APIDisOfDayReplyEvent(…
Var
Dish1, Dish2, Dish3: TFood;
Menu:TArray<TFood>;
Begin
Dish1 := TFood.Create(‘Indonesian’, ‘Ayam goreng’, ‘Indonesian fried chicken’, 10000.0);
Dish2 := TFood.Create(‘Italian, ‘Pizza’, ‘Sicilian Ingredients’, 30000.0);
Dish3 := TFood.Create(‘Japonese’, ‘Sushi’, ‘Fresh Tuna’, 22000.0);
Menu := TArray<TDish>.Create;
Menu.Add(Dish1);
Menu.Add(Dish2);
Menu.Add(Dish3);
Result := TJson.ObjectToJsonObject(Menu).ToString;
FreeAndNil(Dish);
FreeAndNil(Menu);
End;
Chapter 3
Server Events in Deep
I told you before that the Server events responses the HTTP verbs GET PUT POST DELETE,
and now we will see how it works.
Usually I use the method onReplyEvent to respond no complex requests, however I suggest
you to learn the most flexible onReplyEventByType whose var RequestType give you the chance
to return different results depending the kind of the request.
procedure TServerMethodDM.apiDishOfDayReplyEventByType(…
begin
case RequestType of
rtGet: Result := ‘{‚Ayam goring‛:1000.00}’;
rtPost: SaveInDatabase(Params.ItemsString['promotiontoday'].Asstring);
rtDelete: DeleteFood(Params.ItemsString['ID'].Asstring);
end;
end;
17
Understanding HTTP
Suppose you want to get some information from Server, it’s pretty clear that you will use
the method GET. Actually this is the default method of HTTP. Because that is the default
you just need to call the route directly in the browser, and you don’t need to specify the verb
you want for.
However if you debug the request header at the server you will see the browser sent the
addres GET localhost:8082/api/ServerTime.
For example, if you create a web app page a Restaurant, that shows the customers the
foods menu, you can call a GET. Otherwise if you want to create a WEB Application for the
restaurant owner, to himself register the foods, and update the prices, and inform the dish
of the day for example, then you will call the method POST/PUT. You need to create a route
to the customer register the order, and also to show the cost of dinner.
Creating parameters
PUT LocalHost:8082/api/newOrder?foodid=614&persons=2&table=12
For example, to inform the kitchen that the customer chooses a food, you need to specify in
the request which food it chooses, and which table the customer is sitting at. The
parameters are attached in the header of request, such as the verb and the route.
To create a parameter choose Events List at the ‘api’ component, and then choose the event
you want to configure. For example, I choose the event DishOfDay we created before. You
will see the DishOfDay Event has a name, jmPureJson as a mode, and DWParams which
avoid you to create some parameters. Let’s click on the DWParams and choose […] to edit.
18
You can create many parameters as you want.
Properties of ParamMethod
ParamName The name you want to pass during request Example: 'promotiontoday'
Encoded Default behavior True
ObjectDirection In-Out direction. Also accept both odIN, just accept from client
ObjectValue Any Delphi type you want ovString
TypeObject Default type toParam
get /food
get /food?category=pizza
put /food?name= Ayam%20goring&category=Indonesian&price=1000
put /order? foodid=614&persons=2&table=12
get /order? table=12
post /cancelorder? table=12&reason=too late
delete /order?item=614&reason=unavailable&choosenewitem=true
19
Contact
If you have some question about RestDW have a look at installation guide, otherwise you
can send to me an e-mail at ricardodarocha@outlook.com.
Visit my github to get some Delphi example. I will publish exclusive contents about RestDw
library.
20