Skip to content

AsyncAPI Code Generation — Complete Guide

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about AsyncAPI Code Generation. We cover key concepts, practical examples, and best practices to help you master this topic.

Code generation from AsyncAPI specifications automates the creation of client libraries, server stubs, documentation, and validation code. This lesson covers the AsyncAPI CLI, community generators, and integration patterns.

What You'll Learn

  • AsyncAPI CLI installation and usage
  • Available code generators
  • Generating clients and servers
  • Customizing generated code
  • CI/CD integration

Why It Matters

Manual implementation of event-driven clients is error-prone and time-consuming. Code generation ensures that implementations match the specification exactly, reducing integration issues.

Real-World Use

A streaming platform generates TypeScript clients for all microservices from AsyncAPI specs. When a new event is added, developers update the spec and regenerate clients, ensuring all consumers stay in sync.

Flow Chart

flowchart LR
    A[AsyncAPI Spec] --> B[AsyncAPI CLI]
    B --> C{Generator}
    C --> D[JavaScript Client]
    C --> E[Python Client]
    C --> F[Java Spring]
    C --> G[HTML Docs]
    C --> H[Markdown Docs]
    C --> I[Validation Schemas]
    D --> J[Published Package]
    F --> J
    G --> K[Documentation Site]

Code Examples

Example 1: AsyncAPI CLI Code Generation

# Install AsyncAPI CLI
npm install -g @asyncapi/cli

# Generate HTML documentation
asyncapi generate fromTemplate \
  ./asyncapi.yaml \
  @asyncapi/html-template \
  -o ./docs

# Generate Node.js client
asyncapi generate fromTemplate \
  ./asyncapi.yaml \
  @asyncapi/nodejs-template \
  -o ./client

# Generate Java Spring server
asyncapi generate fromTemplate \
  ./asyncapi.yaml \
  @asyncapi/java-spring-template \
  -o ./server

# Validate specification
asyncapi validate ./asyncapi.yaml

# List available templates
asyncapi list templates

Expected output: CLI validates the spec and generates code in the specified output directories.

Example 2: Custom Template Parameters

# Generate with custom parameters
asyncapi generate fromTemplate \
  ./asyncapi.yaml \
  @asyncapi/nodejs-template \
  -o ./src/generated \
  --param-name server=production \
  --param-name generateTestClient=true

# Using template configuration file
asyncapi generate fromTemplate \
  ./asyncapi.yaml \
  @asyncapi/java-spring-template \
  -o ./server \
  -p server=staging \
  -p package=com.example.events \
  -p artifactId=event-client

# Generate with custom template
asyncapi generate fromTemplate \
  ./asyncapi.yaml \
  ./my-custom-template \
  -o ./custom-generated \
  --map-template ./templates

Expected output: Generated code customized for specific server environment and package naming.

Example 3: Generated Node.js Client Usage

// Generated client from AsyncAPI spec
const { KafkaClient } = require('./generated/client');

const client = new KafkaClient({
  brokers: ['kafka://events.example.com:9092'],
  sasl: {
    mechanism: 'scram-sha-256',
    username: process.env.KAFKA_USERNAME,
    password: process.env.KAFKA_PASSWORD,
  },
});

// Generated types and methods
const producer = client.createProducer();

// Publish order created event
await producer.publishOrderCreated({
  orderId: 'ORD-123456',
  customerId: 'CUST-789',
  total: 99.99,
  items: [
    { productId: 'PROD-1', quantity: 2 },
  ],
});

// Subscribe to order events
const consumer = client.createConsumer();
consumer.onOrderCreated(async (event) => {
  console.log('Received order:', event.orderId);
  await processOrder(event);
});

consumer.connect();

Expected output: A fully typed Kafka client generated from the AsyncAPI spec with methods matching channel operations.

Common Mistakes

Mistake Explanation
Running generation without validation Always validate your spec first; invalid specs produce broken generated code
Ignoring generated code updates Regenerate code when the spec changes; manual modifications get overwritten
Forgetting to specify server Most generators need a server specified to configure connection details
Using incompatible templates Ensure the template version matches your AsyncAPI spec version
Not testing generated code Generated code should be integration-tested to verify it works with your broker

Practice Questions

  1. How do you install the AsyncAPI CLI?
  2. What types of code can be generated from an AsyncAPI spec?
  3. How do you pass custom parameters to a generator template?
  4. How do you integrate code generation into a CI/CD pipeline?
  5. What is the difference between client and server code generation?

Challenge

Create a CI/CD pipeline that validates an AsyncAPI specification, generates TypeScript client code, publishes it to an npm registry, generates HTML documentation, and deploys it to a documentation site. Include a Pull Request validation step.

FAQ

Can I generate code in languages besides Node.js?

Yes, the AsyncAPI community provides generators for Java, Python, Go, .NET, Rust, and many more languages.

How do I create a custom code generator?

Create a template repository following the AsyncAPI generator template specification and use it with asyncapi generate fromTemplate.

Does code generation support all protocols?

Most generators support Kafka and MQTT out of the box. Protocol-specific features depend on the template implementation.

Can I generate both producer and consumer code?

Yes, templates can generate both publish (producer) and subscribe (consumer) code from the same specification.

How do I handle multiple environments?

Use template parameters to pass environment-specific values (broker URLs, credentials) during generation.

What is the difference between the official and community templates?

Official templates are maintained by the AsyncAPI team. Community templates are maintained by individual contributors or organizations.

Mini Project

Build a code generation pipeline for an event-driven microservice. Create an AsyncAPI spec, build a custom generator template for your organization, integrate with GitHub Actions to generate code on pull requests, and publish the generated package to a private registry.

What's Next

Learn about AsyncAPI Studio for visual API design

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro