Call a REST API from Delphi and Save the JSON to SQL Server (Step by Step)

Sooner or later every business app has to talk to the outside world: download today’s exchange rates, send an invoice to a tax portal, pull orders from an online shop, or check a shipment’s status. Today almost all of those services are REST APIs that speak JSON over HTTPS.

Delphi has everything you need built in: the REST client components to make the call and System.JSON to read the reply (both in every edition, including the free Community Edition), and FireDAC to save the result into SQL Server. FireDAC’s SQL Server driver needs the Enterprise or Architect edition; on Community or Professional, use the ADO (dbGo) components as shown in the FireDAC connection guide and the save step works the same way. This step-by-step guide builds a small, real example: download the latest exchange rates and store them in a SQL Server table, with proper error handling. Then it shows how to send JSON with POST and an access token.

If you haven’t connected Delphi to SQL Server yet, start with How to Connect Delphi to SQL Server with FireDAC.

Delphi app sends a GET or POST to a REST API, reads the JSON reply with System.JSON and saves it to SQL Server with parameterised FireDAC queries

What a REST API call looks like

A REST call is just an HTTP request to a URL:

  • a method: GET to read, POST to create, PUT/PATCH to change, DELETE to remove;
  • a URL, for example https://open.er-api.com/v6/latest/USD;
  • optional headers, such as an access token;
  • for POST and PUT, a body, usually JSON.

The reply has a status code (200 = OK, 401 = not authorised, 404 = not found, 500 = server error) and a body, again usually JSON. Paste that URL into a browser and you’ll see the JSON the example below reads:

{
  "result": "success",
  "base_code": "USD",
  "time_last_update_utc": "Tue, 17 Nov 2026 00:02:31 +0000",
  "rates": {
    "USD": 1,
    "BHD": 0.376,
    "EUR": 0.92,
    "SAR": 3.75
  }
}

(The real reply lists about 160 currencies; the numbers here are illustrative.) This free endpoint needs no key and updates once a day. For production, read the provider’s terms or use your bank’s or central bank’s API.

Step 1: the SQL Server table

CREATE TABLE dbo.ExchangeRates (
    RateDate     DATE          NOT NULL,
    BaseCurrency CHAR(3)       NOT NULL,
    CurrencyCode CHAR(3)       NOT NULL,
    Rate         DECIMAL(18,6) NOT NULL,
    DownloadedAt DATETIME2(0)  NOT NULL CONSTRAINT DF_ExchangeRates_DownloadedAt DEFAULT SYSDATETIME(),
    CONSTRAINT PK_ExchangeRates PRIMARY KEY (RateDate, BaseCurrency, CurrencyCode)
);

The primary key stops the same day’s rates from being saved twice.

Step 2: the components

You can drop components on a form or a data module, or create them in code. In the IDE they’re on the REST Client palette page:

ComponentJob
TRESTClientHolds the base URL (https://open.er-api.com/v6) and connection settings
TRESTRequestOne call: method, resource (latest/{base}), parameters, body
TRESTResponseReceives the status code, headers and body, and parses the JSON

Plus a TFDConnection to SQL Server and a TFDQuery for the insert.

Tip: before writing code, test the call in the REST Debugger (Tools > REST Debugger). Enter the URL, click Send Request, check the JSON, then click Copy Components and paste them onto your form, already configured.

Step 3: download the rates

The code below creates the components in code so you can see every setting. Add these units to your uses clause: REST.Client, REST.Types, System.JSON, Data.DB, Data.FmtBcd, FireDAC.Comp.Client (and System.Threading for the background example at the end).

function TfrmRates.DownloadRates(const BaseCurrency: string): TJSONObject;
var
  Client: TRESTClient;
  Request: TRESTRequest;
  Response: TRESTResponse;
begin
  Client := TRESTClient.Create('https://open.er-api.com/v6');
  Response := TRESTResponse.Create(nil);
  Request := TRESTRequest.Create(nil);
  try
    Client.ConnectTimeout := 10000;   // ms
    Client.ReadTimeout := 20000;

    Request.Client := Client;
    Request.Response := Response;
    Request.Method := TRESTRequestMethod.rmGET;
    Request.Resource := 'latest/{base}';
    Request.AddParameter('base', BaseCurrency, TRESTRequestParameterKind.pkURLSEGMENT);

    Request.Execute;

    if Response.StatusCode <> 200 then
      raise Exception.CreateFmt('Exchange rate API returned %d %s',
        [Response.StatusCode, Response.StatusText]);

    // Response owns its JSONValue, so return a copy the caller can keep and free
    Result := Response.JSONValue.Clone as TJSONObject;
  finally
    Request.Free;
    Response.Free;
    Client.Free;
  end;
end;

A few points:

  • {base} in the resource is filled from the pkURLSEGMENT parameter, so the final URL is .../latest/USD. Parameters are URL-encoded for you.
  • Timeouts matter. Without them, a slow API can freeze your screen for a long time.
  • Execute raises an exception for network problems (no internet, DNS failure, timeout) and, by default, for server errors (5xx), because RaiseExceptionOn500 is True. It does not raise for 4xx errors like 401 or 404. Always check StatusCode yourself.
  • Response.JSONValue belongs to the response and is freed with it. That’s why the function returns a Clone.

Step 4: read the JSON

System.JSON has a class for each JSON type: TJSONObject ({...}), TJSONArray ([...]), TJSONString, TJSONNumber, TJSONBool. GetValue<T> reads a value by name and converts it:

var
  Root, Rates: TJSONObject;
  Pair: TJSONPair;
begin
  Root := DownloadRates('USD');
  try
    if Root.GetValue<string>('result') <> 'success' then
      raise Exception.Create('API did not return success');

    Rates := Root.GetValue<TJSONObject>('rates');
    for Pair in Rates do
      Memo1.Lines.Add(Pair.JsonString.Value + ' = ' +
        FloatToStr((Pair.JsonValue as TJSONNumber).AsDouble));
  finally
    Root.Free;
  end;
end;

for Pair in Rates walks every "code": value pair in the rates object. Pair.JsonString.Value is the name (“BHD”) and Pair.JsonValue is the value.

If a field might be missing, use TryGetValue instead of GetValue, which raises an exception when the name doesn’t exist:

var LastUpdate: string;
if Root.TryGetValue<string>('time_last_update_utc', LastUpdate) then
  lblUpdated.Caption := 'Rates updated: ' + LastUpdate;

Step 5: save to SQL Server

Use a parameterised query, never string concatenation, and wrap the whole save in a transaction so you never end up with half a day’s rates:

procedure TfrmRates.SaveRates(Root: TJSONObject; RateDate: TDate);
var
  Rates: TJSONObject;
  Pair: TJSONPair;
  Base: string;
begin
  Base := Root.GetValue<string>('base_code');
  Rates := Root.GetValue<TJSONObject>('rates');

  FDConnection1.StartTransaction;
  try
    // Replace today's rates if they were already downloaded
    FDConnection1.ExecSQL(
      'DELETE FROM dbo.ExchangeRates WHERE RateDate = :d AND BaseCurrency = :b',
      [RateDate, Base]);

    qryInsert.SQL.Text :=
      'INSERT INTO dbo.ExchangeRates (RateDate, BaseCurrency, CurrencyCode, Rate) ' +
      'VALUES (:RateDate, :Base, :Code, :Rate)';
    qryInsert.ParamByName('RateDate').DataType := ftDate;
    qryInsert.ParamByName('Base').DataType := ftFixedChar;
    qryInsert.ParamByName('Code').DataType := ftFixedChar;
    qryInsert.ParamByName('Rate').DataType := ftFMTBcd;
    qryInsert.Prepare;

    for Pair in Rates do
    begin
      qryInsert.ParamByName('RateDate').AsDate := RateDate;
      qryInsert.ParamByName('Base').AsString := Base;
      qryInsert.ParamByName('Code').AsString := Pair.JsonString.Value;
      qryInsert.ParamByName('Rate').AsFMTBCD :=
        DoubleToBcd((Pair.JsonValue as TJSONNumber).AsDouble);
      qryInsert.ExecSQL;
    end;

    FDConnection1.Commit;
  except
    FDConnection1.Rollback;
    raise;
  end;
end;

Setting the parameter types once and calling Prepare lets SQL Server reuse the same plan for every row. For thousands of rows, FireDAC’s Array DML sends them in one round trip; see FireDAC Performance Settings for SQL Server. Transactions in FireDAC are explained step by step in Delphi Transactions with FireDAC.

If you’d rather update existing rows than delete and re-insert, use a MERGE statement or a stored procedure; see MERGE and Upsert in SQL Server and MySQL.

Step 6: the button

procedure TfrmRates.btnDownloadClick(Sender: TObject);
var
  Root: TJSONObject;
begin
  Screen.Cursor := crHourGlass;
  try
    try
      Root := DownloadRates('USD');
      try
        SaveRates(Root, Date);
      finally
        Root.Free;
      end;
      qryRates.Refresh;   // the grid that shows dbo.ExchangeRates
      ShowMessage('Exchange rates saved.');
    except
      on E: Exception do
        ShowMessage('Could not update exchange rates: ' + E.Message);
    end;
  finally
    Screen.Cursor := crDefault;
  end;
end;

Network calls fail more often than database calls: Wi-Fi drops, the API is down, a firewall blocks it. Catch the error, tell the user in plain words, and log the details. Delphi Exception Handling covers try..except and try..finally in detail.

Sending data: POST with JSON and a token

Most APIs that accept data (tax portals, e-commerce platforms, SMS gateways) want a JSON body and an access token in the Authorization header:

var
  Body: TJSONObject;
begin
  Body := TJSONObject.Create;
  try
    Body.AddPair('invoiceNo', 'INV-2026-0145');
    Body.AddPair('customerVat', '200000000000003');
    Body.AddPair('total', TJSONNumber.Create(105.50));

    Request.Method := TRESTRequestMethod.rmPOST;
    Request.Resource := 'invoices';
    Request.AddParameter('Authorization', 'Bearer ' + FToken,
      TRESTRequestParameterKind.pkHTTPHEADER, [TRESTRequestParameterOption.poDoNotEncode]);
    Request.AddBody(Body.ToJSON, TRESTContentType.ctAPPLICATION_JSON);
    Request.Execute;

    if not (Response.StatusCode in [200, 201]) then
      raise Exception.CreateFmt('Invoice upload failed: %d %s',
        [Response.StatusCode, Response.Content]);
  finally
    Body.Free;
  end;
end;
  • poDoNotEncode stops the token from being URL-encoded.
  • Response.Content holds the raw reply; APIs usually explain what was wrong there.
  • Never hard-code tokens or passwords in the source. Read them from a protected config file or the database, and keep them out of version control.

Keeping the screen responsive

Request.Execute blocks until the reply arrives. For a quick call that’s fine with an hourglass cursor. For slow APIs, run it in the background with ExecuteAsync, or with TTask.Run from System.Threading:

TTask.Run(
  procedure
  var Root: TJSONObject;
  begin
    Root := DownloadRates('USD');          // runs in a background thread
    TThread.Queue(nil,
      procedure
      begin
        try
          SaveRates(Root, Date);           // back on the main thread
          qryRates.Refresh;
        finally
          Root.Free;
        end;
      end);
  end);

Only touch the form, and the form’s FireDAC connection, from the main thread (inside TThread.Queue or Synchronize). A background thread that needs the database should use its own connection. In real code, also catch exceptions inside the task and report them through TThread.Queue.

Common mistakes

  • Not checking StatusCode, and treating an error page as data.
  • Freeing Response.JSONValue (it belongs to the response) or forgetting to free a JSON object you created or cloned.
  • Using GetValue for optional fields, so one missing field crashes the import.
  • No timeouts, so the app hangs when the API is slow.
  • Building SQL by concatenating values from the JSON. Data from outside is untrusted; use parameters.
  • Saving row by row without a transaction, leaving a half-finished import after an error.
  • Tokens in the source code.

Practice exercises

Exercise 1. Change DownloadRates so it returns rates with EUR as the base currency. What exactly changes?

Exercise 2. The API sometimes returns HTTP 429 (“Too Many Requests”). Where would you detect it, and what should the app do?

Exercise 3. Write a SQL query that returns today’s rate for BHD and SAR from dbo.ExchangeRates, base USD.

Answers

Answer 1. Nothing in the function itself: call DownloadRates('EUR'). The {base} URL segment becomes EUR, and base_code in the reply becomes EUR, which SaveRates stores in BaseCurrency.

Answer 2. In the StatusCode check after Execute. Don’t retry in a tight loop: show “rate limit reached, try again later”, or wait (the reply often has a Retry-After header) and try once more. For a daily download, schedule it once a day instead of on every screen open.

Answer 3.

SELECT CurrencyCode, Rate
FROM dbo.ExchangeRates
WHERE RateDate = CAST(GETDATE() AS DATE)
  AND BaseCurrency = 'USD'
  AND CurrencyCode IN ('BHD', 'SAR');

Summary

  • TRESTClient (base URL), TRESTRequest (method, resource, parameters, body) and TRESTResponse (status and JSON) make REST calls in any Delphi edition.
  • Always set timeouts and check StatusCode; Execute raises for network errors and 5xx replies, but not for 4xx replies like 401 or 404.
  • Read JSON with System.JSON: GetValue<T>, TryGetValue<T>, and for Pair in Obj.
  • Save to SQL Server with parameterised FireDAC queries inside a transaction.
  • For POST, add a JSON body with AddBody and the token as an Authorization header with poDoNotEncode.

Related articles

Scroll to Top