Ejemplos con PHP

Snippets compatibles con PHP 8.1+. Usan cURL directo (parte del stdlib) y opcionalmente Guzzle si tu proyecto ya lo tiene.

Con cURL nativo

<?php
declare(strict_types=1);
 
const BASE = 'http://localhost/api/v1';
 
function login(string $usuario, string $password): string {
    $ch = curl_init(BASE . '/auth/login');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_POSTFIELDS => json_encode(['usuario' => $usuario, 'password' => $password]),
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $body = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($body, true);
    if (!empty($json['errors'])) {
        throw new RuntimeException($json['errors'][0]['message']);
    }
    return $json['data']['token'];
}
 
function get(string $path, string $token): array {
    $ch = curl_init(BASE . $path);
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $token],
        CURLOPT_RETURNTRANSFER => true,
    ]);
    $body = curl_exec($ch);
    curl_close($ch);
    $json = json_decode($body, true);
    if (!empty($json['errors'])) {
        throw new RuntimeException($json['errors'][0]['message']);
    }
    return $json['data'];
}
 
$token = login('cb', '1234');
$monedas = get('/Moneda', $token);
foreach ($monedas as $m) {
    echo "{$m['id']} — {$m['nombre']}\n";
}

Con Guzzle

<?php
declare(strict_types=1);
 
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
 
$client = new Client(['base_uri' => 'http://localhost/api/v1/']);
 
$login = $client->post('auth/login', [
    'json' => ['usuario' => 'cb', 'password' => '1234'],
])->getBody()->getContents();
 
$token = json_decode($login, true)['data']['token'];
 
try {
    $compras = $client->get('Compra', [
        'headers' => ['Authorization' => 'Bearer ' . $token],
        'query' => ['per_page' => 10, 'sort' => 'fecha', 'order' => 'desc'],
    ]);
    $body = json_decode($compras->getBody()->getContents(), true);
    foreach ($body['data'] as $c) {
        printf("Compra %d — %s — \$%s\n", $c['id'], $c['proveedor_str'] ?? '?', $c['total'] ?? '0');
    }
} catch (ClientException $e) {
    $body = json_decode($e->getResponse()->getBody()->getContents(), true);
    fwrite(STDERR, "API error [{$body['errors'][0]['code']}]: {$body['errors'][0]['message']}\n");
    exit(1);
}

Business Action — cancelar single

<?php
$response = $client->post('Compra/12345/actions/cancelar_compra', [
    'headers' => ['Authorization' => 'Bearer ' . $token],
    'json' => ['motivo' => 'Duplicado'],
]);
 
$body = json_decode($response->getBody()->getContents(), true);
if (empty($body['errors'])) {
    echo "Compra cancelada\n";
}