Asyncapi Websocket
title: "AsyncAPI with WebSocket" description: "Learn how to document WebSocket connections, message frames, channels, and real-time communication using AsyncAPI specifications." weight: 28 date: 2026-06-28 lastmod: 2026-06-28 tags: ["apis", "asyncapi"]
WebSocket is a full-duplex communication protocol for real-time applications. AsyncAPI provides bindings to document WebSocket endpoints, message framing, and connection lifecycle.
## What You'll Learn
- WebSocket server definitions in AsyncAPI
- Channel mapping for WebSocket
- Message framing and types
- Connection lifecycle documentation
- WebSocket security
## Why It Matters
WebSocket APIs often lack formal documentation. AsyncAPI brings contract-first design to real-time communication, making WebSocket APIs as well-documented as REST endpoints.
## Real-World Use
A real-time collaboration platform uses AsyncAPI to document its WebSocket API. The spec defines channels for document edits, cursor positions, and presence events. New frontend developers read the spec to understand all real-time capabilities.
## Flow Chart
```mermaid
flowchart LR
A[WebSocket AsyncAPI] --> B[Server Config]
A --> C[Channel Mapping]
A --> D[Message Frames]
B --> E[ws:// or wss://]
C --> F[Channels as Event Types]
D --> G[Text/Binary Frames]
D --> H[JSON/Protobuf]
Code Examples
Example 1: Basic WebSocket Server
asyncapi: '2.6.0'
info:
title: Real-Time Chat API
version: '1.0.0'
description: WebSocket-based chat application
servers:
production:
url: wss://chat.example.com/ws
protocol: wss
description: Production WebSocket server
security:
- bearerToken: []
channels:
chat/messages:
description: Chat message channel
subscribe:
operationId: sendMessage
summary: Send a chat message
message:
payload:
type: object
properties:
roomId:
type: string
text:
type: string
timestamp:
type: string
format: date-time
publish:
operationId: receiveMessage
summary: Receive chat messages
message:
payload:
type: object
properties:
messageId:
type: string
userId:
type: string
username:
type: string
text:
type: string
timestamp:
type: string
format: date-time
chat/typing:
subscribe:
operationId: typingIndicator
message:
payload:
type: object
properties:
roomId:
type: string
userId:
type: string
isTyping:
type: boolean
Expected output: A WebSocket-based chat API with channels for messages and typing indicators.
Example 2: WebSocket with Multiple Event Types
asyncapi: '2.6.0'
info:
title: Real-Time Dashboard
version: '1.0.0'
servers:
production:
url: wss://dashboard.example.com/realtime
protocol: wss
channels:
dashboard/events:
description: Real-time dashboard events
subscribe:
operationId: subscribeToEvents
summary: Subscribe to dashboard events
message:
oneOf:
- $ref: '#/components/messages/MetricUpdate'
- $ref: '#/components/messages/AlertTriggered'
- $ref: '#/components/messages/StatusChange'
components:
messages:
MetricUpdate:
name: MetricUpdate
payload:
type: object
properties:
metricName:
type: string
value:
type: number
unit:
type: string
timestamp:
type: string
format: date-time
AlertTriggered:
name: AlertTriggered
payload:
type: object
properties:
alertId:
type: string
severity:
type: string
enum: [info, warning, critical]
message:
type: string
StatusChange:
name: StatusChange
payload:
type: object
properties:
service:
type: string
oldStatus:
type: string
newStatus:
type: string
Expected output: A WebSocket channel that delivers different event types (metrics, alerts, status changes) through a single connection.
Example 3: WebSocket with Request-Response Pattern
asyncapi: '2.6.0'
info:
title: WebSocket RPC API
version: '1.0.0'
channels:
rpc/{method}:
parameters:
method:
schema:
type: string
enum:
- getStockQuote
- placeOrder
- getAccountBalance
subscribe:
operationId: callRpcMethod
summary: Call a remote procedure
message:
payload:
type: object
properties:
requestId:
type: string
format: uuid
params:
type: object
publish:
operationId: receiveRpcResponse
summary: Receive RPC response
message:
payload:
type: object
properties:
requestId:
type: string
format: uuid
result:
type: object
error:
type: string
rpc/stream/{symbol}:
parameters:
symbol:
schema:
type: string
subscribe:
operationId: subscribeToStockStream
summary: Subscribe to real-time stock prices
message:
payload:
type: object
properties:
subscribe:
type: boolean
publish:
operationId: receiveStockUpdates
summary: Receive stock price updates
message:
payload:
type: object
properties:
symbol:
type: string
price:
type: number
change:
type: number
volume:
type: integer
Expected output: A WebSocket RPC-style API with request-response patterns and streaming subscriptions.
Common Mistakes
| Mistake | Explanation |
|---|---|
| Confusing subscribe and publish | In WebSocket, subscribe means client sends to server; publish means server sends to client |
| Not documenting reconnection | Every WebSocket spec should mention reconnection strategy and backoff |
| Ignoring binary frames | If using binary protocols like Protobuf over WebSocket, document the binary format |
| Forgetting connection init | Document the initial handshake and any authentication messages required |
| Not handling connection errors | Document error message formats and status codes returned during connection failures |
Practice Questions
- How do WebSocket bindings differ from Kafka bindings in AsyncAPI?
- How do you document multiple event types on a single WebSocket connection?
- What is the difference between
wsandwssprotocol in server definitions? - How do you implement request-response patterns over WebSocket in AsyncAPI?
- How do you document WebSocket authentication?
Challenge
Design a WebSocket API for a real-time multiplayer game using AsyncAPI. Include channels for player movement, game state updates, chat, and matchmaking. Document connection initialization, heartbeats, and reconnection strategy.
FAQ
Mini Project
Design a comprehensive WebSocket API for a live auction platform using AsyncAPI. Include channels for bid submission, real-time price updates, auction timers, bidder presence, and outbid notifications. Document connection authentication, reconnection strategy, and message rate limits.
What's Next
Build a complete AsyncAPI project
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro