Modern PetstoreAPI Docs
HomeGuides
Modern PetstoreAPIClassic PetstoreAPI
HomeGuides
Modern PetstoreAPIClassic PetstoreAPI
  1. Protocol Guides
  • Introduction
  • Quick Start Guide
  • API Protocols Guide
  • Protocol Guides
    • REST API
    • GraphQL
    • gRPC
    • Server-Sent Events (SSE)
    • WebSocket
    • Socket.IO
    • MQTT
    • Webhooks
    • MCP (Model Context Protocol)
HomeGuides
Modern PetstoreAPIClassic PetstoreAPI
HomeGuides
Modern PetstoreAPIClassic PetstoreAPI
  1. Protocol Guides

PetstoreAPI WebSocket Protocol Guide

Modern Petstore API provides WebSocket support for full-duplex, low-latency communication over a single TCP connection. Our WebSocket implementation enables real-time customer support chat through the /v1/ws/chat endpoint, allowing bidirectional messaging between users and support agents with typing indicators, message delivery confirmations, and agent assignment notifications.

Overview#

Protocol: WebSocket (RFC 6455)
Communication: Bidirectional (Client ↔ Server)
Endpoint: wss://api.petstoreapi.com/v1/ws/chat
When to Use WebSocket:
✅ Real-time chat applications
✅ Collaborative editing
✅ Live dashboards and monitoring
✅ Gaming and interactive applications
✅ Bidirectional communication required
When NOT to Use WebSocket:
❌ Only need server → client updates (use SSE instead)
❌ Simple request/response (use REST instead)

How WebSocket Works#

Client                                    Server
  │                                         │
  ├───────── HTTP Upgrade (WebSocket) ────>│
  │<──────────── 101 Switching Protocols ──┤
  │                                         │
  │<───────────── Message 1 ───────────────┤
  ├───────────── Message 2 ───────────────>│
  │<───────────── Message 3 ───────────────┤
  ├───────────── Message 4 ───────────────>│
  │          (persistent connection)        │
Key Characteristics:
Full-duplex communication (send and receive simultaneously)
Low latency overhead
Persistent connection
Binary and text data support
No HTTP overhead after handshake

Connection#

URL Format#

wss://api.petstoreapi.com/v1/ws/chat?token=YOUR_JWT_TOKEN
│   │                            │           │
│   │                            │           └─ Query params (auth)
│   │                            └────────────── Path
│   └────────────────────────────────────────── Host
└────────────────────────────────────────────── Protocol (wss = secure)

JavaScript (Browser)#

JavaScript (Node.js - ws library)#

Python (websockets)#


Message Types#

Chat Message#

Send:
{
  "type": "chatMessage",
  "payload": {
    "conversationId": "conv_abc123",
    "senderId": "user_xyz789",
    "content": "Hello, I need help with my order",
    "timestamp": "2025-01-06T12:00:00Z"
  }
}
Receive:
{
  "type": "chatMessage",
  "payload": {
    "conversationId": "conv_abc123",
    "messageId": "msg_xyz789",
    "senderId": "agent_abc123",
    "senderName": "Support Agent",
    "content": "Hi! How can I help you today?",
    "timestamp": "2025-01-06T12:00:01Z"
  }
}

Message Delivered#

{
  "type": "messageDelivered",
  "payload": {
    "conversationId": "conv_abc123",
    "messageId": "msg_xyz789",
    "timestamp": "2025-01-06T12:00:02Z"
  }
}

Message Read#

{
  "type": "messageRead",
  "payload": {
    "conversationId": "conv_abc123",
    "messageId": "msg_xyz789",
    "readBy": "user_xyz789",
    "timestamp": "2025-01-06T12:00:03Z"
  }
}

Typing Indicators#

Start Typing:
{
  "type": "typingStarted",
  "payload": {
    "conversationId": "conv_abc123",
    "userId": "user_xyz789"
  }
}
Stop Typing:
{
  "type": "typingStopped",
  "payload": {
    "conversationId": "conv_abc123",
    "userId": "user_xyz789"
  }
}

Agent Assigned#

{
  "type": "agentAssigned",
  "payload": {
    "conversationId": "conv_abc123",
    "agentId": "agent_abc123",
    "agentName": "Sarah Johnson",
    "timestamp": "2025-01-06T12:00:00Z"
  }
}

Advanced Usage#

Reconnection Logic#

Heartbeat/Ping-Pong#

Message Queue#


Authentication#

Query Parameter#

Subprotocol#


Error Handling#

Connection Errors#

Close Codes#


Best Practices#

1. Graceful Shutdown#

2. Message Validation#

3. Rate Limiting#


Troubleshooting#

Connection Drops#

Implement reconnection logic with exponential backoff
Check network connectivity
Verify authentication token is valid
Monitor close codes and reasons

Memory Leaks#

Clean up event listeners when closing
Don't accumulate message history indefinitely
Use weak references where appropriate

High CPU Usage#

Avoid tight loops when sending messages
Use requestAnimationFrame for UI updates
Batch message processing

Comparison with Alternatives#

FeatureWebSocketSSEPolling
DirectionBidirectionalServer → ClientClient → Server
LatencyVery LowLowHigh
OverheadVery LowLowHigh
Binary Support✅❌❌
Browser SupportExcellentExcellentUniversal
ReconnectionManualAutomaticN/A

Interactive Documentation#

API Specification: AsyncAPI 3.0
Protocol Overview: All Protocols
Socket.IO Guide: Socket.IO Protocol

Related Resources#

SSE Guide - For server → client streaming
Socket.IO Guide - WebSocket with fallbacks
Quick Start Guide
Modified at 2026-01-06 09:33:04
Previous
Server-Sent Events (SSE)
Next
Socket.IO
Built with