Sample code for 30+ languages & platforms
Pascal (Lazarus/Delphi)

Finnhub API - Get Stock Quote

See more AI Examples

Demonstrates how to get a stock quote from the Finnhub API.

Chilkat Pascal (Lazarus/Delphi) Downloads

Pascal (Lazarus/Delphi)
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.Http,
  Chilkat.HttpRequest,
  Chilkat.HttpResponse,
  Chilkat.JsonObject;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  success: Boolean;
  apiKey: string;
  symbol: string;
  http: THttp;
  urlWithoutParams: string;
  req: THttpRequest;
  resp: THttpResponse;
  json: TJsonObject;
  statusCode: Integer;

begin
  success := False;

  //  Replace with your actual Finnhub API key.
  apiKey := 'YOUR_FINNHUB_API_KEY';
  symbol := 'AAPL';

  http := THttp.Create;

  //  This is the URL without params.
  urlWithoutParams := 'https://finnhub.io/api/v1/quote';

  req := THttpRequest.Create;

  //  Add params that will be sent in the URL.
  req.AddParam('symbol',symbol);
  req.AddParam('token',apiKey);

  req.HttpVerb := 'GET';

  //  Send the request to get the JSON response.
  resp := THttpResponse.Create;
  success := http.HttpReq(urlWithoutParams,req,resp);
  if (success = False) then
    begin
      WriteLn(http.LastErrorText);
      Exit;
    end;

  json := TJsonObject.Create;
  resp.GetBodyJson(json);

  statusCode := resp.StatusCode;
  WriteLn('response status code: ' + statusCode);

  json.EmitCompact := False;
  WriteLn(json.Emit());

  //  Sample result:

  //  {
  //    "c": 248.8,
  //    "d": -4.09,
  //    "dp": -1.6173,
  //    "h": 255.493,
  //    "l": 248.07,
  //    "o": 253.9,
  //    "pc": 252.89,
  //    "t": 1774641600
  //  }

  if (statusCode = 200) then
    begin
      //  Add the symbol to the top of the result.
      json.AddStringAt(0,'symbol',symbol);

      //  Rename members for clarification.
      json.Rename('c','currentPrice');
      json.Rename('d','change');
      json.Rename('dp','percentChange');
      json.Rename('h','high');
      json.Rename('l','low');
      json.Rename('o','open');
      json.Rename('pc','prevClose');
      json.Rename('t','unixTime');

      WriteLn(json.Emit());

    end
  else
    begin
      WriteLn('Failed');
    end;


  http.Free;
  req.Free;
  resp.Free;
  json.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.