Overview
The Notification WebSocket API provides a real-time solution for delivering push notifications, alerts, and events to your applications. This API is ideal for building notification centers, toast messages, status updates, and other real-time alert systems.
Key Features
- Real-time notification delivery without polling
- Four notification types: info, warning, error, and success
- Configurable notification frequency
- Notification acknowledgment tracking
- Type-specific additional data fields
Connection
To connect to the Notification WebSocket API, use the following endpoint:
wss://mockly.me/ws/notify/{client_id}
Replace {client_id}
with a unique identifier for the client connecting to the notification service.
Configuration
After establishing the connection, you can optionally send a configuration message to customize the notification behavior:
{
"frequency": 5.0 // Time between notifications in seconds (min: 1.0, max: 30.0)
}
If no configuration is sent within 2 seconds of connecting, default values will be used.
Connection Code Examples
// Connect to the notification WebSocket
const clientId = 'client_' + Math.floor(Math.random() * 10000);
const notifySocket = new WebSocket(`wss://mockly.me/ws/notify/${clientId}`);
// Handle connection open
notifySocket.onopen = (event) => {
console.log('Connected to notification service');
// Optional: Send configuration
const config = {
frequency: 3.0 // Get a notification roughly every 3 seconds
};
notifySocket.send(JSON.stringify(config));
// Update UI to show connected state
document.getElementById('connection-status').textContent = 'Connected';
document.getElementById('connection-status').classList.add('text-green-600');
};
// Handle incoming notifications
notifySocket.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Notification received:', data);
// Display notification based on type
switch(data.type) {
case 'info':
showInfoNotification(data);
break;
case 'warning':
showWarningNotification(data);
break;
case 'error':
showErrorNotification(data);
break;
case 'success':
showSuccessNotification(data);
break;
case 'system':
console.log('System message:', data.message);
break;
}
// Optional: Acknowledge receipt of notification
if (data.id) {
acknowledgeNotification(data.id);
}
};
// Acknowledge notification receipt
function acknowledgeNotification(notificationId) {
notifySocket.send(JSON.stringify({
action: 'acknowledge',
id: notificationId
}));
}
// Handle connection close
notifySocket.onclose = (event) => {
console.log('Disconnected from notification service');
// Update UI to show disconnected state
document.getElementById('connection-status').textContent = 'Disconnected';
document.getElementById('connection-status').classList.remove('text-green-600');
document.getElementById('connection-status').classList.add('text-red-600');
// Attempt to reconnect after a delay
setTimeout(() => {
console.log('Attempting to reconnect...');
// Reconnection logic here
}, 5000);
};
import asyncio
import json
import random
import websockets
async def connect_to_notifications():
client_id = f"client_{random.randint(1000, 9999)}"
uri = f"wss://mockly.me/ws/notify/{client_id}"
async with websockets.connect(uri) as websocket:
print(f"Connected to notification service as {client_id}")
# Send configuration
config = {
"frequency": 5.0 # Get a notification roughly every 5 seconds
}
await websocket.send(json.dumps(config))
# Handle incoming notifications
while True:
try:
message = await websocket.recv()
data = json.loads(message)
# Handle different notification types
if data["type"] == "system":
print(f"SYSTEM: {data['message']}")
else:
# Print notification details
print(f"[{data['type'].upper()}] {data['title']}")
print(f"Message: {data['message']}")
print(f"ID: {data['id']}")
# Print additional data if available
if "priority" in data:
print(f"Priority: {data['priority']}")
if "action_required" in data:
print(f"Action required: {data['action_required']}")
if "error_code" in data:
print(f"Error code: {data['error_code']}")
if "completion_time" in data:
print(f"Completion time: {data['completion_time']}")
print('-' * 40)
# Acknowledge the notification
if random.random() > 0.5: # 50% chance to acknowledge
await websocket.send(json.dumps({
"action": "acknowledge",
"id": data["id"]
}))
except websockets.exceptions.ConnectionClosed:
print("Connection closed")
break
# Run the notification client
asyncio.run(connect_to_notifications())
Notification Types
The API supports four main notification types, each with specific additional data fields:
Info
Informational updates that don't require immediate action.
Additional fields:
priority
: "low", "medium", or "high"
Warning
Alert about potential issues that may require attention.
Additional fields:
action_required
: boolean indicating if user action is needed
Error
Notification about errors, failures, or critical issues.
Additional fields:
error_code
: numeric error code (typically 400-500)retry_allowed
: boolean indicating if retry is possible
Success
Confirmation of successful operations or processes.
Additional fields:
completion_time
: string indicating how long the operation took
Message Format
Receiving Notifications
You will receive notifications in the following JSON format:
Base Notification Format
{
"type": "info|warning|error|success",
"title": "Notification Title",
"message": "Detailed notification message",
"id": "notif_1234",
"timestamp": "2023-07-25T14:32:15.123456",
"read": false,
// Additional type-specific fields
}
Notification Examples
Info Notification
{
"type": "info",
"title": "Info Notification",
"message": "New update available",
"id": "notif_1234",
"timestamp": "2023-07-25T14:32:15.123456",
"read": false,
"priority": "medium"
}
Warning Notification
{
"type": "warning",
"title": "Warning Notification",
"message": "Your subscription will end soon",
"id": "notif_5678",
"timestamp": "2023-07-25T14:40:22.123456",
"read": false,
"action_required": true
}
Error Notification
{
"type": "error",
"title": "Error Notification",
"message": "Failed to connect to server",
"id": "notif_9012",
"timestamp": "2023-07-25T14:45:10.123456",
"read": false,
"error_code": 503,
"retry_allowed": true
}
Success Notification
{
"type": "success",
"title": "Success Notification",
"message": "Data synchronization completed",
"id": "notif_3456",
"timestamp": "2023-07-25T14:50:05.123456",
"read": false,
"completion_time": "3.25s"
}
Acknowledging Notifications
To acknowledge receipt of a notification, send the following JSON message:
{
"action": "acknowledge",
"id": "notif_1234" // ID of the notification to acknowledge
}
When a notification is acknowledged, you'll receive a system message confirming the acknowledgment:
Acknowledgment Response
{
"type": "system",
"message": "Notification notif_1234 marked as read",
"timestamp": "2023-07-25T14:33:05.123456"
}
Example Notification Center
Here's a simple notification center implementation using the Notification WebSocket API:
Live Demo
Try out the WebSocket Notification API with this interactive demo. Connect to receive real-time notifications of different types.
Notification Center
Notifications
Statistics
Notification Count
Read Status
Meet Mockly Assistant
Your AI assistant for API testing, debugging and code generation. Access the power of mockly.me directly in ChatGPT.
- Generate code examples in your preferred language
- Get guidance for request/response handling and formatting
- Supercharged by ChatGPT Plus from OpenAI
"How do I send data to a POST endpoint"
"I can show you how to structure your request with headers and JSON — here's a code example..."