サーバレス練習帳

着眼大局着手小局

【Delphi】DelphiからRESTコール(app0013)

なんだ!簡単じゃないか!

(1) RESTコール
まずは、このサイトを参考に作ってみます。
FireMokeyじゃなくても大丈夫だろうと思いまして、vclにて試してみます。
www.gesource.jp

まずは、3つのコンポーネントを配置します。
TRESTRequest
TRESTResponse
TRESTClient

usesに「REST.Types」が必要です。

(2) jsonパース
jsonパースは、こちらのサイトが分かりやすかったです。
www.gesource.jp
Delphi10seatle用のサイトなので、安心です。
usesに「System.JSON」が必要です。


(3)できた!
さて、今日のコードです。
用意してあったAWSAPI(CludFrontでくるんだもの)を叩くコードです。

15分で、できちゃった。

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, Vcl.StdCtrls, REST.Client,REST.Types,
  Data.Bind.Components, Data.Bind.ObjectScope,System.JSON;

type
  TForm1 = class(TForm)
    RESTClient1: TRESTClient;
    RESTRequest1: TRESTRequest;
    RESTResponse1: TRESTResponse;
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
    procedure RESTRequest1AfterExecute(Sender: TCustomRESTRequest);
  private
    { Private 宣言 }
  public
    { Public 宣言 }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  RESTRequest1.ResetToDefaults;
  RESTClient1.ResetToDefaults;
  RESTResponse1.ResetToDefaults;

  RESTClient1.BaseURL := 'http://xxxxxxxxxxxxxxxx.cloudfront.net/';
  RESTRequest1.Resource := '?title={TITLE}';
  RESTRequest1.Params.AddItem('TITLE', 'イベント',
    TRESTRequestParameterKind.pkURLSEGMENT);
  RESTRequest1.Execute;
end;



procedure TForm1.RESTRequest1AfterExecute(Sender: TCustomRESTRequest);
const
  KEYS: array [0 .. 2] of string = ('dateLabel', 'telop', 'date');
var
  JSONValue: TJSONValue;
  Contents: TJSONArray;
  Content: TJSONValue;
  JSONPair: TJSONPair;
  JSONObject: TJSONObject;
  Key: string;
  S, V: string;
begin
  Memo1.Lines.Clear;;
  JSONValue := RESTResponse1.JSONValue;
  JSONObject := JSONValue as TJSONObject;
  JSONPair := JSONObject.Pairs[0];
  S := JSONPair.JsonString.Value; // => name
  V := JSONPair.JSONValue.Value; // => John Smith
  Memo1.Lines.Add(S+' :' +V);
end;

end.