REST Clients and HTTP

42.1 REST Client Library

Design-time: drop TRESTClient/TRESTRequest/TRESTResponse and test them in the IDE. REST Debugger tool. TRESTResponseDataSetAdapter converts JSON arrays into datasets. Authenticators: THTTPBasicAuthenticator, TOAuth1Authenticator, TOAuth2Authenticator.

uses REST.Client, REST.Types, System.JSON;

var Client := TRESTClient.Create('https://jsonplaceholder.typicode.com');
var Request := TRESTRequest.Create(nil);
var Response := TRESTResponse.Create(nil);
try
  Request.Client := Client;
  Request.Response := Response;
  Request.Resource := 'posts/{id}';
  Request.AddParameter('id', '1', TRESTRequestParameterKind.pkURLSEGMENT);
  Request.Method := rmGET;
  Request.Execute;
  if Response.StatusCode = 200 then
    Writeln(Response.JSONValue.GetValue<string>('title'));

  // POST with a JSON body
  Request.Resource := 'posts';
  Request.Method := rmPOST;
  Request.ClearBody;
  Request.AddBody('{"title":"Hello","body":"From Delphi","userId":1}', TRESTContentType.ctAPPLICATION_JSON);
  Request.Execute;
  Writeln(Response.StatusCode, ' ', Response.Content);

  // Async (UI stays responsive)
  Request.ExecuteAsync(procedure begin Memo1.Lines.Text := Response.Content; end);
finally
  Response.Free; Request.Free; Client.Free;
end;

42.2 THTTPClient / TNetHTTPClient (System.Net)

Uses the OS HTTP stack (WinHTTP, NSURLSession, HttpURLConnection, libcurl). TLS is handled by the OS, so no OpenSSL DLLs are needed (unlike Indy).

uses System.Net.HttpClient, System.Net.URLClient, System.Net.HttpClientComponent;

var Http := THTTPClient.Create;
try
  Http.CustomHeaders['Authorization'] := 'Bearer ' + Token;
  Http.ConnectionTimeout := 5000;
  Http.ResponseTimeout := 10000;
  var Resp := Http.Get('https://api.github.com/repos/embarcadero/dev');
  Writeln(Resp.StatusCode, ' ', Resp.ContentAsString(TEncoding.UTF8));
  var Body := TStringStream.Create('{"a":1}', TEncoding.UTF8);
  try
    Resp := Http.Post('https://httpbin.org/post', Body, nil, [TNetHeader.Create('Content-Type', 'application/json')]);
  finally
    Body.Free;
  end;
finally
  Http.Free;
end;