Setting up the client
Create a client once and configure its key, base URL, timeouts and retries.
Create one client when your application starts and reuse it everywhere. A client holds no connection, so it is cheap. It is safe to share between concurrent requests.
import Swarmhit from '@swarmhit/swarmhit-sdk';
export const swarmhit = new Swarmhit();With no options, the client reads its key from SWARMHIT_API_KEY and sends
requests to https://app.swarmhit.com/api/v1. If it finds no key, the
constructor throws a SwarmhitError.
In CommonJS, use const { Swarmhit } = require('@swarmhit/swarmhit-sdk').
Options
const swarmhit = new Swarmhit({
apiKey: process.env.SWARMHIT_API_KEY,
timeout: 30_000,
maxRetries: 3,
});| Option | Default | What it does |
|---|---|---|
apiKey | SWARMHIT_API_KEY | Your API key (swh_live_…). |
baseURL | SWARMHIT_BASE_URL, then https://app.swarmhit.com/api/v1 | Where requests go. |
workspace | none | With an organization's key, the workspace to act on. See Organizations. |
timeout | 60000 | Milliseconds one attempt may take. A slower attempt is abandoned, then retried. |
maxRetries | 2 | How many times a failed request is retried. See Retries. |
defaultHeaders | none | Headers sent with every request. |
logger | none | Where the SDK writes what it does, for example console. See Logging. |
fetch | the runtime's | A fetch implementation, when you need a specific one: for a proxy, or a test double. |
dangerouslyAllowBrowser | false | Lets the client start in a browser-like runtime. See Browsers and apps. |
Changing options for some calls
withOptions returns a new client with some options changed. The original
client does not change:
const patient = swarmhit.withOptions({ timeout: 120_000, maxRetries: 5 });
await patient.stats.get();To change an option for a single request, pass it as the last argument of the method instead:
await swarmhit.campaigns.list({ limit: 10 }, { timeout: 5_000, maxRetries: 0 });The request options are timeout, maxRetries, signal (an
AbortSignal), idempotencyKey, headers and workspace.
Retries, timeouts and idempotency describes them.
Keeping the key safe
An API key opens everything in its workspace. Keep it in an environment variable or a secret manager, never in your source code. Never send it to a browser: the SDK refuses to start in a web page (see Browsers and apps).
You can create several keys, one per integration. Revoking one on the Access tokens page leaves the others working.
Logging
The SDK writes nothing unless you give it a logger. Anything with debug,
info, warn and error methods that take a message and an optional data
object works, such as console:
const swarmhit = new Swarmhit({ logger: console });It logs:
- each request, at
debug; - each retry, with its reason, at
info; - each endpoint the API marks as deprecated, once, with its sunset date, at
warn.