DEV Community

CrabPascal
CrabPascal

Posted on

Building REST APIs in Pascal with Horse | APIs REST em Pascal com Horse

Bilingual post · Post bilíngue

Jump to: English · Português


English {#english}

Building REST APIs in Pascal with Horse

Pascal is not stuck in desktop forms. With Horse — a lightweight HTTP framework popular in the Delphi ecosystem — CrabPascal v2.22.0 runs real REST servers from .dpr files. No IIS, no Apache: just crab-pascal run and curl.

Why Horse in CrabPascal?

Horse provides routing, JSON bodies, and middleware-style handlers. CrabPascal ships RTL shims and a runtime HTTP stack so examples work out of the box:

Example Port Endpoints
examples/crud/ 9000 Full product CRUD
examples/time-server/ 9001 Time/date ping
examples/agenda/ 9000 Contact registry

All runnable with the internal runtime — no gcc required.

Minimal API

program SimpleAPI;
uses Horse, System.JSON;

begin
  THorse.Get('/ping',
    procedure(Req: THorseRequest; Res: THorseResponse; Next: TNextProc)
    var J: TJSONObject;
    begin
      J := TJSONObject.Create;
      J.AddPair('message', 'pong');
      Res.Send(J.ToJSON);
    end);

  THorse.Listen(9000);
end.
Enter fullscreen mode Exit fullscreen mode

Run and test:

crab-pascal run SimpleAPI.dpr
curl http://localhost:9000/ping
Enter fullscreen mode Exit fullscreen mode

Expected response: {"message":"pong"}.

CRUD example from the repo

The examples/crud/crud.dpr project demonstrates production-style routes:

THorse.Get('/produtos', procedure(Req, Res, Next)
begin
  Res.Send<TJSONObject>(TProdutoService.ListarProdutos);
end);

THorse.Post('/produtos', procedure(Req, Res, Next)
var json: TJSONObject;
begin
  json := Req.Body<TJSONObject>;
  Res.Send(TProdutoService.CriarProduto(
    json.GetValue('nome').Value,
    json.GetValue('categoria').Value,
    StrToFloatDef(json.GetValue('preco').Value, 0),
    StrToIntDef(json.GetValue('estoque').Value, 0)
  ));
end);
Enter fullscreen mode Exit fullscreen mode

Start the server:

cd examples/crud
crab-pascal run crud.dpr
Enter fullscreen mode Exit fullscreen mode

Testing with curl

List products:

curl http://localhost:9000/produtos
Enter fullscreen mode Exit fullscreen mode

Create a product:

curl -X POST http://localhost:9000/produtos \
  -H "Content-Type: application/json" \
  -d '{"nome":"Notebook","categoria":"Eletrônicos","preco":3499.90,"estoque":10}'
Enter fullscreen mode Exit fullscreen mode

Fetch by ID:

curl http://localhost:9000/produtos/1
Enter fullscreen mode Exit fullscreen mode

Postman workflow

  1. Start the server with crab-pascal run crud.dpr
  2. Import curl commands into Postman (Import → Raw text)
  3. Save as a collection for regression tests

The mintlify docs include a full Postman collection JSON for all three example APIs.

Configuration tip

Set the default port in crabpascal.toml:

[runtime]
default_http_port = 9000
Enter fullscreen mode Exit fullscreen mode

Change ports when running multiple servers locally.

Limitations (honest)

Horse support in CrabPascal covers core routing and JSON — not every Delphi middleware plugin. Check sprint release notes for new HTTP features. For learning REST in Pascal or prototyping backends, the included examples are fully functional today.

Pascal + Horse + CrabPascal = backend scripts that feel native to Delphi developers but run from a single Rust-powered binary. Start with examples/crud/, hit the endpoints, then build your own API.


Português {#portugus}

Construindo APIs REST em Pascal com Horse

Pascal não ficou preso em formulários desktop. Com Horse — framework HTTP leve popular no ecossistema Delphi — o CrabPascal v2.22.0 roda servidores REST reais a partir de .dpr. Sem IIS, sem Apache: só crab-pascal run e curl.

Por que Horse no CrabPascal?

Horse oferece rotas, corpos JSON e handlers estilo middleware. O CrabPascal inclui shims RTL e stack HTTP no runtime para exemplos funcionarem de fábrica:

Exemplo Porta Endpoints
examples/crud/ 9000 CRUD completo de produtos
examples/time-server/ 9001 Ping de hora/data
examples/agenda/ 9000 Cadastro de contatos

Tudo executável pelo runtime interno — sem gcc.

API mínima

program SimpleAPI;
uses Horse, System.JSON;

begin
  THorse.Get('/ping',
    procedure(Req: THorseRequest; Res: THorseResponse; Next: TNextProc)
    var J: TJSONObject;
    begin
      J := TJSONObject.Create;
      J.AddPair('message', 'pong');
      Res.Send(J.ToJSON);
    end);

  THorse.Listen(9000);
end.
Enter fullscreen mode Exit fullscreen mode

Execute e teste:

crab-pascal run SimpleAPI.dpr
curl http://localhost:9000/ping
Enter fullscreen mode Exit fullscreen mode

Resposta esperada: {"message":"pong"}.

Exemplo CRUD do repositório

O projeto examples/crud/crud.dpr demonstra rotas estilo produção:

THorse.Get('/produtos', procedure(Req, Res, Next)
begin
  Res.Send<TJSONObject>(TProdutoService.ListarProdutos);
end);

THorse.Post('/produtos', procedure(Req, Res, Next)
var json: TJSONObject;
begin
  json := Req.Body<TJSONObject>;
  Res.Send(TProdutoService.CriarProduto(
    json.GetValue('nome').Value,
    json.GetValue('categoria').Value,
    StrToFloatDef(json.GetValue('preco').Value, 0),
    StrToIntDef(json.GetValue('estoque').Value, 0)
  ));
end);
Enter fullscreen mode Exit fullscreen mode

Suba o servidor:

cd examples/crud
crab-pascal run crud.dpr
Enter fullscreen mode Exit fullscreen mode

Testando com curl

Listar produtos:

curl http://localhost:9000/produtos
Enter fullscreen mode Exit fullscreen mode

Criar produto:

curl -X POST http://localhost:9000/produtos \
  -H "Content-Type: application/json" \
  -d '{"nome":"Notebook","categoria":"Eletrônicos","preco":3499.90,"estoque":10}'
Enter fullscreen mode Exit fullscreen mode

Buscar por ID:

curl http://localhost:9000/produtos/1
Enter fullscreen mode Exit fullscreen mode

Fluxo no Postman

  1. Inicie o servidor com crab-pascal run crud.dpr
  2. Importe comandos curl no Postman (Import → Raw text)
  3. Salve como collection para testes de regressão

A documentação mintlify inclui JSON de collection Postman completo para as três APIs de exemplo.

Dica de configuração

Defina a porta padrão em crabpascal.toml:

[runtime]
default_http_port = 9000
Enter fullscreen mode Exit fullscreen mode

Altere portas ao rodar vários servidores localmente.

Limitações (honestas)

O suporte Horse no CrabPascal cobre rotas core e JSON — nem todo plugin middleware Delphi. Consulte release notes de sprint para novos recursos HTTP. Para aprender REST em Pascal ou prototipar backends, os exemplos incluídos funcionam hoje.

Pascal + Horse + CrabPascal = scripts backend nativos para devs Delphi, rodando de um único binário powered by Rust. Comece com examples/crud/, teste os endpoints e construa sua API.


Published on dev.to/@crabpascal · Código em CrabPascal

Top comments (0)