Docs/SDKs y herramientas
Clientes HTTP
Snippets oficiales en Node.js, Python y PHP para llamar a la API con reintentos, idempotencia y paginación resueltos.
La API de HUB+ es REST sobre HTTPS con JSON, así que puedes llamarla con cualquier cliente HTTP. Estos snippets oficiales resuelven lo repetitivo en un solo archivo que copias a tu proyecto: encabezados, reintentos con espera creciente, llave de idempotencia, paginación y errores con su Request-Id.
Node.jsNode 18 o superior, sin dependencias.
PythonPython 3.9 o superior, con
requests.
PHPPHP 8.1 o superior, con la extensión curl.
Qué resuelve cada cliente#
| Tema | Comportamiento |
|---|---|
| Autenticación | Envía tu token de acceso (Authorization: Bearer) y X-Tenant-Id en cada petición. |
| Reintentos | Ante errores de red, 429 y 5xx, con espera creciente. Nunca reintenta un 4xx. |
| Idempotencia | Genera una Idempotency-Key por cada POST y la conserva entre reintentos. Puedes pasar la tuya. |
| Paginación | Un iterador por página para las consultas de catálogos y datos, y otro por cursor para los recursos transaccionales. |
| Errores | Una excepción con el código HTTP, el cuerpo y el Request-Id. |
Node.js#
Node.js
// hubplus.js · Node.js 18 o superior, sin dependencias
import { randomUUID } from "node:crypto";
export class HubPlusError extends Error {
constructor(status, body, requestId) {
super(`HUB+ respondió ${status}`);
this.status = status;
this.body = body;
this.requestId = requestId;
}
}
export class HubPlus {
constructor({ accessToken, tenantId, baseUrl, maxRetries = 3 }) {
this.baseUrl = baseUrl.replace(/\/$/, "");
this.headers = { "Authorization": "Bearer " + accessToken, "X-Tenant-Id": tenantId, Accept: "application/json" };
this.maxRetries = maxRetries;
}
async request(method, path, { query, body, idempotencyKey } = {}) {
const url = new URL(this.baseUrl + path);
for (const [k, v] of Object.entries(query || {})) url.searchParams.set(k, v);
const headers = { ...this.headers };
if (body !== undefined) headers["Content-Type"] = "application/json";
if (method === "POST") headers["Idempotency-Key"] = idempotencyKey || randomUUID();
for (let attempt = 0; ; attempt++) {
let res;
try {
res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
} catch (err) {
if (attempt >= this.maxRetries) throw err;
await new Promise((r) => setTimeout(r, 2 ** attempt * 500));
continue;
}
if ((res.status === 429 || res.status >= 500) &&. Attempt < this.maxRetries) {
await new Promise((r) => setTimeout(r, 2 ** attempt * 500));
continue;
}
const text = await res.text();
const data = text ? JSON.parse(text) : null;
if (!res.ok) throw new HubPlusError(res.status, data, res.headers.get("Request-Id"));
return data;
}
}
get(path, query) { return this.request("GET", path, { query }); }
post(path, body, idempotencyKey) { return this.request("POST", path, { body, idempotencyKey }); }
// Consultas de catálogos y datos: paginación por página
async *pages(path, query = {}, limit = 100) {
for (let page = 1; ; page++) {
const { data } = await this.get(path, { ...query, page, limit });
if (!data.items.length) return;
yield* data.items;
}
}
// Recursos transaccionales: paginación por cursor
async *list(path, query = {}, limit = 100) {
let cursor;
for (;;) {
const page = await this.get(path, { ...query, limit, ...(cursor ? { starting_after: cursor } : {}) });
yield* page.data;
if (!page.has_more || !page.data.length) return;
cursor = page.data[page.data.length - 1].id;
}
}
}
// Uso
const hub = new HubPlus({
accessToken: process.env.HUB_ACCESS_TOKEN,
tenantId: process.env.HUB_TENANT_ID,
baseUrl: "https://api.sandbox.hubplus.example",
});
const campus = await hub.get("/v1/catalog/schools");
for await (const pago of hub.pages("/v1/data/payment-history", {
payment_start_date: "2027-02-01", payment_end_date: "2027-02-01",
})) {
procesar(pago);
}Python#
Python
# hubplus.py · Python 3.9 o superior, requiere requests
import os, time, uuid
import requests
class HubPlusError(Exception):
def __init__(self, status, body, request_id):
super().__init__(f"HUB+ respondió {status}")
self.status, self.body, self.request_id = status, body, request_id
class HubPlus:
def __init__(self, access_token, tenant_id, base_url, max_retries=3, timeout=30):
self.base_url = base_url.rstrip("/")
self.max_retries, self.timeout = max_retries, timeout
self.session = requests.Session()
self.session.headers.update({
"Authorization": f"Bearer {access_token}",
"X-Tenant-Id": tenant_id,
"Accept": "application/json",
})
def request(self, method, path, query=None, body=None, idempotency_key=None):
headers = {}
if method == "POST":
headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
for attempt in range(self.max_retries + 1):
try:
res = self.session.request(method, self.base_url + path, params=query,
json=body, headers=headers, timeout=self.timeout)
except requests.RequestException:
if attempt == self.max_retries:
raise
time.sleep(0.5 * 2 ** attempt)
continue
if (res.status_code == 429 or res.status_code >= 500) and attempt < self.max_retries:
time.sleep(0.5 * 2 ** attempt)
continue
data = res.json() if res.content else None
if not res.ok:
raise HubPlusError(res.status_code, data, res.headers.get("Request-Id"))
return data
def get(self, path, **query):
return self.request("GET", path, query=query)
def post(self, path, body=None, idempotency_key=None):
return self.request("POST", path, body=body, idempotency_key=idempotency_key)
def pages(self, path, limit=100, **query):
"""Consultas de catálogos y datos: paginación por página."""
page = 1
while True:
items = self.get(path, page=page, limit=limit, **query)["data"]["items"]
if not items:
return
yield from items
page += 1
def list(self, path, limit=100, **query):
"""Recursos transaccionales: paginación por cursor."""
cursor = None
while True:
params = dict(query, limit=limit, **({"starting_after": cursor} if cursor else {}))
page = self.get(path, **params)
yield from page["data"]
if not page["has_more"] or not page["data"]:
return
cursor = page["data"][-1]["id"]
# Uso
hub = HubPlus(os.environ["HUB_ACCESS_TOKEN"], os.environ["HUB_TENANT_ID"],
"https://api.sandbox.hubplus.example")
campus = hub.get("/v1/catalog/schools")
for pago in hub.pages("/v1/data/payment-history",
payment_start_date="2027-02-01", payment_end_date="2027-02-01"):
procesar(pago)PHP#
PHP
<?php
// HubPlus.php · PHP 8.1 o superior, extensión curl
final class HubPlusError extends RuntimeException
{
public function __construct(public int $status, public ?array $body, public ?string $requestId)
{
parent::__construct("HUB+ respondió $status");
}
}
final class HubPlus
{
public function __construct(
private string $accessToken,
private string $tenantId,
private string $baseUrl,
private int $maxRetries = 3,
) {
$this->baseUrl = rtrim($baseUrl, "/");
}
public function request(string $method, string $path, array $query = [], ?array $body = null, ?string $idempotencyKey = null): ?array
{
$url = $this->baseUrl . $path . ($query ? "?" . http_build_query($query) : "");
$headers = ["Authorization: Bearer {$this->accessToken}", "X-Tenant-Id: {$this->tenantId}", "Accept: application/json"];
if ($body !== null) {
$headers[] = "Content-Type: application/json";
}
if ($method === "POST") {
$headers[] = "Idempotency-Key: " . ($idempotencyKey ?? bin2hex(random_bytes(16)));
}
for ($attempt = 0; ; $attempt++) {
$requestId = null;
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 30,
CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$requestId) {
if (stripos($line, "Request-Id:") === 0) {
$requestId = trim(substr($line, 11));
}
return strlen($line);
},
]);
if ($body !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
}
$raw = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$retryable = $raw === false || $status === 429 || $status >= 500;
if ($retryable && $attempt < $this->maxRetries) {
usleep((int) (500000 * 2 ** $attempt));
continue;
}
$data = $raw ? json_decode($raw, true) : null;
if ($raw === false || $status >= 400) {
throw new HubPlusError($status, $data, $requestId);
}
return $data;
}
}
public function get(string $path, array $query = []): ?array
{
return $this->request("GET", $path, $query);
}
public function post(string $path, array $body = [], ?string $idempotencyKey = null): ?array
{
return $this->request("POST", $path, [], $body, $idempotencyKey);
}
/** Consultas de catálogos y datos: paginación por página. */
public function pages(string $path, array $query = [], int $limit = 100): Generator
{
for ($page = 1; ; $page++) {
$items = $this->get($path, $query + ["page" => $page, "limit" => $limit])["data"]["items"];
if (!$items) {
return;
}
yield from $items;
}
}
}
// Uso
$hub = new HubPlus(getenv("HUB_ACCESS_TOKEN"), getenv("HUB_TENANT_ID"), "https://api.sandbox.hubplus.example");
$campus = $hub->get("/v1/catalog/schools");
foreach ($hub->pages("/v1/data/payment-history", [
"payment_start_date" => "2027-02-01", "payment_end_date" => "2027-02-01",
]) as $pago) {
procesar($pago);
}Otros lenguajes#
Para Java, C#, Go u otro lenguaje, genera un cliente tipado a partir del con el generador que ya use tu equipo. Todos los ejemplos de las guías incluyen además una versión en Java con java.net.http.