DEV Community

CrabPascal
CrabPascal

Posted on

Testing Horse APIs with Postman | Testando APIs Horse com Postman

Bilingual post · Post bilíngue

Jump to: English · Português


English {#english}

Testing Horse APIs with Postman

The IDE story from post 034–035 gets you compiling Pascal. But CrabPascal's killer demos are HTTP servers — Horse routes, JSON bodies, middleware. How do you verify them without writing another Pascal test harness every time?

Answer: usage/postman-guide plus the living example at examples/crud/ in the repo.

Three reference APIs

The Postman guide catalogs three starter projects:

Project Port Endpoints Path
Time Server 9001 3 examples/time-server/
CRUD Produtos 9000 5 examples/crud/
Agenda 9000 2 examples/agenda/

Each runs with crab-pascal run (interpreter) or build-exe for a native binary. Pick one server per port — don't run CRUD and Agenda simultaneously on 9000.

Start the CRUD server

The CRUD walkthrough (blog post 029) shows structure; here's the minimal boot:

program CrudAPI;
uses System.SysUtils, Horse, System.JSON, ProdutoService;
begin
  THorse.Get('/produtos',
    procedure(Req: THorseRequest; Res: THorseResponse; Next: TNextProc)
    begin
      Res.Send<TJSONObject>(TProdutoService.ListarProdutos);
    end);
  THorse.Listen(9000);
end.
Enter fullscreen mode Exit fullscreen mode

Terminal:

cd examples/crud
crab-pascal run crud.dpr
# Server listening on port 9000...
Enter fullscreen mode Exit fullscreen mode

Keep this terminal open. Use Postman or cURL in another window.

Import the collection

Fastest path from postman-guide:

  1. Copy the JSON collection from the doc (full CRUD + time-server requests)
  2. Postman → Import → Raw text → paste → Import
  3. Set environment variable baseUrl = http://localhost:9000

Alternative: import individual cURL snippets — Postman converts them automatically.

Example requests

List products:

curl -s http://localhost:9000/produtos | jq
Enter fullscreen mode Exit fullscreen mode

Create product:

curl -X POST http://localhost:9000/produtos \
  -H "Content-Type: application/json" \
  -d '{"nome":"Widget","preco":19.99}'
Enter fullscreen mode Exit fullscreen mode

Time server (port 9001):

curl http://localhost:9001/horaservidor
Enter fullscreen mode Exit fullscreen mode

Expected JSON includes ISO timestamp and server label — proves SysUtils date helpers and Horse routing both work.

What Postman testing validates

Unlike unit tests that mock HTTP, this flow exercises:

  • Horse Get/Post/Put/Delete registration
  • Anonymous procedure handlers (Delphi closure style)
  • System.JSON serialization
  • Generic collections inside ProdutoService.pas
  • Long-running process stability

When a sprint breaks Horse parity, Postman turns red before users file vague "API broken" issues.

CI and local smoke

Full Postman collections in CI need Newman or a script wrapper. Locally, tests/test_exemplos_completo.ps1 runs broader example smoke (Horse servers noted as environment-dependent in Sprint 1 review).

Pragmatic split:

  • Developer loop: Postman + crab-pascal run
  • CI gate: cargo test + Horse E2E where headless mocks exist (Sprint 16+)

Troubleshooting

Symptom Fix
Connection refused Server not started or wrong port
Empty JSON array Fresh in-memory store — POST first
404 on route Check route string vs collection path
Compiler error on Horse unit Verify crabpascal.toml search paths

Deep reference: usage/postman-guide. Source: examples/crud/ in Bitbucket.

Environment variables and team sharing

Export Postman environments with fixed ports per developer machine:

{
  "name": "CrabPascal Local",
  "values": [
    { "key": "crudBase", "value": "http://localhost:9000" },
    { "key": "timeBase", "value": "http://localhost:9001" }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Share collection + environment JSON in your team wiki — the Mintlify guide includes copy-paste blocks. For automated regression later, Newman (newman run collection.json) can gate releases once Horse headless mocks land in CI; until then, manual Postman remains the honest integration test Delphi developers already know.

Next in series

Post 037 — Nova Arquitetura v2.0.1 Explained covers why we stopped hardcoding every RTL call in Rust and started loading real .pas units from .dproj search paths.


Português {#portugus}

Testando APIs Horse com Postman

A história de IDE dos posts 034–035 leva você a compilar Pascal. Mas os demos matadores do CrabPascal são servidores HTTP — rotas Horse, corpos JSON, middleware. Como verificar sem escrever outro harness de teste em Pascal toda vez?

Resposta: usage/postman-guide mais o exemplo vivo em examples/crud/ no repositório.

Três APIs de referência

O guia Postman cataloga três projetos iniciais:

Projeto Porta Endpoints Caminho
Time Server 9001 3 examples/time-server/
CRUD Produtos 9000 5 examples/crud/
Agenda 9000 2 examples/agenda/

Cada um roda com crab-pascal run (interpretador) ou build-exe para binário nativo. Um servidor por porta — não rode CRUD e Agenda juntos na 9000.

Subir o servidor CRUD

O walkthrough CRUD (post 029) mostra a estrutura; boot mínimo:

program CrudAPI;
uses System.SysUtils, Horse, System.JSON, ProdutoService;
begin
  THorse.Get('/produtos',
    procedure(Req: THorseRequest; Res: THorseResponse; Next: TNextProc)
    begin
      Res.Send<TJSONObject>(TProdutoService.ListarProdutos);
    end);
  THorse.Listen(9000);
end.
Enter fullscreen mode Exit fullscreen mode

Terminal:

cd examples/crud
crab-pascal run crud.dpr
# Server listening on port 9000...
Enter fullscreen mode Exit fullscreen mode

Mantenha este terminal aberto. Use Postman ou cURL em outra janela.

Importar a collection

Caminho mais rápido a partir de postman-guide:

  1. Copie a collection JSON do doc (CRUD + time-server completos)
  2. Postman → Import → Raw text → colar → Import
  3. Variável de ambiente baseUrl = http://localhost:9000

Alternativa: importar cURLs individuais — o Postman converte automaticamente.

Requisições de exemplo

Listar produtos:

curl -s http://localhost:9000/produtos | jq
Enter fullscreen mode Exit fullscreen mode

Criar produto:

curl -X POST http://localhost:9000/produtos \
  -H "Content-Type: application/json" \
  -d '{"nome":"Widget","preco":19.99}'
Enter fullscreen mode Exit fullscreen mode

Time server (porta 9001):

curl http://localhost:9001/horaservidor
Enter fullscreen mode Exit fullscreen mode

JSON esperado inclui timestamp ISO e rótulo do servidor — prova helpers de data SysUtils e roteamento Horse.

O que o teste Postman valida

Diferente de unit tests que mockam HTTP, este fluxo exercita:

  • Registro Horse Get/Post/Put/Delete
  • Handlers em procedures anônimas (estilo closure Delphi)
  • Serialização System.JSON
  • Collections genéricas em ProdutoService.pas
  • Estabilidade de processo longo

Quando um sprint quebra paridade Horse, o Postman fica vermelho antes de issues vagas "API quebrou".

CI e smoke local

Collections Postman completas em CI precisam Newman ou script wrapper. Localmente, tests/test_exemplos_completo.ps1 roda smoke mais amplo (servidores Horse marcados como dependentes de ambiente no review Sprint 1).

Divisão pragmática:

  • Loop do dev: Postman + crab-pascal run
  • Gate CI: cargo test + E2E Horse onde mocks headless existem (Sprint 16+)

Troubleshooting

Sintoma Correção
Connection refused Servidor não iniciado ou porta errada
Array JSON vazio Store in-memory fresh — POST primeiro
404 na rota Conferir string da rota vs path da collection
Erro de compilação na unit Horse Verificar search paths em crabpascal.toml

Referência: usage/postman-guide. Fonte: examples/crud/ no Bitbucket.

Variáveis de ambiente e compartilhamento em time

Exporte environments Postman com portas fixas por máquina:

{
  "name": "CrabPascal Local",
  "values": [
    { "key": "crudBase", "value": "http://localhost:9000" },
    { "key": "timeBase", "value": "http://localhost:9001" }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Compartilhe collection + environment JSON na wiki do time — o guia Mintlify traz blocos copy-paste. Para regressão automatizada depois, Newman (newman run collection.json) pode gatear releases quando mocks Horse headless entrarem no CI; até lá, Postman manual continua sendo o teste de integração honesto que devs Delphi já conhecem.

Próximo da série

Post 037 — Nova arquitetura v2.0.1 explicada cobre por que paramos de hardcodar cada chamada RTL em Rust e passamos a carregar units .pas reais dos search paths do .dproj.


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

Top comments (0)