
RESTful API Design and WebSocket Integration
Building and consuming market data and trading APIs
REST: Resources and Verbs
REST maps CRUD to HTTP: GET for reads, POST to create, PATCH for partial updates, DELETE to remove. Use status codes honestly—200 with an error JSON breaks clients.
Version in the path (/v1/), paginate large lists (cursor feeds for append-only streams), and document breaking changes with a deprecation window.
Keys and HMAC
API keys identify; secrets prove. For trading endpoints, HMAC a canonical string (method + path + body + timestamp) so the secret never rides the wire. Reject stale timestamps to block replays—±30s is a common window.
OAuth fits third-party apps; pure exchange bots often stay on key+HMAC. Rate limits: expect 429 and honor Retry-After.
WebSocket Upgrades
The session starts as HTTP GET with Upgrade: websocket; server returns 101 Switching Protocols. After that, frames are cheap compared to repeated TLS handshakes on HTTP polling.
Subscribe messages are usually JSON: method, channels, and sometimes auth signatures for private fills.
Books, Trades, Recovery
Trades stream is tick data; books are snapshot + delta with sequence numbers. If you miss sequences, resync from REST snapshot then apply deltas with sequence > snapshot.
Heartbeat: send ping or expect server pings; reconnect with jittered backoff to avoid thundering herds.
GraphQL and OpenAPI
GraphQL trims over-fetching for dashboards; many exchanges still expose REST for trading hot paths. OpenAPI (Swagger) specs help codegen and QA—keep examples copy-pasteable.
A Minimal Consumer Pattern
Run the WebSocket loop in a task, push last prices into a thread-safe map, expose HTTP for health checks. Log reconnect counts; alert when they spike.
Put signing and clock skew tests in CI: a broken HMAC in production is indistinguishable from “the market moved” until you audit logs.