Getting Started
Install hapic, create a client and send your first request.
HTTP API client for TypeScript
Hooks, transformers and typed errors around every request. Error hooks can recover or retry. One tiny client for Node, browsers and workers.
error hook returned new options, request ran again
Documentation
Install hapic, create a client and send your first request.
Every part of the client explained, from hooks and errors to testing.
Typed clients for Harbor, Loki, OAuth2, Vault and VictoriaLogs.
Hooks and recovery
hapic runs your hooks around the whole request lifecycle. An error hook is special. Return a Response to swallow the failure, or fresh RequestOptions to retry, and the client runs the request again for you. Token refresh, backoff and fallbacks become a handful of lines.
// auth.ts
import { createClient, isClientErrorWithStatusCode } from 'hapic';
const client = createClient({ baseURL: 'https://api.example.com/' });
// Recover from a 401 by refreshing the token, then retry
client.on('responseError', async (error) => {
if (isClientErrorWithStatusCode(error, 401)) {
const token = await refreshAccessToken();
const headers = new Headers(error.request.headers);
headers.set('authorization', `Bearer ${token}`);
// returning RequestOptions runs the original request again
return { ...error.request, headers };
}
// anything else keeps throwing
throw error;
});
Features
A small, predictable core with everything a real HTTP layer needs already wired in.
A thin wrapper over the platform fetch, with a base URL and shortcuts for get, post, put, patch, delete and head.
Shape the outgoing body with transform and the decoded data with responseTransform, per request or for the whole client.
Any 4xx or 5xx response throws a typed error carrying the request, the response and its status. Guards like isClientError work across bundled copies.
Set a timeout per request or per client and combine it with your own abort signal. A timed out request fails with the code ETIMEDOUT.
One code path for Node, the browser and worker runtimes. fetch, Headers, Blob and FormData resolve per environment.
Pass a MemoryTransport to the client. It records every request and answers it with your handler, while hooks and decoding run as usual.
From zero to request
No client builders, no interceptor registries. A function call and a few options.
npm install hapicThe family
Each package extends the same Client with a typed API for one service.
Typed client for the Harbor container registry: projects, repositories, artifacts, robots and webhooks.
OAuth2 and OpenID Connect client: authorization URLs, every token grant, device authorization, introspection and userinfo.
HashiCorp Vault client: key value v1 and v2 secret engines plus mount management.
Grafana Loki client: push log streams and run LogQL instant and range queries.
VictoriaLogs client: ingest logs as JSON lines and query them with LogsQL.