Skip to content
Learni
View all tutorials
Architecture Backend

How to Master AsyncAPI for Event-Driven APIs in 2026

Lire en français

Introduction

AsyncAPI is the open standard for documenting asynchronous and event-driven APIs. Unlike OpenAPI, which targets synchronous REST APIs, AsyncAPI models message flows between producers and consumers. In 2026, its adoption is essential for microservices, IoT, and data streaming architectures. This expert tutorial guides you from writing a complete specification to generating and implementing functional TypeScript code with Kafka. You will learn to handle schemas, bindings, and security schemes professionally.

Prerequisites

  • Node.js 20+ and TypeScript 5.4+
  • Advanced knowledge of event-driven architectures
  • Docker for Kafka and the AsyncAPI Generator
  • npm or pnpm installed

Basic AsyncAPI Specification

asyncapi.yaml
asyncapi: '3.0.0'
info:
  title: Order Processing API
  version: '1.0.0'
  description: API événementielle pour le traitement des commandes
servers:
  production:
    host: kafka.cluster.local:9092
    protocol: kafka
channels:
  orders.created:
    address: orders/created
    messages:
      orderCreated:
        payload:
          type: object
          properties:
            orderId:
              type: string
            amount:
              type: number

This YAML file defines the minimal AsyncAPI 3.0 document with a Kafka server and a channel for order creation events. It includes the payload schema to enable automatic validation.

Adding Operations and Bindings

asyncapi.yaml
operations:
  sendOrderCreated:
    action: send
    channel: $ref: '#/channels/orders.created'
    messages:
      - $ref: '#/channels/orders.created/messages/orderCreated'
    bindings:
      kafka:
        key:
          type: string
        partition: 0
  receiveOrderCreated:
    action: receive
    channel: $ref: '#/channels/orders.created'
    messages:
      - $ref: '#/channels/orders.created/messages/orderCreated'

Operations explicitly define the send/receive role and specific Kafka bindings. This allows code generators to produce correctly typed and configured stubs.

Generating TypeScript Code

terminal
npx @asyncapi/generator@2.5.0 asyncapi.yaml @asyncapi/nodejs-template -o ./generated -p server=production

The command generates a complete TypeScript SDK including types, publisher, and subscriber with Kafka bindings. The generated folder contains ready-to-use, compilable code.

Publisher Implementation

src/publisher.ts
import { OrderCreatedProducer } from '../generated';

const producer = new OrderCreatedProducer({
  clientId: 'order-service',
  brokers: ['kafka.cluster.local:9092']
});

export async function publishOrderCreated(order: { orderId: string; amount: number }) {
  await producer.send({
    key: order.orderId,
    value: order,
    partition: 0
  });
}

The publisher uses the generated classes to publish messages with strict typing. This prevents schema errors and ensures compatibility with consumers.

Subscriber Implementation

src/subscriber.ts
import { OrderCreatedConsumer } from '../generated';

const consumer = new OrderCreatedConsumer({
  groupId: 'order-processor',
  clientId: 'processor-service',
  brokers: ['kafka.cluster.local:9092']
});

consumer.on('orderCreated', async (message) => {
  console.log(`Processing order ${message.orderId}`);
  // Logique métier ici
});

The subscriber automatically subscribes to the channel and receives typed messages. Error handling and offset commits are included in the generated template.

Best Practices

  • Always version your AsyncAPI documents with semantic numbers
  • Use strict and reusable JSON Schema schemas
  • Explicitly declare security schemes (OAuth, API keys)
  • Test message compatibility with AsyncAPI Validator
  • Integrate code generation into your CI/CD pipeline

Common Mistakes to Avoid

  • Forgetting protocol-specific bindings (Kafka, MQTT)
  • Not validating payloads against the AsyncAPI schema before deployment
  • Ignoring message versioning and breaking changes
  • Using inconsistent partition keys leading to load imbalances

Going Further

Explore advanced features such as multi-protocol support and contract testing. Join our advanced AsyncAPI training to master large-scale event-driven architectures.