Reusable parts in AsyncAPI provide flexibility, modularity, and code reusability. You can reuse the majority of document sections like messages, schema definitions, channels, operations, and more.
Reusable parts allow you to split up the AsyncAPI document into many files and reference them using the Reference Object. You can use the $ref keyword to reference the same document, another local file, or an external URL. The diagram below describes how to reuse parts in AsyncAPI:
Same document
You can use the $ref keyword to reference a component in an AsyncAPI document. In the example below, you define a component called MyMessageSchema under the schemas section to describe the structure of a message. Under the myChannel channel, you have a message with a payload definition that's represented as a reference to the MyMessageSchema schema via the $ref keyword.
1channels:2 myChannel:3 message:4 myMessage:5 payload:6 $ref: '#/components/schemas/MyMessageSchema'7components:8 schemas:9 MyMessageSchema:10 type: object11 properties:12 message:13 type: string
Another local file
You can reference another local document using the $ref keyword. Ensure the path to the local file is correct and accessible from your main AsyncAPI document.
In the code below, you reference the component from another local document, such as message-schema.yaml.
1UserSignup:2 name: UserSignup3 title: User signup4 summary: Action to sign a user up.5 description: A longer description6 contentType: application/json7 payload: null
In the code below, you use another local document, message-schema.yaml, through a reference inside the AsyncAPI document.
1channels:2 signUp:3 address: user/signedup4 messages:5 UserSignup:6 $ref: './message-schema.yaml#/UserSignup'7operations:8 user/signedup.publish:9 action: receive10 channel:11 $ref: '#/channels/signUp'12 messages:13 - $ref: '#/channels/signUp/messages/UserSignup'
External URL
You can reference an external URL using the $ref keyword. Ensure the external URL provides the referenced component in a compatible format, such as YAML or JSON. In the example below, you reference the component from an external URL. The $ref value specifies the full URL to the external resource and the component's location.
1channels:2 signUp:3 address: user/signedup4 messages:5 UserSignup:6 $ref: https://example.com/my-components.yaml#/schemas/MySchema7operations:8 user/signedup.publish:9 action: receive10 channel:11 $ref: '#/channels/signUp'12 messages:13 - $ref: '#/channels/signUp/messages/UserSignup'