Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi REST API Post Sample

Can someone post a simple example of a JSON POST request to an API using Delphi 2005. I have found numerous examples using GET but the API provider does not allow requests via HTTP GET and does not support URL encoding parameters.

I am brand new to calling REST services (have used SOAP in the past) so please let me know if you require more information.

like image 673
BrianKE Avatar asked Mar 16 '12 19:03

BrianKE


2 Answers

You would just use Indy's TIdHTTP component and call the Post method. Pass the URL as the first argument and your JSON string as the second argument. Something like this:

procedure TForm1.Button1Click(Sender: TObject);
var
  jsonToSend: TStringList;
  http: TIdHTTP;
begin
  http := TIdHTTP.Create(nil);
  try
    http.HandleRedirects := True;
    http.ReadTimeout := 5000;
    jsonToSend := TStringList.create;
    try
      jsonToSend.Add('{ Your JSON-encoded request goes here }');
      http.Post('http://your.restapi.url', jsonToSend);
    finally
      jsonToSend.Destroy;
    end;
  finally
    http.Destroy;
  end;
end;

I'm assuming you are already able to encode and decode the JSON and that you were just asking how to perform an HTTP post using Delphi.

like image 152
Jeff Wilhite Avatar answered Oct 22 '22 11:10

Jeff Wilhite


One option, using some part of our mORMot Open Source framework:

uses SynCrtSock, SynCommons;
var t: variant;
begin
  TDocVariant.New(t);
  t.name := 'john';
  t.year := 1982;
  TWinHTTP.Post('http://servername/resourcename',t,'Content-Type: application/json');
end;

Note that here you can construct your JSON content using a custom variant storage, which will be converted as JSON text when sent to the server.

like image 20
Arnaud Bouchez Avatar answered Oct 22 '22 11:10

Arnaud Bouchez