Integrate the QRNG API with direct HTTP and WebSocket examples, source selection, and cryptographic proof verification.
Sign up and create a key in the dashboard. Set QRNG_API_KEY in your server environment before running the example. Examples default to https://qrngapi.com; set QRNG_API_ORIGIN to your own authorized test instance when needed.
These examples explicitly select simulator and Ed25519. Simulator output is cryptographic software output, not physical quantum output. Other requests can differ according to key settings, account access and live source policy.
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/random?bytes=32&format=hex&method=simulator&signatureType=ed25519" \
-H "X-API-Key: $QRNG_API_KEY"
# Python 3, standard library only.
import json
import os
from urllib.request import Request, urlopen
origin = os.environ.get('QRNG_API_ORIGIN', 'https://qrngapi.com').rstrip('/')
url = origin + '/api/random?bytes=8&format=hex&method=simulator&signatureType=ed25519'
request = Request(url, headers={'X-API-Key': os.environ['QRNG_API_KEY']})
with urlopen(request, timeout=10) as response:
print(json.dumps(json.load(response)))
// Node.js 20+; save as random.mjs and run with node.
const origin = process.env.QRNG_API_ORIGIN || 'https://qrngapi.com';
const key = process.env.QRNG_API_KEY;
if (!key) throw new Error('Set QRNG_API_KEY');
const url = new URL('/api/random?bytes=8&format=hex&method=simulator&signatureType=ed25519', origin);
const response = await fetch(url, {
headers: { 'X-API-Key': key }, signal: AbortSignal.timeout(10000)
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const result = await response.json();
console.log(JSON.stringify(result));
Eligible accounts can receive temporary access without a paid subscription change. Check your effective plan in the dashboard. Keep the returned bytes and proof if you need to verify the data later.
The verified integration paths here are cURL, Python 3 standard library and server-side Node.js. They do not require a QRNG SDK.
Python, JavaScript, Go, Java and Rust SDK source projects exist, but registry ownership, installability and runtime compatibility have not been established for the previously advertised releases. Do not assume their models, methods or proof helpers match this API.
Send X-API-Key with the full qnrk_… key for GET or POST /api/random. Keys are shown once at creation. Keep them out of public clients, URLs, logs and repositories; rotate compromised keys by creating a replacement and revoking the old one.
Dashboard account, key-management, usage and billing routes require the signed-in browser session, not an API key. Session mutations require a trusted Origin. WebSocket authentication uses a message after opening the socket, not a query parameter.
Missing or wrong-prefix key: 401 Invalid API key format. Unknown or revoked key: 401 Invalid API key. A 403 indicates a permission or entitlement restriction, not ordinary key invalidity.
Use query parameters for GET or a JSON body for POST. The response contains data, bytes, format, method, source and proof. Method and source describe the delivered result. Additional source and provenance objects are present when the integration feature is enabled.
Use one of these documented formats. An unknown format currently falls back to hex data but echoes the supplied format; do not rely on that behavior.
| Parameter | Accepted input / behavior |
|---|---|
| bytes | Default 32; parsed and clamped to 1–1024. Use a positive integer. |
| format | hex (default), base64 or binary (a string of bits); uint8 or uint32 (JSON number arrays). For uint32, request a multiple of four and do not rely on portable byte order. |
| method | Omitted or auto uses the key’s stored method. An explicit non-auto method overrides it, subject to current availability and effective-plan access. |
| signatureType | ed25519, dilithium2, dilithium3 or dilithium5. Set ed25519 explicitly for the local verification example. |
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/random?bytes=32&format=hex&method=simulator&signatureType=ed25519" \
-H "X-API-Key: $QRNG_API_KEY"
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/random" \
-H "X-API-Key: $QRNG_API_KEY" -H 'Content-Type: application/json' \
--data '{"bytes":8,"format":"base64","method":"simulator","signatureType":"ed25519"}'
{
"data": "00112233",
"bytes": 4,
"format": "hex",
"method": "simulator",
"source": "simulator",
"proof": {
"id": "proof_example",
"hash": "82e7b30e4edfb80dc6f904ad87ff5172aae860808e91f3521be7dbe589704513",
"signature": "<base64 signature>",
"publicKey": "<base64 public key>",
"signatureType": "ed25519",
"signatureInfo": {
"algorithm": "Ed25519",
"securityLevel": "Classical 128-bit security",
"quantumResistant": false,
"signatureSize": 88
}
}
}
This public discovery response includes available, hardware and simulator. Discover live availability separately from method validity and account entitlement. For creating a new key, the signed-in /api/keys/methods response distinguishes supported, available and allowed methods.
Auto and simulator are allowed on all plans, photon on Starter and above, and tunneling and vacuum on Pro and Enterprise. The hardware and crypta selectors also require an enabled integration and Pro or Enterprise access. An accepted selector is not a guarantee of available hardware.
Explicit simulator stays software. After resolving the key default, an explicit unavailable hardware source fails closed (503); only AUTO may fall back if policy permits. An unresolved required-hardware request also fails closed. Read the actual source, not just the requested selector.
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/methods"
Health is public: status, metrics (pass and pValue), entropySource, sources, availableMethods and epoch-millisecond timestamp. Monobit, runs and approximate-entropy checks are sampled software health indicators, not certification, a full NIST validation, or uptime.
Usage requires a browser session. It returns organization (including persisted tier, effective tier, monthly byte quota, usage and Beta metadata) and a current-month breakdown. An X-API-Key alone will not authorize it.
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/health"
Connect over wss://qrngapi.com/ws/stream, send the auth frame, and wait for the authenticated frame with sessionId. Then send one stream frame per result. The route does not implement subscribe, unsubscribe or automatic interval delivery.
A successful entropy frame contains type, data, bytes, format, and proof.id and proof.hash. Source and provenance are feature-dependent. The socket does not return the full signature; read the stored proof by ID and retain the original bytes if verifying locally.
The byte range is 1–256 (default 32); source selection and plan permissions apply as for REST. Read type:error frames and close the socket when finished. Use a server-side client to keep the key private.
{"type":"auth","apiKey":"<your API key>"}
{"type":"stream","bytes":8,"format":"hex","method":"simulator"}
// Node.js 20+ with ws 8 installed; save as stream.mjs.
import WebSocket from 'ws';
const url = new URL('/ws/stream', process.env.QRNG_API_ORIGIN || 'https://qrngapi.com');
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
const key = process.env.QRNG_API_KEY;
if (!key) throw new Error('Set QRNG_API_KEY');
const ws = new WebSocket(url);
const timeout = setTimeout(() => ws.terminate(), 10000);
let received = false;
ws.on('open', () => ws.send(JSON.stringify({ type: 'auth', apiKey: key })));
ws.on('message', (raw) => {
const frame = JSON.parse(raw.toString());
if (frame.type === 'authenticated') {
ws.send(JSON.stringify({ type: 'stream', bytes: 8, format: 'hex', method: 'simulator' }));
} else if (frame.type === 'entropy') {
received = true;
console.log(JSON.stringify(frame));
ws.close();
} else if (frame.type === 'error') {
console.error(frame.error);
ws.close();
}
});
ws.on('error', (error) => console.error(error.message));
ws.on('close', () => {
clearTimeout(timeout);
if (!received) process.exitCode = 1;
});
Set QRNG_PROOF_ID to proof.id from a fresh response. This public lookup checks the persisted signature against the persisted digest. A valid signature can return valid:true with status:unverifiable, hashValid:null and dataAvailable:false because the service does not retain the original bytes.
For independent verification, decode the original entropy bytes, compute SHA3-256, compare to proof.hash (hex), and verify the signature over the 32 decoded digest bytes, not JSON, timestamps or hex characters. Ed25519 signatures are base64 and public keys are base64 DER/SPKI.
Save a hex REST response for the Node.js example and pass it on standard input. Set QRNG_TRUSTED_PUBLIC_KEY from a source you independently trust. A response-supplied key alone only shows internal consistency; the current Ed25519 signer generates its key at process startup, so do not assume a stable pin across restarts or replicas. The signature does not authenticate a timestamp, hardware source, health result or fairness claim.
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/verify/$QRNG_PROOF_ID"
// Node.js 20+; save as verify.mjs. Pass an unmodified hex REST result on stdin.
import { createHash, createPublicKey, verify } from 'node:crypto';
import { readFileSync } from 'node:fs';
const result = JSON.parse(readFileSync(0, 'utf8'));
const { data, bytes, format, proof } = result;
const trustedKey = process.env.QRNG_TRUSTED_PUBLIC_KEY;
if (format !== 'hex' || typeof data !== 'string' ||
!/^(?:[0-9a-f]{2})+$/i.test(data) || data.length !== bytes * 2 ||
proof?.signatureType !== 'ed25519' || !trustedKey ||
proof.publicKey !== trustedKey) throw new Error('Unexpected result or untrusted key');
const digest = createHash('sha3-256').update(Buffer.from(data, 'hex')).digest();
const key = createPublicKey({ key: Buffer.from(trustedKey, 'base64'), format: 'der', type: 'spki' });
if (key.asymmetricKeyType !== 'ed25519' || digest.toString('hex') !== proof.hash ||
!verify(null, digest, key, Buffer.from(proof.signature, 'base64'))) {
throw new Error('Proof verification failed');
}
console.log('Bytes match authenticated digest');
API names dilithium2, dilithium3 and dilithium5 map to ML-DSA-44, ML-DSA-65 and ML-DSA-87 respectively. Pro (developer internally), when PQC is enabled, offers dilithium2; Enterprise (pro internally) with PQC enabled offers all three. Omitting signatureType can default to dilithium2 or dilithium3 respectively. Otherwise the default is Ed25519. WebSocket proofs use Ed25519.
The example requires an Enterprise key with PQC enabled. PQ signatures and raw ML-DSA public keys are base64. Verify the decoded signature over the SHA3-256 digest bytes with the corresponding ML-DSA parameter set. FIPS 204 defines ML-DSA; this is not a claim that this service is certified or that third-party packages were validated.
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/random" \
-H "X-API-Key: $QRNG_API_KEY" -H 'Content-Type: application/json' \
--data '{"bytes":8,"format":"hex","method":"simulator","signatureType":"dilithium3"}'
REST proofs enter server-side Merkle batching. The API does not accept documented per-request chain selection or notarization flags; the generation response does not promise a transaction. Successful proof generation is not evidence of an on-chain confirmation.
Read /api/notarization/stats for configuration and process-local counts, /api/notarization/proof/{proofId} for a Merkle inclusion record when batched, and /api/notarization/batch/{batchId} for batch metadata. The proof or batch route can return 404; the batch anchor can be null. Treat transaction status and confirmations as separate observations.
curl --fail-with-body --silent --show-error "${QRNG_API_ORIGIN:-https://qrngapi.com}/api/notarization/stats"
For cryptography and security, keep keys and random values on the server. Prefer standard local cryptography APIs for sensitive key generation unless your threat model explicitly permits an external source.
For gaming and financial sampling, use rejection sampling for unbiased bounded values, and sample without replacement when uniqueness is needed. A signature attests to a digest, not that a game, allocation or draw was fair.
For AI, science and simulations, preserve exact seed bytes, record the algorithm and fix the application PRNG version when reproducibility matters. Converting arbitrary 64-bit bytes into a JavaScript Number can lose precision.
REST rate limits are per organization, not per key. WebSocket connection and stream-message limits are also per organization. Effective Beta access may change limits without changing the persisted paid plan.
Monthly usage is measured in bytes. A hard monthly limit applies to Free, Starter and eligible promotional access. A hard-quota 429 is distinct from a rate-limit 429; back off for rate limits and use the reset information or Retry-After when supplied.
| Plan (stored tier) | REST requests/min | WS connections | WS messages/min | Monthly allowance (bytes) |
|---|---|---|---|---|
| Free (free) | 10 | 2 | 60 | 10,000 |
| Starter (starter) | 50 | 5 | 300 | 104,857,600 |
| Pro (developer) | 100 | 10 | 600 | 1,073,741,824 |
| Enterprise (pro) | 1000 | 100 | 6000 | 107,374,182,400 |
400: invalid method or signature type. 401: missing, invalid or revoked key for entropy. 403: current effective plan or organization setting does not allow the request. 429: rate window or monthly byte quota. 503: required entropy source unavailable; do not silently substitute a source when your policy requires it.
Do not assume a uniform error envelope or JSON for all rate limits. Inspect the HTTP status and content type before reading an error body. The error below is a fixture for a missing API key.
{"error":"Invalid API key format"}
Share method, format, status and any non-secret diagnostic reference when requesting support. Never share an API key, sensitive generated bytes or an account cookie.