WebSocket Real-time Updates¶
Endpoint¶
Authentication¶
The WebSocket connection requires a valid JWT access token as a query parameter.
Invalid or expired tokens result in connection rejection (code 4001).
Connection Example¶
const ws = new WebSocket("ws://localhost:8080/ws/notifications?token=your_jwt_token");
ws.onopen = () => {
console.log("Connected to WebSocket");
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log("Received:", data);
};
ws.onclose = () => {
console.log("Disconnected");
};
Server Events¶
After shipment CRUD operations, the server sends JSON messages:
| Event | Trigger | Payload |
|---|---|---|
shipment_created |
POST /api/shipments | Full shipment object |
shipment_updated |
PUT /api/shipments/{id} | Full shipment object |
shipment_deleted |
DELETE /api/shipments/{id} | {"id": "uuid"} |
Example Event¶
{
"type": "shipment_created",
"data": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"tracking_id": "TRK-A1B2C3D4",
"sender_name": "Juan Pérez",
"status": "RECEIVED",
...
}
}
Keepalive¶
The server responds to ping messages with pong for keepalive:
Implementation Files¶
| Component | Location |
|---|---|
| ConnectionManager | core/websocket_manager.py |
| WebSocket Routes | modules/notifications/presentation/websocket_routes.py |
Reconnection Strategy¶
Client Library¶
Use websockets library (NOT httpx for WebSocket):