How to declare a POST request in Delphi REST Datasnap? - json

I'm trying to write a function that will insert informations in my database using JSON or multiple parameters in the URL.
I already managed to create a function that returns informations from my database to the client but not the other way. Every example I find explains how to creat a JSON but not how to receive it with System.JSON (Delphi 10.2)
Here is a code sample for a GET function actually working on my Datasnap :
function TDM_Test.DS_getArticles(pStock : String): string;
begin
try
VGOutils.PR_logs('Get all articles from table');
VGOutils.FU_CheckConnect('1234567890');
with VGOutils.SQ_temp1 do
begin
SQL.Clear;
SQL.Add('SELECT code, name, price, seller, departement FROM articles');
SQL.Add('WHERE stock');
ParamByName('stock').AsString := pStock;
VGOutils.SQ_temp1.Open;
end;
GetInvocationMetadata().ResponseCode := 200;
GetInvocationMetadata().ResponseContent :=
VGOutils.PR_JSON(VGOutils.SQ_temp1, ['code', 'name', 'price', 'seller']);
except on E: Exception do
PR_error(E.Message);
end;
VGOutils.PR_Disconnect;
end;
Now I need the client to send me new articles to INSERT in my database.
The only thing that I cant figure out is how to declare the function and it's parameters.
I want the client to be able to send me a JSON with this correct format
{"article":[{"code":"AAA","name":"car","price" : "10400.90", "sellers" : [{"seller1" : "Automaniac", "seller2" : "Autopro" }]}]}
Now I know how to parse it with TJSONObject.ParseJSONValue() by reading this JSON RadStudio
EDIT
If this JSON string is hardcoded it works fine with ParseJSONValue but if the string is taken from the URL my JSONstring only contains "]}" and obviously there is nothing to parse.
function TDM_Test.DS_insertArticles(pUrlJsonString: String): string;
// Hardcoded JSON string
jsonString := '{"article":[{"code":"AAA","name":"car","price" : "10400.90", "sellers" : [{"seller1" : "Automaniac", "seller2" : "Autopro" }]}]}';
JSonValue := TJSONObject.ParseJSONValue(jsonString);
// String received in url
jsonString := pUrlJsonString;
JSonValue := TJSONObject.ParseJSONValue(pUrlJsonString);

I found the way I wanted it to work by not using the string parameter of the function but instead using the Custom body by passing a JSONObject.
The method is POST and the content type is application/JSON.
function TDM_Test.DS_insertArticles(pUrlJsonObj: TJSONObject): string;
JSonValue := TJSONObject.ParseJSONValue(pUrlJsonObj);
// Retrieve data for database fields
artCode := JSONValue.GetValue<string>('article[0].code');
artName := JSONValue.GetValue<string>('article[0].name');
artPrice := JSONValue.GetValue<string>('article[0].price');
//... Proceed to INSERT SQL with these values

Related

Delphi, TSuperObject > from JSON to Object

I have in Delphi XE4, TSuperObject:
TAspTransactionBasicData = Class(TObject)
Currency : Byte;
Amount : Currency;
constructor Create(aCurrency: Byte; aAmount: Currency);
end;
TStartWorkflowWithBasicData = Class(TObject)
AdditionalData : TAspTransactionBasicData; // here it is as an Object
TypeOfWorkflow : Byte;
constructor Create(aAdditionalData: TAspTransactionBasicData; aTypeOfWorkflow: Byte);
function toJSon(TObject:TStartWorkflowWithBasicData):String;
end;
and the ToJSon function puts the object into JSON:
function TStartWorkflowWithBasicData.toJSon(TObject:TStartWorkflowWithBasicData):String;
Var
JSon: ISuperObject;
RttiCont: TSuperRttiContext;
begin
Result := '';
RttiCont := TSuperRttiContext.Create;
JSon := RttiCont.AsJson<TStartWorkflowWithBasicData>(TObject); // Insert the object into JSON
Result := JSon.AsJSon(False);
RttiCont.Free;
end;
and I would also need the exact opposite, a function fromJSon, which will read the JSON (where the object was inserted) back into the object, but I'm groping...
Can you please advise me?
I can't help you with SuperObject, but kbmMW contains a very complete XML, JSON, YAML, BSON, MessagePack + CSV and in next release also TXT (fixed format) serializer/deserializer and object marshaller/unmarshaller.
It will easily convert both ways, and even between formats.
kbmMW Community Edition contains all (except the new TXT format), and is free, even for commercial use (limited by license).
https://components4developers.blog/2019/03/11/rest-easy-with-kbmmw-24-xml_json_yaml_to_object_conversion/

TRESTRequest JSON POST issue in Delphi

I'm trying to send JSON POST request to an API using a TRESTClient (Delphi 10.4/Windows 10), but I'm receiving a 409 conflict indicating "No input found". Using the same code in (Delphi XE6/Windows 10) I get a REST request failed: Socket Error # 10054 Connection reset by peer.. Using WireShark I was able to see that Delphi XE6 was sending the request with TLS 1.0 and Delphi 10.4 is using TLS v1.2. The API service accepts only TLS v1.2. Is there a way to use these REST components in Delphi XE6 to deliver the request with TLS 1.2?
I beleived my problem was that I was JSON encoding all the input with the code:
// Assign JSON
sl := TStringList.Create;
sl.Add('locations=[{"address":"Test1","lat":"52.05429","lng":"4.248618"},{"address":"Test2","lat":"52.076892","lng":"4.26975"},{"address":"Test3","lat":"51.669946","lng":"5.61852"},{"address":"Sint-Oedenrode, The Netherlands","lat":"51.589548","lng":"5.432482"}]');
and then assigning it to the Request Body with RESTRequest.AddBody(sl);, whereas the API only expects the value of the locations parameter to be JSON.
I have updated the code to assign the JSON to a String and used the RESTRequest.Params.Items[0].name := 'locations'; and RESTRequest.Params.Items[0].Value := s; to add the string to the request body.
Here's my updated code:
procedure TMainForm.btn_RouteXL_PostClick(Sender: TObject);
var
s, sResult, AError: String;
jsObj: TJSONObject;
AJSONValue, jsResponse: TJSONValue;
AParameter: TRESTRequestParameter;
AStatusCode: Integer;
begin
//ResetRESTComponentsToDefaults;
s := '[{"address":"Test1","lat":"52.05429","lng":"4.248618"},{"address":"Test2","lat":"52.076892","lng":"4.26975"},{"address":"Test3","lat":"51.669946","lng":"5.61852"},{"address":"Sint-Oedenrode, The Netherlands","lat":"51.589548","lng":"5.432482"}]';
RESTClient.BaseURL := 'https://api.routexl.com/tour';
RESTClient.ContentType := 'ctAPPLICATION_X_WWW_FORM_URLENCODED';
RESTClient.Authenticator := HTTPBasic_RouteXL;
RESTRequest.Method := TRESTRequestMethod.rmPOST;
RESTRequest.Params.AddItem; //Adds a new Parameter Item
RESTRequest.Params.Items[0].name := 'locations'; //sets the name of the parameter. In this case, since I need to use 'locations=' on the request, the parameter name is locations.
RESTRequest.Params.Items[0].Value := s; //Adds the value of the parameter, in this case, the JSON data.
RESTRequest.Params.Items[0].ContentType := ctAPPLICATION_X_WWW_FORM_URLENCODED; //sets the content type.
RESTRequest.Params.Items[0].Kind := pkGETorPOST; //sets the kind of request that will be executed.
RESTRequest.Execute;
try
memo_ResponseData.Lines.Add('************JSONText*******************');
memo_ResponseData.Lines.Add(RESTResponse.JSONValue.ToString);
//Memo1.Lines.Add('JSONValue :'+RESTResponse.JSONValue.Value);
memo_ResponseData.Lines.Add('StatusText :'+RESTRequest.Response.StatusText );
memo_ResponseData.Lines.Add('StatusCode :'+IntToStr(RESTRequest.Response.StatusCode ));
memo_ResponseData.Lines.Add('ErrorMesage:'+RESTRequest.Response.ErrorMessage);
memo_ResponseData.Lines.Add('************Content*******************');
memo_ResponseData.Lines.Add(RESTRequest.Response.Content);
memo_ResponseData.Lines.Add('************Headers*******************');
memo_ResponseData.Lines.Add(RESTRequest.Response.Headers.Text);
except
on E: Exception do
begin
memo_ResponseData.Lines.Add('************Error*******************');
memo_ResponseData.Lines.Add('Error : ' +E.Message);
memo_ResponseData.Lines.Add(E.ClassName);
memo_ResponseData.Lines.Add('************Error*******************');
memo_ResponseData.Lines.Add('Error : '+RESTResponse.Content);
end;
end;
end;
I'm able to get it to work in Postman using a key-value pair, by assigning the key as locations and the value as the contents of sl as seen in the screenshot. But I'm unable to translate that to Delphi.

Delphi HTTPClient root page

I use THTTPClient instead of Indy to get a Json value from my API. I do it like this :
Url := 'http://example.com/api/index.php?get&latitude=' +
TNetEncoding.Base64.Encode(MapView.Location.Latitude.ToString)
+ '&longitude=' + TNetEncoding.Base64.Encode(MapView.Location.Longitude.ToString);
Json := TToolHTTP.Get(Url);
The method to get is write below :
class function TToolHTTP.Get(aUrl: string): string;
var
Client : THTTPClient;
Response: IHTTPResponse;
begin
Result := '';
Client := THTTPClient.Create;
try
try
Response := Client.Get(aUrl);
Result := Response.ContentAsString;
except
ShowMessage('Error');
end;
finally
FreeAndNil(Client);
end;
end;
The first time or two first time I get my Json value, the third time I call this method with same url I get the content of the root page (http://example.com/index.html), and then when I call it the 4 time I get my Json. It's look like really random, but for sure I always get a Status Code HTTP 200.
Why sometime I get the html of the root page ?

Passing a JSON object to Datasnap Server application

I have a datasnap application server and a client witten in Delphi Tokyo 10.2. I need to know whether I do the communication between the two correctly. I will write down the client code here :
Client Code:
procedure TRemoteAcessModule.InitialiseRESTComponents(BaseURL: string);
var
ReqParam : TRESTRequestParameter;
begin
//URL to which client has to connect
RESTClient1.BaseURL := BaseURL;//'http://192.168.110.160:8080/datasnap/rest/TserverMethods1';
RESTClient1.Accept:= 'application/json, text/plain; q=0.9, text/html;q=0.8,';
RESTClient1.AcceptCharset := 'UTF-8, *;q=0.8';
RESTRequest1.Client := RESTClient1;
RESTRequest1.Response := RESTResponse1;
RESTResponse1.RootElement := 'Rows';
RESTResponseDataSetAdapter1.Response := RESTResponse1;
RESTResponseDataSetAdapter1.Dataset := FDMemTable1;
RESTResponseDataSetAdapter1.NestedElements := true;
end;
class function TItemsHelper.InsertItem(item: TItem): boolean;
var
ds : TDataset;
begin
ds := RemoteAcessModule.CallResource2('InsertItem', TJson.ObjectToJsonString(item));
if ds.Fields[0].AsInteger > 0 then
result := true
else
result := false
end;
function TRemoteAcessModule.CallResource2(ResourceName: string): TDataset;
begin
CallResourceNoParams(ResourceName);
result := GetQueryResult;
end;
procedure TRemoteAcessModule.CallResource(ResourceName, Params: string);
begin
RESTResponseDataSetAdapter1.Dataset := TFDMemTable.Create(self); //new
RESTRequest1.Resource := ResourceName;
RESTRequest1.ResourceSuffix := '{qry}';
RESTRequest1.AddParameter('qry', TIdURi.ParamsEncode(Params), TRESTRequestParameterKind.pkURLSEGMENT, [poAutoCreated]);
RESTRequest1.Execute;
RESTResponseDataSetAdapter1.Active := true;
RESTRequest1.Params.Delete('qry');
RESTRequest1.ResourceSuffix :='';
end;
At server side, I have written a function which decodes the json and inserts the item data into the database.
So, to insert an item, i have call TItemsHelper.InsertItem by passing the Titem object i need to insert. This works. But the doubts I have are :
RESTRequest1.AddParameter('qry', TIdURi.ParamsEncode(Params), TRESTRequestParameterKind.pkURLSEGMENT, [poAutoCreated]);
is the way mentioned above the correct method to pass the encoded
json object to server (making it a part of the URL ) ? If not how
can i send json data to datasnap server ?
Can I get some advise on things I have done incorrectly here ?
Thanks in advance for your patience to go through this. Looking forward for some guidance.
If you have a DataSnap REST Server, there is a wizard to build DataSnap client application. The REST Client Library you use is for generic REST server. If you have DataSnap Server, and you want Delphi client application, you can take advantage to use wizard DataSnap REST Client Module.
BTW, Embarcadero now recommends RAD Server to develop REST server.
As #erwin Mentioned you should check the DataSnap REST Client Module. At least that's how I have set up my Proof of Concept application I made for a client. For example the DataSnap Server has a few REST Client Module which has a public method called GetListByFetchParams which returns a TFDJSONDataSets. The implementation looks a bit like this :
function TBaseServerMethods.InternalGetListByFetchParams(aFetchParams: TFetchParams): TFDJSONDataSets;
begin
{$IFDEF USE_CODESITE}
CSServerMethods.TraceMethod( Self, 'InternalGetListByFetchParams', tmoTiming );
CSServerMethods.Send( csmFetchParams, 'aFetchParams', aFetchParams );
{$ENDIF}
Result := TFDJSONDataSets.Create;
// Close the ListDataSet
ListDataSet.Close;
// Open the List DataSet
ListDataSet.Open;
// Add the ListDataSet to the result using a predefined name.
TFDJSONDataSetsWriter.ListAdd( Result, ListDataSetName, ListDataSet );
{$IFDEF USE_CODESITE}
CSServerMethods.Send( 'qryList.SQL', ListDataSet.SQL );
CSServerMethods.Send( csmFDDataSet, 'qryList DataSet Contents', ListDataSet );
{$ENDIF}
end;
The most important thing is that I create a TFDJSONDataSets which I set up as th result. I removed some code but in short the aFetchParams is used to alter the SQL Statement of the FireDaC Query component which is referenced by ListDataSet and it then Opens that dataset. Next I use a TFDJSONDataSetsWriter.ListAdd call to add our ListDataSet to the TFDJSONDataSets which is the result of the function.
Client Side I need some code too. This code will call the remote method on the DataSnapServer which will return the TFDJSONDataSets and which I can then deserialise into the TFDMemTables on the client :
procedure TBaseAgent.FetchListWithParams(aFetchParams : TFetchParams);
var
oListData : TFDJSONDataSets;
oKeyValues : TDictionary< String, String >;
begin
{$IFDEF USE_CODESITE}CSAgent.TraceMethod( Self, 'FetchListWithParams', tmoTiming );{$ENDIF}
oListData := FetchListWithParamsFromServer( aFetchParams );
try
tblList.AppendData( TFDJSONDataSetsReader.GetListValue( oListData, 0 ) );
tblList.Open;
finally
FreeAndNil( oListData );
end;
end;

How to serialize JSON key containing dots (like e.g. IP address) with SuperObject?

I'm trying to save JSON where IP is a key. Expected JSON result is:
{"SnmpManagers":[{"10.112.25.235":162}]}
The Delphi SuperObject code:
const
IpAddr = '10.112.25.235';
Port = 162;
var
tmp: TSuperObject;
begin
tmp := TSuperObject.Create;
tmp.I[IpAddr] := Port;
Json.A['SnmpManagers'].Add(tmp);
end;
SuperObject parses dots as path delimiters of a JSON object:
{"SnmpManagers":[{"10":{"112":{"25":{"235":162}}}}]}
How to save IP as a JSON key correctly with SuperObject ?
The solution is to create JSON object from string
Json.A['SnmpManagers'].Add(SO(Format('{"%s":%d}', [IpAddr, Port])));
Another way to add (do not use with .O[] because AsObject gives nil for non existing keys):
// for a simple key-value object
Json.AsObject.S['1.2.3'] := 'a'; // gives us {{"1.2.3":"a"}}
Json.AsObject.S['4.5'] := 'b'; // gives us {{"1.2.3":"a"}, {"4.5":"b"}}
This also works:
var
tmp: ISuperObject;
begin
tmp := SO([IpAddr, port]);
Json.A['SnmpManagers'].Add(tmp);