@printhive/api
v0.17.0
Published
TypeScript client for the Print Hive REST API: printers, print jobs, and live farm events
Maintainers
Readme
@printhive/api
TypeScript client for the Print Hive REST API and live event stream. List your printers, plan and queue print jobs from a .3mf file, and ask Print Hive to start them. Types come from the OpenAPI schema. ESM, CommonJS, and declarations ship together.
It needs Node 20 or newer, or Bun or Deno with npm compatibility. REST calls use global fetch. The live stream uses socket.io-client, the one runtime dependency.
- Docs: Get Started and the API reference
- OpenAPI spec: https://api.printhiv3d.com/openapi.json
- Sample file to print: cube.3mf, one PETG plate
- For agents:
node_modules/@printhive/api/llms.txt
Keep your API key on a server. Never put it in a browser, a mobile app, or a chat with an agent.
Install
npm install @printhive/apiGet an API key
Sign in at app.printhiv3d.com and open Settings > API Keys.
Create a key with the smallest scope that does the job:
| Scope | Allows | | ----------- | -------------------------------------------------------------------------------------- | |
read| Read printers, jobs, and queue state. | |control| Everything inread, plus create, release, start, and cancel queued print jobs. | |dangerous| Everything incontrol, plus operations on a running print, such asprintJobs.stop. |To watch printers or jobs live, also tick a box under Live events: Printers (
events:read:printer), Print jobs (events:read:job), or All event kinds (events:read).Copy the key. Print Hive shows it once. Put it in
PRINTHIVE_API_KEY:export PRINTHIVE_API_KEY="<your key>"
A new organization has no printers until Hive Link is installed and a printer is connected. Until then, printers.list returns an empty page and job requests fail with no_qualified_target_model.
List your printers
import { PrintHive } from "@printhive/api";
const hive = new PrintHive({ apiKey: process.env.PRINTHIVE_API_KEY! });
const page = await hive.printers.list({ limit: 50 });
for (const printer of page.printers) {
console.log(printer.id, printer.name, printer.state);
}
// Pass page.nextCursor as `cursor` for the next page, until it is null.printers.list and printers.get return PrinterPage and Printer, typed from the OpenAPI schema.
Queue and start a print
create needs a control key, and plan needs read. Use your own sliced or sliceable .3mf, or the sample file above.
const filaments = [{ sourceSlot: 0, material: "PETG", color: "#39FF14" }];
// 1. Optional and read-only: rank the printers that could take the plate.
// It checks materials, not whether a printer is online or ready.
const plan = await hive.printJobs.plan({ filaments });
// The printer the person approves, or undefined to leave it to Smart Queue.
const approvedPrinterId = plan.suggestions[0]?.printer.id;
// 2. Ask the person first. A created job is QUEUED, and its printer's Hive Link
// host can claim and print it as soon as the printer is ready, without
// start. Print Hive answers at once with a request id.
const request = await hive.printJobs.create({
file: "./cube.3mf",
filename: "cube.3mf",
plate: 1,
filaments,
printer_id: approvedPrinterId, // omit it to leave the choice to Smart Queue
idempotencyKey: "order-1042-plate-1", // one per job. Reuse it only to retry
});
// 3. Wait for the job. It throws PrintJobCreateStoppedError when the request
// is held, failed, or cancelled.
const created = await hive.printJobs.waitUntilCreated(request.requestId);
const job = created.job;
if (!job) throw new Error("The job was deleted after it was created");
// 4. Optional: move the job to the front of the approved printer's queue now.
// With Smart Queue routing, ask the person again before you prioritize it.
if (!approvedPrinterId) throw new Error("No printer was approved for this job");
const started = await hive.printJobs.start(job.id, {
expectedPrinterId: approvedPrinterId,
});
console.log(started.dispatch, started.status); // "requested" "QUEUED"A resolved start means Print Hive accepted the request, not that printing began. Print Hive sends no command to the printer. It moves the job to the front of its printer's queue, and the printer's Hive Link host claims it on its next poll. Follow the job with hive.printJobs.get(job.id). Passing expectedPrinterId makes a job that was reassigned fail with job_assignment_changed instead of starting on another printer.
If you are an agent, ask the human before you call create or start. A created job can print as soon as its printer is ready. To hold a job until a person approves it, create it with release: "manual". waitUntilCreated then throws PrintJobCreateStoppedError with the held request; follow "Release or cancel a creation request" in docs/reference.md. Do not start, stop, or heat a printer to test a connection.
Watch printers live
printers.watch() streams each printer's status, progress, temperatures, and filament. The key needs events:read:printer or events:read.
const watch = hive.printers.watch();
for await (const update of watch) {
if (update.type === "connection") {
console.log("stream", update.state); // "connected" or "reconnecting"
continue;
}
if (update.type !== "printer") continue;
const { printerName, stage, progress } = update.printer;
console.log(printerName, stage.phase, `${progress.percent ?? "?"}%`);
}A connection item says connected once Pulse accepts the subscription, and reconnecting while the client retries. Only a printer item confirms that telemetry arrived, so a quiet loop after connected does not prove that no printer is reporting.
You first get each printer's latest stored sample, if it is at most 24 hours old. After that, an online printer typically sends a sample at least every 60 seconds, and a Bambu printer about every 10 seconds while it prints. The client reconnects on its own. For job events that resume after a saved cursor, use hive.events.subscribe. The reference covers both.
Receive job and printer webhooks
A webhook posts an event to your HTTPS server when a job or a printer changes, so you do not poll. Create the endpoint with a key that has webhooks:write: in Settings > API Keys, click Create API Key and select Manage webhooks under Webhooks.
const endpoint = await hive.webhooks.create({
name: "Fulfilment",
url: "https://hooks.example.com/printhive",
event_types: ["job.completed", "job.failed", "printer.offline"],
});
// Store endpoint.signing_secret now. Print Hive returns it once.The types are job.created, job.assigned, job.started, job.paused, job.resumed, job.recovered, job.completed, job.failed, job.cancelled, printer.ready, printer.online, printer.offline, model.created, and model_file.uploaded. Verify each delivery on its raw bytes before you parse it, and answer 2xx only after it verifies:
import { verifyWebhookSignature, type WebhookEvent } from "@printhive/api";
app.post(
"/printhive",
express.raw({ type: "application/json" }),
async (req, res) => {
const verified = await verifyWebhookSignature({
rawBody: req.body, // the Buffer, not parsed JSON
signatureHeader: req.get("x-hive-signature"),
secret: process.env.PRINTHIVE_WEBHOOK_SECRET!,
});
if (!verified) return res.sendStatus(400);
const event: WebhookEvent = JSON.parse(req.body.toString("utf8"));
if (event.type === "printer.offline")
await markOffline(event.data.printerId);
res.sendStatus(204);
}
);Delivery is at least once, so skip an event.id that you have handled. For a Farm Event type, id and data are the id and payload of the item that events.subscribe yields for the same event. A printer's printer.offline also comes from a Host that stops answering, up to about two minutes after it stopped. See "Receive webhooks" in docs/reference.md.
Handle errors
An API failure throws PrintHiveApiError. A network failure, timeout, or abort throws PrintHiveNetworkError.
import { PrintHiveApiError, PrintHiveNetworkError } from "@printhive/api";
if (!approvedPrinterId) throw new Error("No printer was approved for this job");
try {
await hive.printJobs.start(job.id, { expectedPrinterId: approvedPrinterId });
} catch (error) {
if (error instanceof PrintHiveApiError) {
// status 409, code "Conflict", and body.reason "printer_busy", for example
console.error(
error.status,
error.code,
error.body?.reason,
error.requestId
);
} else if (error instanceof PrintHiveNetworkError) {
console.error(error.reason); // "network", "timeout", or "aborted"
} else {
throw error;
}
}statusis the HTTP status, andcodeis the response'serrorfield.bodyholds the full validated error body, andrequestIdis what support asks for.- A 403 whose
body.codeisAPI_KEY_SCOPE_REQUIREDmeans the key lacks the scope (error.codeisForbidden).401means the key is missing, invalid, or expired. startfailures carry a typedbody.reason, such asmodel_file_not_ready,printer_offline, orjob_not_queued. A 404 or 409 means dispatch was refused. After a 500dispatch_failedthe outcome is unknown, so read the job withprintJobs.getbefore you act again. The client never retriesstart.- Reads and idempotent calls retry on 429, 503, and network errors, with backoff and
Retry-After. SetmaxRetries: 0to turn that off. - A failed creation request is not an exception from
create.waitUntilCreatedthrowsPrintJobCreateStoppedError, and itsrequest.errornames the failure, such asno_qualified_target_modelorplate_not_found.
More you can do
The reference covers every method: print job lists and queue pagination, creation-request release and amendment, library sources, slice jobs, the live event stream (hive.events.subscribe), webhook endpoints and signature checks (hive.webhooks, verifyWebhookSignature), material slots and filament assignment, the filament catalog, printer and filament search, stop and cancel, and client options.
Partner integrations that attest an operator cleared a printer should read the operator-ready guide.
For project uploads, see Naming parts in your 3MF to set part and modifier SKUs.
See the changelog for released changes.
These files ship in the package under node_modules/@printhive/api/: docs/reference.md, docs/partner-operator-ready.md, docs/naming-parts-in-a-3mf.md, CHANGELOG.md, and llms.txt. The links above use unpkg so they work on npmjs.com.
For agents
Read node_modules/@printhive/api/llms.txt first. It lists the calls, the scopes, and the rules for starting a print.
