AsyncAPI Specification

repository·master·Indexed 11 days ago

https://github.com/asyncapi/spec

The standard for describing event-driven APIs. This protocol-agnostic, machine-readable format allows developers to define message-driven architectures using core abstractions such as Applications, Senders, Receivers, Channels, and Messages. It supports various protocols including Kafka, MQTT, WebSockets, AMQP, and STOMP.

Tokens
17.8K
Snippets
51
Records
73
Agent score
80%

What's inside AsyncAPI

  1. Overview of the AsyncAPI converter script

    master
    The converter script is a utility used to convert official AsyncAPI examples to newer versions of the specification once they are released. This ensures that the repository's example suite remains compatible with the evolving AsyncAPI standard.
  2. What is a Message Trait and how to use it

    master
    A Message Trait is a reusable object that can be applied to a Message Object to share common properties. A trait can contain any property from the Message Object except for payload and traits. When applied, traits MUST be merged using the AsyncAPI traits merge mechanism.
  3. Avoid deriving Receiver documents from Sender documents

    master

    It is NOT RECOMMENDED to automatically derive a Receiver AsyncAPI document from a Sender document (or vice versa).

    Even if the underlying channel is the same, the roles, metadata, and intent differ significantly. For example, an operation described as receive for a receiver might have a summary and description that do not make sense when converted to a send action for a sender. Additionally, infrastructure configurations (like read-only channels or intermediary forwarders) may exist that are not captured by simply flipping the action field.

  4. Use Multi Format Schema Objects for non-JSON schemas

    master

    When your message payload uses a schema format other than standard JSON Schema (e.g., Avro, Protobuf, or XSD), you must use a Multi Format Schema Object. This object requires two fields:

    1. schemaFormat: A string identifying the schema format. If omitted, it defaults to the AsyncAPI versioned format (e.g., application/vnd.aai.asyncapi+json;version=3.1.0).
    2. schema: The actual definition of the payload.

    Important Rules:

    • Non-JSON schemas (like Protobuf or XSD) MUST be inlined as a string.
    • JSON-based schemas (like Avro) should be inlined as a YAML or JSON object rather than a string.
    • When using a Reference Object within a multi-format schema, the schemaFormat of the referenced resource MUST match the schemaFormat of the parent schema.
    channels:
      example:
        messages:
          myMessage:
            payload:
              schemaFormat: 'application/vnd.apache.avro;version=1.9.0'
              schema:
                type: record
                name: User
                namespace: com.company
                doc: User information
                fields:
                  - name: displayName
                    type: string
                  - name: age
                    type: int
  5. Reference reusable schemas in the components object

    master

    When defining reusable schemas in components.schemas, you can use a standard Schema Object or a Multi Format Schema Object.

    If you provide a standard Schema Object, the schemaFormat is automatically assumed to be application/vnd.aai.asyncapi+json;version= followed by the current AsyncAPI version string. To use a different format (like Avro), you must explicitly provide the schemaFormat field.

    components:
      schemas:
        Category:
          type: object
          properties:
            id:
              type: integer
              format: int64
        AvroExample:
          schemaFormat: 'application/vnd.apache.avro+json;version=1.9.0'
          schema:
            $ref: './user-create.avsc'
  6. Understand the AsyncAPI Specification core concepts

    master

    The AsyncAPI Specification is a protocol-agnostic, machine-readable format used to describe message-driven APIs. It is designed to work across any protocol (e.g., AMQP, MQTT, WebSockets, Kafka, STOMP, HTTP, etc.).

    Core Abstractions

    • Application: Any computer program or group of programs (microservices, IoT devices, etc.) that acts as a Sender, a Receiver, or both.
    • Sender: An application that sends messages to Channels.
    • Receiver: An application that receives messages from Channels. A receiver might act as a consumer, a processor (aggregating messages), or a forwarder.
    • Server: The infrastructure (e.g., a message broker or a WebSocket service) that facilitates communication between senders and receivers.
    • Channel: An addressable component provided by the server used to organize messages. Senders target channels, and receivers listen to them.
    • Message: The mechanism for exchanging information. A message can include a payload (the data, serialized in formats like JSON, XML, or Avro) and headers (metadata).
    • Protocol: The wireline protocol or API used to exchange messages (e.g., Kafka, MQTT, WebSocket).
    • Bindings: A mechanism used to define protocol-specific information that goes beyond the generic AsyncAPI structure.
  7. How traits are merged

    master

    Traits are merged into target objects using the JSON Merge Patch algorithm in the order they are defined.

    Crucial Rule: A property defined in a trait MUST NOT override a property that already exists on the target object. If a conflict occurs, the target object's property is preserved.

    description: A longer description.
    traits:
      - name: UserSignup
        description: Description from trait.
      - tags:
          - name: user

    Resulting Object:

    name: UserSignup
    description: A longer description.
    tags:
      - name: user
  8. Use Channel Address Expressions

    master

    Channel addresses can be dynamic by using Channel Address Expressions.

    An expression MUST be a name enclosed in curly braces { and }. For example, {userId}. When using expressions in an address, you MUST also define the corresponding parameters in the parameters object of the Channel.

    Note: Query parameters and fragments SHALL NOT be used in the address; instead, use bindings to define them.

    {
      "address": "users.{userId}",
      "parameters": {
        "userId": {
          "$ref": "#/components/parameters/userId"
        }
      }
    }
  9. Use Server Variables for URL substitution

    master

    You can define variables in the variables map of a Server Object to create templates for the host and pathname fields. This is useful for switching between environments (e.g., production vs staging) using a single definition.

    host: 'rabbitmq.in.mycompany.com:5672'
    pathname: '/{env}'
    protocol: amqp
    description: RabbitMQ broker. Use the `env` variable to point to either `production` or `staging`.
    variables:
      env:
        description: Environment to connect to. It can be either `production` or `staging`.
        enum:
          - production
          - staging
  10. Implement Polymorphism with Discriminators

    master

    AsyncAPI supports polymorphism in schemas using a discriminator. A discriminator is a field in the schema that determines which specific sub-schema should be used for validation.

    • The discriminator property identifies the field name used to distinguish types.
    • Sub-schemas (like Cat or Dog) use allOf to inherit from the base schema.
    • The discriminator value can be matched against the schema name or a specific const value within the sub-schema.
    schemas:
      Pet:
        type: object
        discriminator: petType
        properties:
          name:
            type: string
          petType:
            type: string
        required:
        - name
        - petType
      Cat:
        allOf:
        - $ref: '#/components/schemas/Pet'
        - type: object
          properties:
            huntingSkill:
              type: string
              enum:
              - clueless
              - lazy
              - adventurous
              - aggressive
          required:
          - huntingSkill
  11. Organize reusable objects in the Components Object

    master
    The components object acts as a registry for reusable objects (such as schemas, message traits, or security schemes). Objects defined here have no effect on the AsyncAPI document unless they are explicitly referenced from other parts of the specification using a $ref.
  12. Use Operation Trait Objects to reuse operation properties

    master

    An Operation Trait Object allows you to define a reusable set of properties that can be applied to multiple Operation Objects. This is useful for applying common security, tags, or bindings across many operations.

    Constraints

    • A trait can contain any property from an Operation Object EXCEPT for action, channel, messages, and traits.
    • When applied to an operation, traits MUST be merged using the traits merge mechanism.
    {
      "bindings": {
        "amqp": {
          "ack": false
        }
      }
    }