Code examples
A small mlab.sh API client in Python and TypeScript: authentication, an IP lookup, a domain scan polled until it ends, a file upload, and error and 429 handling.
Two small clients, one in Python (requests) and one in TypeScript (fetch, Node 18 or later), that do the same things:
- check the API key with
GET /api/v1/ - look up an IP address
- launch a domain scan, poll it until it ends, and read the full report
- upload a file and poll its results
- turn errors into exceptions, retry what is worth retrying, and stop on a spent quota
They follow the rules of Errors. Copy them as a starting point; neither is a published SDK.
How a domain scan is followed
/scan/domain/status answers pending, then scanning (with done and total parts), then success once the scan has ended. success means ended, not succeeded: read the outcome from the status of /scan/domain/report, which is completed, partial or failed. Polling spends no quota. If your organization has a webhook, scan.domain.completed, scan.domain.partial or scan.domain.failed tells you the same thing without polling.
A file scan is followed the same way on GET /api/v1/scan/file/results?sha256=..., until its status is completed, partial or failed.
Python
Requires pip install requests. Set MLAB_API_KEY in the environment.
"""Minimal mlab.sh API client: lookups, domain scan, file upload."""
import os
import random
import time
import requests
BASE = "https://mlab.sh"
class MlabError(Exception):
def __init__(self, status: int, message: str):
super().__init__(f"HTTP {status}: {message}")
self.status = status
self.message = message
class QuotaExceeded(MlabError):
"""A scan quota is spent (429). Retrying right away will not help."""
def __init__(self, status: int, message: str, retry_after: int | None, resource: str | None):
super().__init__(status, message)
self.retry_after = retry_after
self.resource = resource
def _message(resp: requests.Response) -> str:
try:
body = resp.json()
except ValueError:
return resp.text[:200]
err = body.get("error", body.get("message", ""))
if isinstance(err, dict): # /upload/file: {"success": false, "error": {"code", "message"}}
return str(err.get("message", err))
return str(err)
class Mlab:
def __init__(self, api_key: str, timeout: float = 30.0):
self.http = requests.Session()
self.http.headers["Authorization"] = f"Bearer {api_key}"
self.timeout = timeout
def _request(self, method: str, path: str, *, retry: bool, **kwargs) -> dict:
"""One call. `retry` is True only for calls that are safe to repeat."""
attempts = 5 if retry else 1
for attempt in range(attempts):
try:
resp = self.http.request(method, BASE + path, timeout=self.timeout, **kwargs)
except requests.ConnectionError:
if attempt == attempts - 1:
raise
time.sleep(2 ** (attempt + 1) + random.random())
continue
if resp.ok:
remaining = resp.headers.get("X-RateLimit-Remaining")
if remaining is not None and int(remaining) <= 2:
print(f"warning: {remaining} {resp.headers.get('X-RateLimit-Resource')} scans left")
return resp.json()
if resp.status_code == 429:
retry_after = resp.headers.get("Retry-After")
raise QuotaExceeded(429, _message(resp),
int(retry_after) if retry_after else None,
resp.headers.get("X-RateLimit-Resource"))
# 502 (upstream down) and other 5xx are transient: back off and retry.
if resp.status_code >= 500 and attempt < attempts - 1:
time.sleep(2 ** (attempt + 1) + random.random())
continue
# 400, 401, 403, 404, 413: the same request fails the same way.
raise MlabError(resp.status_code, _message(resp))
raise AssertionError("unreachable")
# ---- auth --------------------------------------------------------------
def whoami(self) -> dict:
"""Validates the key: {"auth", "message", "organization", "plan"}."""
return self._request("GET", "/api/v1/", retry=True)
# ---- lookups -----------------------------------------------------------
def ip(self, ip: str) -> dict:
return self._request("GET", "/api/v1/scan/ip", params={"ip": ip}, retry=True)
def limit(self, scan_type: str) -> dict:
"""{"scan_type", "remaining", "total"} for domain, ip, file or crypto."""
return self._request("GET", f"/api/v1/limit/{scan_type}", retry=True)
# ---- domain scan -------------------------------------------------------
def scan_domain(self, domain: str, poll_every: float = 10, give_up_after: float = 1800) -> dict:
# Not retried: a repeated POST starts the scan again and spends another one.
self._request("POST", "/api/v1/scan/domain", json={"domain": domain}, retry=False)
deadline = time.monotonic() + give_up_after
while True:
status = self._request("GET", "/api/v1/scan/domain/status",
params={"domain": domain}, retry=True)
if status["status"] not in ("pending", "scanning"):
break
if time.monotonic() > deadline:
raise TimeoutError(f"{domain}: still {status['status']} after {give_up_after}s")
time.sleep(poll_every)
# The report says how it ended: completed, partial or failed.
return self._request("GET", "/api/v1/scan/domain/report",
params={"domain": domain}, retry=True)
# ---- file scan ---------------------------------------------------------
def scan_file(self, path: str, poll_every: float = 5, give_up_after: float = 900) -> dict:
with open(path, "rb") as fh:
# /upload/file lives at the site root, not under /api/v1.
uploaded = self._request("POST", "/upload/file",
files={"file": (os.path.basename(path), fh)}, retry=False)
sha256 = uploaded["sha256"]
deadline = time.monotonic() + give_up_after
while True:
result = self._request("GET", "/api/v1/scan/file/results",
params={"sha256": sha256}, retry=True)
if result["status"] in ("completed", "partial", "failed"):
return result
if time.monotonic() > deadline:
raise TimeoutError(f"{sha256}: still {result['status']} after {give_up_after}s")
time.sleep(poll_every)
if __name__ == "__main__":
mlab = Mlab(os.environ["MLAB_API_KEY"])
print(mlab.whoami())
try:
print(mlab.ip("185.220.101.47"))
report = mlab.scan_domain("example.com")
print(report["status"], report.get("score"), len(report.get("findings", [])), "findings")
result = mlab.scan_file("suspicious.exe")
print(result["status"], result.get("error"))
except QuotaExceeded as e:
print(f"{e.resource or 'scan'} quota spent: {e.message}. Retry-After {e.retry_after}s")
print("left:", mlab.limit(e.resource) if e.resource else "see /api/v1/limit/*")
except MlabError as e:
print(f"refused ({e.status}): {e.message}")TypeScript
Runs on Node 18 or later (global fetch, FormData and Blob), or in Deno and Bun. Set MLAB_API_KEY in the environment.
// Minimal mlab.sh API client: lookups, domain scan, file upload.
import { readFile } from "node:fs/promises";
import { basename } from "node:path";
const BASE = "https://mlab.sh";
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export class MlabError extends Error {
constructor(public status: number, message: string) {
super(`HTTP ${status}: ${message}`);
}
}
/** A scan quota is spent (429). Retrying right away will not help. */
export class QuotaExceeded extends MlabError {
constructor(message: string, public retryAfter: number | null, public resource: string | null) {
super(429, message);
}
}
async function messageOf(res: Response): Promise<string> {
const text = await res.text();
try {
const body = JSON.parse(text);
const err = body.error ?? body.message ?? "";
// /upload/file: {"success": false, "error": {"code", "message"}}
return typeof err === "object" ? String(err.message ?? JSON.stringify(err)) : String(err);
} catch {
return text.slice(0, 200);
}
}
export class Mlab {
constructor(private apiKey: string) {}
/** One call. `retry` is true only for calls that are safe to repeat. */
private async request<T>(method: string, path: string, init: { query?: Record<string, string>; json?: unknown; form?: FormData; retry: boolean }): Promise<T> {
const url = new URL(path, BASE);
for (const [k, v] of Object.entries(init.query ?? {})) url.searchParams.set(k, v);
const headers: Record<string, string> = { Authorization: `Bearer ${this.apiKey}` };
let body: BodyInit | undefined;
if (init.json !== undefined) {
headers["Content-Type"] = "application/json";
body = JSON.stringify(init.json);
} else if (init.form) {
body = init.form; // fetch sets the multipart boundary itself
}
const attempts = init.retry ? 5 : 1;
for (let attempt = 0; attempt < attempts; attempt++) {
let res: Response;
try {
res = await fetch(url, { method, headers, body, signal: AbortSignal.timeout(30_000) });
} catch (e) {
if (attempt === attempts - 1) throw e;
await sleep(2 ** (attempt + 1) * 1000 + Math.random() * 1000);
continue;
}
if (res.ok) {
const remaining = res.headers.get("X-RateLimit-Remaining");
if (remaining !== null && Number(remaining) <= 2) {
console.warn(`${remaining} ${res.headers.get("X-RateLimit-Resource")} scans left`);
}
return (await res.json()) as T;
}
if (res.status === 429) {
const ra = res.headers.get("Retry-After");
throw new QuotaExceeded(await messageOf(res), ra ? Number(ra) : null, res.headers.get("X-RateLimit-Resource"));
}
// 502 (upstream down) and other 5xx are transient: back off and retry.
if (res.status >= 500 && attempt < attempts - 1) {
await sleep(2 ** (attempt + 1) * 1000 + Math.random() * 1000);
continue;
}
// 400, 401, 403, 404, 413: the same request fails the same way.
throw new MlabError(res.status, await messageOf(res));
}
throw new Error("unreachable");
}
/** Validates the key: { auth, message, organization, plan }. */
whoami() {
return this.request<{ auth: string; message: string; organization: string; plan: string }>("GET", "/api/v1/", { retry: true });
}
ip(ip: string) {
return this.request<Record<string, unknown>>("GET", "/api/v1/scan/ip", { query: { ip }, retry: true });
}
/** { scan_type, remaining, total } for domain, ip, file or crypto. */
limit(scanType: "domain" | "ip" | "file" | "crypto") {
return this.request<{ scan_type: string; remaining: number; total: number }>("GET", `/api/v1/limit/${scanType}`, { retry: true });
}
async scanDomain(domain: string, pollEveryMs = 10_000, giveUpAfterMs = 30 * 60_000) {
// Not retried: a repeated POST starts the scan again and spends another one.
await this.request("POST", "/api/v1/scan/domain", { json: { domain }, retry: false });
const deadline = Date.now() + giveUpAfterMs;
for (;;) {
const s = await this.request<{ status: string }>("GET", "/api/v1/scan/domain/status", { query: { domain }, retry: true });
if (s.status !== "pending" && s.status !== "scanning") break;
if (Date.now() > deadline) throw new Error(`${domain}: still ${s.status}`);
await sleep(pollEveryMs);
}
// The report says how it ended: completed, partial or failed.
return this.request<{ status: string; score: unknown; findings?: unknown[] }>("GET", "/api/v1/scan/domain/report", { query: { domain }, retry: true });
}
async scanFile(path: string, pollEveryMs = 5_000, giveUpAfterMs = 15 * 60_000) {
const form = new FormData();
form.append("file", new Blob([await readFile(path)]), basename(path));
// /upload/file lives at the site root, not under /api/v1.
const { sha256 } = await this.request<{ sha256: string }>("POST", "/upload/file", { form, retry: false });
const deadline = Date.now() + giveUpAfterMs;
for (;;) {
const r = await this.request<{ status: string; error?: unknown }>("GET", "/api/v1/scan/file/results", { query: { sha256 }, retry: true });
if (["completed", "partial", "failed"].includes(r.status)) return r;
if (Date.now() > deadline) throw new Error(`${sha256}: still ${r.status}`);
await sleep(pollEveryMs);
}
}
}
// Example run
const mlab = new Mlab(process.env.MLAB_API_KEY!);
console.log(await mlab.whoami());
try {
console.log(await mlab.ip("185.220.101.47"));
const report = await mlab.scanDomain("example.com");
console.log(report.status, report.score, report.findings?.length ?? 0, "findings");
const file = await mlab.scanFile("suspicious.exe");
console.log(file.status, file.error ?? "");
} catch (e) {
if (e instanceof QuotaExceeded) {
console.error(`${e.resource ?? "scan"} quota spent: ${e.message}. Retry-After ${e.retryAfter}s`);
} else if (e instanceof MlabError) {
console.error(`refused (${e.status}): ${e.message}`);
} else {
throw e;
}
}Notes
- Permissions. These calls need a key with
scan.lookup(IP lookup),scan.domain(domain scan) andscan.file(upload and results). A missing one answers403naming it. See Permissions. - Quota on a 429.
Retry-Afteris a fixed one-hour hint; the quota window is a rolling 24 hours. A long-running job should stop the spent scan type and resume whenGET /api/v1/limit/{type}showsremainingabove 0, rather than sleep and retry. - Two quotas answer 400. Crypto lookups and RedKit credits answer
400when spent, so these clients raiseMlabErrorfor them, notQuotaExceeded. Match on the message if you call those endpoints. - The header must be sent. A request without
Authorizationis served as anonymous with tiny per-IP quotas, not refused. The clients set the header on every call. - Upload size. The file must stay under the upload limit, or
/upload/fileanswers413.
Webhooks
Receive mlab.sh events on your own endpoint: the event catalog with example payloads, the signed envelope and its headers, HMAC-SHA256 verification in Python and Node, retries and testing.
Versioning and status
How the mlab.sh API is versioned, what can change under an integration, where changes are announced, and what exists for service status.