Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
DelphiRAD Studio

あなたのアプリケーションでREST APIを追加するのは簡単ですか?

smartmockups_kpve9reo

この記事は、Heru Susanto氏のブログの抄訳です

結論から先に言うと、DelphiのWindowsデスクトップアプリケーションにREST APIを追加するのは非常に簡単です。このブログをご覧いただければ、その簡単さがよく理解できるでしょう。Expressjsは、Node.jsの向けの高速かつ柔軟な必要最小限のWebフレームワークです。

ExpressJSは、通常のNode.jsだけでは時間のかかるWebアプリケーションの開発を、迅速かつ容易にする機能を備えています。またExpressJSを使用すると、ユーザー向けに高速で堅牢なAPIを非常に簡単に構築して公開することもできます。この強力で使い勝手の良さから、ExpressJSはNode.jsの開発者の間で非常に人気のあるフレームワークです。

ExpressJSに似たDelphiのフレームワークはありますか?

Delphiには、膨大な種類のDelphiコンポーネントやライブラリ、オープンソースを提供しているエコシステムがあり、Delphiの開発者は、その中からアプリケーションへ自由に組み合わせて利用することができます。エコシステムの中には非常に有難いことにExpressJSのコンセプトに触発されて、現在では「Horse」というOpensourceプロジェクト(https://github.com/HashLoad/horse)があります。Horseは、Delphi向けのWebフレームワークです。最小限の方法で迅速な開発のために物事を容易にするように設計されていますが、高いパフォーマンスを達成しています。

ExpressJSとDelphi Horseフレームワークを比較してみましょう

ExpressJS :

app.get('/path_here', function (req, res) {
  res.send('GET request to the homepage')
})

Horse:

begin
  THorse.get('/path_here', procedure(Req: THorseRequest; Res: THorseResponse; Next: TProc) begin
      Res.Send('GET request to the homepage');
  end);
end.

ご覧のように両者を比べると非常に似ていますね? APIルートを作成するときはシンプルに見えます。

Horseを使ってアプリケーションを作成する手順は?

ここでは、APIサーバーアプリケーションを作成する方法を紹介します。これは、expressjsでできることと少し似ています。手順は以下の通りです。

(1) リポジトリのダウンロードまたはクローン作成

git clone https://github.com/HashLoad/horse

(2) Delphi IDEを起動し、新しいアプリケーションコンソールを作成

(3) Projectソースコード(.dpr)を開き、以下のコードを貼り付ける

program horse1;
 
{$APPTYPE CONSOLE}
 
{$R *.res}
 
uses
  Horse,
  System.SysUtils,
  index in 'approutesindex.pas',
  employee in 'approutesemployee.pas';
 
begin
  try
    with THorse.Group.Prefix('/apis') do begin
      Route('/')
        .Get(index.API_Index);
      Route('/employees')
        .Get(employee.Get_Employees);
      Route('/employees/:id')
        .Get(employee.Get_Employee);
    end;
 
    THorse.Listen(8080, procedure(Horse: THorse) begin
        Writeln(Format('Server is runing on %s:%d', [Horse.Host, Horse.Port]));
      end
    );
 
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

(4)app/routesというフォルダを作り、以下のようなファイル構成にする

screen-shot-2021-06-13-at-22-23-26

(5)新しいユニットファイルを作成し、ここではファイル名を「index.pas」に変更

(6)別のユニットを作成し、ここではファイル名を「employee.pas」に変更

Horseフレームワークを使用したDelphiのサンプルプログラム

index.pas

unit index;
 
interface
 
uses
  Horse, System.JSON;
 
procedure API_Index(Req: THorseRequest; Res: THorseResponse; Next: TProc);
 
implementation
 
procedure API_Index(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
  LRespObj: TJSONObject;
begin
  LRespObj:= TJSONObject.Create;
  try
    LRespObj.AddPair(TJSONPair.Create('r', TJSONBool.Create(true)));
    LRespObj.AddPair(TJSONPair.Create('m', TJSONString.Create('this is an API index using https://github.com/HashLoad/horse')));
    Res.Send(LRespObj.ToString);
  finally
    LRespObj.Free;
  end;
end;
 
end.

employee.pas

unit employee;
 
interface
 
uses
  Horse, System.JSON, sysutils;
 
procedure Get_Employees(Req: THorseRequest; Res: THorseResponse; Next: TProc);
procedure Get_Employee(Req: THorseRequest; Res: THorseResponse; Next: TProc);
 
implementation
 
procedure Get_Employees(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
  LRespArr: TJSONArray;
  LRespObj: TJSONObject;
  LEmployee1, LEmployee2, LEmployee3, LEmployee4, LEmployee5: TJSONObject;
begin
  LRespObj:= TJSONObject.Create;
  LRespArr:= TJSONArray.Create;
  LEmployee1:= TJSONObject.Create;
  LEmployee2:= TJSONObject.Create;
  LEmployee3:= TJSONObject.Create;
  LEmployee4:= TJSONObject.Create;
  LEmployee5:= TJSONObject.Create;
  try
    LEmployee1.AddPair(TJSONPair.Create('id', TJSONNumber.Create(1)));
    LEmployee1.AddPair(TJSONPair.Create('name', 'Employee1'));
 
    LEmployee2.AddPair(TJSONPair.Create('id', TJSONNumber.Create(2)));
    LEmployee2.AddPair(TJSONPair.Create('name', 'Employee2'));
 
    LEmployee3.AddPair(TJSONPair.Create('id', TJSONNumber.Create(3)));
    LEmployee3.AddPair(TJSONPair.Create('name', 'Employee3'));
 
    LEmployee4.AddPair(TJSONPair.Create('id', TJSONNumber.Create(4)));
    LEmployee4.AddPair(TJSONPair.Create('name', 'Employee4'));
 
    LEmployee5.AddPair(TJSONPair.Create('id', TJSONNumber.Create(5)));
    LEmployee5.AddPair(TJSONPair.Create('name', 'Employee5'));
    LRespArr.AddElement(LEmployee1);
    LRespArr.AddElement(LEmployee2);
    LRespArr.AddElement(LEmployee3);
    LRespArr.AddElement(LEmployee4);
    LRespArr.AddElement(LEmployee5);
 
    LRespObj.AddPair(TJSONPair.Create('r', TJSONBool.Create(true)));
    LRespObj.AddPair(TJSONPair.Create('m', 'Success'));
    LRespObj.AddPair(TJSONPair.Create('d', LRespArr));
 
    Res.Send(LRespObj.ToString);
  finally
    LRespObj.Free;
  end;
end;
 
procedure Get_Employee(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
  LRespObj: TJSONObject;
  LEmployeeSelected: TJSONObject;
  id: Double;
begin
  id := StrToFloat(Req.Params['id']);
 
  LRespObj := TJSONObject.Create;
  LEmployeeSelected := TJSONObject.Create;
  LEmployeeSelected.AddPair(TJSONPair.Create('name', 'Employee'+Req.Params['id']));
  LEmployeeSelected.AddPair(TJSONPair.Create('id', TJSONNumber.Create(id)));
 
  LRespObj.AddPair(TJSONPair.Create('r', TJSONBool.Create(true)));
  LRespObj.AddPair(TJSONPair.Create('m', 'Success'));
  LRespObj.AddPair(TJSONPair.Create('d', LEmployeeSelected));
  res.Send(LRespObj.ToString);
end;
 
end.

ファイルごとにAPIパスを作成することで、開発者がさらなる開発やコードのトラブルシューティングを容易に行うことができます。手順は以上です。

ここでプログラムを実行し、ブラウザでhttp://localhost:8080/apis/employees/3を表示すると、以下のHTTPレスポンスが返ってきます。

{"r":true,"m":"Success","d":{"name":"Employee3","id":3}}

このように、あなたのDelphiアプリケーションにREST APIを追加することは、非常に簡単です。

是非あなたも試してみませんか?

サンプルのソースコードは、こちらのリンクから入手できます。

Kai for RAD Studio is Now Available! Special Live Webinar: Introducing Kai - A New Chapter for RAD Studio RAD Studio 13.1 Florence Now Available

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.

Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES