Developer event gateway
The gateway sends your program a message each time a new opportunity is added to Apprentice Wizard. You open one WebSocket connection, prove who you are with a token, and keep listening. This page gets you to your first event.
Version 1 of the protocol is served at wss://gateway.apprenticewizard.co.uk/v1. Browser clients are not supported, so run the examples from Node.js or Python.
Get your first event
- Create a token on the developer tokens page. You need to be signed in with a verified email address and to have accepted the developer terms. The token is shown once, so copy it straight away. See tokens.
- Save it in an environment variable called
AW_GATEWAY_TOKEN. Do not put it in code or in a URL. - Run one of the listeners below. Each is a complete program that connects, identifies, sends heartbeats, prints the type of every event it receives and resumes after a dropped connection.
- Wait for an opportunity to be added. The listener prints it.
A healthy start prints HELLO received, then Event: READY, then READY: listening for new opportunities, then a heartbeat acknowledgement every 45 seconds. A new session starts at the current position, so you only see opportunities added after you connect. Nothing from before is replayed.
Node.js
Needs Node.js 22 or later, which has WebSocket built in. Run it with AW_GATEWAY_TOKEN=... node listener.mjs.
// Minimal listener for the Apprentice Wizard developer event gateway.// Needs Node.js 22 or later (global WebSocket). Run: AW_GATEWAY_TOKEN=... node listener.mjsconst GATEWAY_URL = "wss://gateway.apprenticewizard.co.uk/v1";const token = process.env.AW_GATEWAY_TOKEN;if (!token) { console.error("Set AW_GATEWAY_TOKEN to your gateway token."); process.exit(1);}// Opcodes (see the opcodes page).const OP = { DISPATCH: 0, HEARTBEAT: 1, IDENTIFY: 2, RESUME: 6, RECONNECT: 7, INVALID_SESSION: 9, HELLO: 10, HEARTBEAT_ACK: 11 };// Close codes after which reconnecting cannot help: 4004, 4012 and 4013.const FATAL_CLOSE_CODES = new Set([4004, 4012, 4013]);// 4010 means the token already has 2 connections open. A connection that dropped without closing// cleanly keeps counting until the server times it out after 2 missed heartbeats (90 s), so wait// that long before trying again.const TOO_MANY_CONNECTIONS_CLOSE_CODE = 4010;const TOO_MANY_CONNECTIONS_WAIT_MS = 90_000;// 4007 means the sequence number was invalid: forget the session and identify afresh.const IDENTIFY_AFRESH_CLOSE_CODE = 4007;let sessionId = null; // from READY. Treat it like a token: do not log it.let lastSeq = null; // sequence number of the last event processedlet attempts = 0;const seen = new Set(); // d.id values already handledconst SEEN_LIMIT = 10_000;function handleOpportunity(opportunity) { console.log(`New opportunity: ${opportunity.title} at ${opportunity.employer} (${opportunity.url})`);}function connect() { const ws = new WebSocket(GATEWAY_URL); let heartbeatTimer = null; let heartbeatInterval = 45_000; const send = (op, d) => ws.readyState === WebSocket.OPEN && ws.send(JSON.stringify({ op, d })); const heartbeat = () => send(OP.HEARTBEAT, { last_seq: lastSeq }); const identify = () => send(OP.IDENTIFY, { token }); const startHeartbeats = () => { clearInterval(heartbeatTimer); heartbeatTimer = setInterval(heartbeat, heartbeatInterval); }; ws.addEventListener("message", (message) => { const { op, d, s, t } = JSON.parse(message.data); switch (op) { case OP.HELLO: console.log("HELLO received"); heartbeatInterval = d.heartbeat_interval; // Resume when there is a session to continue, otherwise identify. if (sessionId !== null && lastSeq !== null) send(OP.RESUME, { session_id: sessionId, seq: lastSeq }); else identify(); break; case OP.HEARTBEAT: // the server asks for a heartbeat: answer at once heartbeat(); break; case OP.HEARTBEAT_ACK: console.log("Heartbeat acknowledged"); break; case OP.RECONNECT: ws.close(); break; case OP.INVALID_SESSION: // cannot resume: start a new session sessionId = null; lastSeq = null; identify(); break; case OP.DISPATCH: console.log(`Event: ${t}`); if (t === "READY") { sessionId = d.session_id; lastSeq = d.head_seq; attempts = 0; console.log("READY: listening for new opportunities"); startHeartbeats(); } else if (t === "RESUMED") { attempts = 0; console.log("RESUMED: missed events replayed"); startHeartbeats(); } else if (t === "OPPORTUNITY_CREATE") { lastSeq = s; if (seen.has(d.id)) break; // delivery is at least once: skip repeats seen.add(d.id); if (seen.size > SEEN_LIMIT) seen.delete(seen.values().next().value); handleOpportunity(d.opportunity); } break; } }); ws.addEventListener("close", (event) => { clearInterval(heartbeatTimer); console.log(`Closed with code ${event.code}`); if (FATAL_CLOSE_CODES.has(event.code)) { console.error("The gateway told us not to reconnect. Check the token and the close codes page."); process.exit(1); } if (event.code === IDENTIFY_AFRESH_CLOSE_CODE) { sessionId = null; lastSeq = null; } // Back off between attempts: 1 s, 2 s, 4 s ... up to 30 s. let delay = Math.min(30_000, 1_000 * 2 ** attempts); if (event.code === TOO_MANY_CONNECTIONS_CLOSE_CODE) delay = Math.max(delay, TOO_MANY_CONNECTIONS_WAIT_MS); attempts += 1; setTimeout(connect, delay); }); ws.addEventListener("error", () => {}); // a close event always follows}connect();Python
Needs Python 3.9 or later and version 12 or later of the websockets package: pip install "websockets>=12". Run it with AW_GATEWAY_TOKEN=... python listener.py.
"""Minimal listener for the Apprentice Wizard developer event gateway.Needs Python 3.9 or later and websockets 12 or later (pip install "websockets>=12").Run: AW_GATEWAY_TOKEN=... python listener.py"""import asyncioimport jsonimport osimport sysfrom collections import OrderedDictimport websocketsGATEWAY_URL = "wss://gateway.apprenticewizard.co.uk/v1"# Opcodes (see the opcodes page).DISPATCH, HEARTBEAT, IDENTIFY, RESUME, RECONNECT, INVALID_SESSION, HELLO, HEARTBEAT_ACK = 0, 1, 2, 6, 7, 9, 10, 11# Close codes after which reconnecting cannot help: 4004, 4012 and 4013.FATAL_CLOSE_CODES = {4004, 4012, 4013}# 4010 means the token already has 2 connections open. A connection that dropped without closing# cleanly keeps counting until the server times it out after 2 missed heartbeats (90 s), so wait# that long before trying again.TOO_MANY_CONNECTIONS_CLOSE_CODE = 4010TOO_MANY_CONNECTIONS_WAIT = 90# 4007 means the sequence number was invalid: forget the session and identify afresh.IDENTIFY_AFRESH_CLOSE_CODE = 4007SEEN_LIMIT = 10_000token = os.environ.get("AW_GATEWAY_TOKEN")if not token: sys.exit("Set AW_GATEWAY_TOKEN to your gateway token.")class State: session_id = None # from READY. Treat it like a token: do not log it. last_seq = None # sequence number of the last event processed attempts = 0 seen = OrderedDict() # d.id values already handleddef handle_opportunity(opportunity): print(f"New opportunity: {opportunity['title']} at {opportunity['employer']} ({opportunity['url']})")async def send(ws, op, d): await ws.send(json.dumps({"op": op, "d": d}))async def heartbeats(ws, interval): while True: await asyncio.sleep(interval) await send(ws, HEARTBEAT, {"last_seq": State.last_seq})async def listen(ws): interval = 45.0 heartbeat_task = None try: async for raw in ws: message = json.loads(raw) op, d = message["op"], message.get("d") if op == HELLO: print("HELLO received") interval = d["heartbeat_interval"] / 1000 # Resume when there is a session to continue, otherwise identify. if State.session_id is not None and State.last_seq is not None: await send(ws, RESUME, {"session_id": State.session_id, "seq": State.last_seq}) else: await send(ws, IDENTIFY, {"token": token}) elif op == HEARTBEAT: # the server asks for a heartbeat: answer at once await send(ws, HEARTBEAT, {"last_seq": State.last_seq}) elif op == HEARTBEAT_ACK: print("Heartbeat acknowledged") elif op == RECONNECT: await ws.close() elif op == INVALID_SESSION: # cannot resume: start a new session State.session_id = None State.last_seq = None await send(ws, IDENTIFY, {"token": token}) elif op == DISPATCH: event = message.get("t") print(f"Event: {event}") if event in ("READY", "RESUMED"): if event == "READY": State.session_id = d["session_id"] State.last_seq = d["head_seq"] print("READY: listening for new opportunities") else: print("RESUMED: missed events replayed") State.attempts = 0 if heartbeat_task: heartbeat_task.cancel() heartbeat_task = asyncio.create_task(heartbeats(ws, interval)) elif event == "OPPORTUNITY_CREATE": State.last_seq = message["s"] if d["id"] in State.seen: # delivery is at least once: skip repeats continue State.seen[d["id"]] = True if len(State.seen) > SEEN_LIMIT: State.seen.popitem(last=False) handle_opportunity(d["opportunity"]) finally: if heartbeat_task: heartbeat_task.cancel()async def main(): while True: close_code = None try: async with websockets.connect(GATEWAY_URL) as ws: try: await listen(ws) finally: close_code = ws.close_code except websockets.ConnectionClosed: pass # the close code is printed below except (OSError, websockets.WebSocketException) as error: print(f"Connection problem: {error}") print(f"Closed with code {close_code}") if close_code in FATAL_CLOSE_CODES: sys.exit("The gateway told us not to reconnect. Check the token and the close codes page.") if close_code == IDENTIFY_AFRESH_CLOSE_CODE: State.session_id = State.last_seq = None # Back off between attempts: 1 s, 2 s, 4 s ... up to 30 s. delay = min(30, 2**State.attempts) if close_code == TOO_MANY_CONNECTIONS_CLOSE_CODE: delay = max(delay, TOO_MANY_CONNECTIONS_WAIT) await asyncio.sleep(delay) State.attempts += 1asyncio.run(main())Where to go next
- Connection lifecycle explains each step the examples take.
- Resume covers what to do when the connection drops.
- Repeats and stable identifiers covers why you may see an event twice.
- Troubleshooting maps a close code to a fix.