Publish/Subscribe Operations

Document event-driven APIs with publish and subscribe operations

Operations in AsyncAPI are defined underneath the operations key, with channels defined under the channels key. Below is an example of defining publish and subscribe operations:

asyncapi.yml
1channels:
2 user/notifications:
3 address: user/notifications
4 messages:
5 UserNotification:
6 $ref: '#/components/messages/UserNotification'
7
8operations:
9 onUserNotification:
10 action: receive
11 channel:
12 $ref: '#/channels/user~1notifications'
13 summary: Receive user notifications
14 description: Subscribe to user notification events
15 sendUserNotification:
16 action: send
17 channel:
18 $ref: '#/channels/user~1notifications'
19 summary: Send user notification
20 description: Publish a user notification event

Message examples

You can provide examples of messages by using the examples key in your message definitions:

asyncapi.yml
1components:
2 messages:
3 UserNotification:
4 name: UserNotification
5 title: User Notification
6 summary: Notification sent to a user
7 contentType: application/json
8 payload:
9 $ref: '#/components/schemas/Notification'
10 examples:
11 - name: EmailNotification
12 summary: Example email notification
13 payload:
14 userId: "123e4567-e89b-12d3-a456-426614174000"
15 type: "email"
16 message: "Welcome to our service!"
17 priority: "medium"

Publish operations

Publish operations represent messages that your service sends to a channel:

asyncapi.yml
1operations:
2 publishOrderStatus:
3 action: send
4 channel:
5 $ref: '#/channels/order~1status'
6 summary: Publish order status update
7 description: Send order status updates to subscribers
8 message:
9 $ref: '#/components/messages/OrderStatus'

Subscribe operations

Subscribe operations represent messages that your service receives from a channel:

asyncapi.yml
1operations:
2 subscribeToUserSignups:
3 action: receive
4 channel:
5 $ref: '#/channels/user~1signup'
6 summary: Subscribe to user signups
7 description: Receive notifications when users sign up
8 message:
9 $ref: '#/components/messages/UserSignup'

Bi-directional communication

You can define both publish and subscribe operations for the same channel to enable bi-directional communication:

asyncapi.yml
1operations:
2 sendChatMessage:
3 action: send
4 channel:
5 $ref: '#/channels/chat~1room'
6 summary: Send chat message
7 description: Send a message to a chat room
8 receiveChatMessage:
9 action: receive
10 channel:
11 $ref: '#/channels/chat~1room'
12 summary: Receive chat message
13 description: Receive messages from a chat room