Pieter van Wyk
Pieter van Wyk

Reputation: 2378

Cannot get values for query parameters when using POST in Delphi REST Server

I have written a REST server with an action POSTCameras to update. In the client i have te following

RESTClient.ResetToDefaults;
RESTClient.BaseURL := EditERServiceUrl.Text;
RESTRequest.Method := TRESTRequestMethod.rmGET;
RESTRequest.Resource := 'GetUpdateCameras';
RESTRequest.Params.AddItem('thislocn', '0000', TRESTRequestParameterKind.pkGETorPOST);
RESTRequest.Params.AddItem('cameras', '{"id":1,"name":"Camera 1"}', 
RESTRequestParameterKind.pkGETorPOST);
RESTRequest.Execute;

If I use rmGET, I can easily extract the parameters in the REST server using

ThisStore = Request.QueryFields.Values['thislocn'];
ThisCamera = Request.QueryFields.Values['camera'];

If I use rmPOST, the Query Fields are blank.

I'm not sure what I have to do to get the query parameters from the TWebRequest.

Upvotes: 2

Views: 1784

Answers (1)

Peter Wolf
Peter Wolf

Reputation: 3830

You didn't specify what kind of server technology do you use, but I guess it's DataSnap (REST server).

In your REST client code you manually add parameters of kind pkGETorPOST to the request. This is BTW the default kind when adding a parameter via method AddItem, so you don't need to specify it at all and use an invariant with just 2 parameters function AddItem(const AName, AValue: string): TRESTRequestParameter; overload;.

The documentation for pkGETorPOST clearly states

pkGETorPOST: Sends the parameter as a URL parameter (for GET requests) or as a body parameter (for POST/PUT requests).

That means in case of GET request, the parameters are transferred in query string of the URL, while in case of POST request they're sent in the body as x-www-form-urlencoded string. To read such values from the request's body in server code you have to use property ContentFields instead.

ThisStore = Request.ContentFields.Values['thislocn'];
ThisCamera = Request.ContentFields.Values['camera'];

If you insist on sending parameters in URL even for POST requests then add them as pkQUERY.

pkQUERY: Sends the Parameter explicitly as a URL parameter (for all requests), in contrast to pkGETorPOST, when parameter location depends on the request type.

Unfortunatelly pkQUERY wasn't available prior to Delphi 10.3 Rio.

Upvotes: 4

Related Questions