asyncapi-rust
AsyncAPI 3.0 specification generation for Rust WebSockets and async protocols
Generate AsyncAPI documentation directly from your Rust code using procedural macros. Similar to how utoipa generates OpenAPI specs for REST APIs, asyncapi-rust generates AsyncAPI specs for WebSocket and other async protocols.
Table of Contents
- Features
- Migrating from 0.3.x
- Migrating from 0.2.x
- Quick Start
- Examples
- Motivation
- Comparison: Manual vs Generated
- Supported Frameworks
- Binary Protocol Support
- DateTime Support (Chrono)
- Generating Specification Files
- Documentation
- Roadmap
- Contributing
- License
- Statement on AI/LLM Usage
- Acknowledgments
Features
- π¦ Code-first: Generate specs from Rust types, not YAML
- β‘ Compile-time: Zero runtime cost, all generation at build time
- π Type-safe: Compile errors if documentation drifts from code
- π― Familiar: Follows patterns from
utoipa,serde, andclap - π Framework agnostic: Works with actix-ws, axum, or any serde-compatible types
- π¦ Binary protocols: Support for mixed text/binary WebSocket messages (Arrow IPC, Protobuf, etc.)
Migrating from 0.3.x
Breaking change in 0.4.0: all map-typed fields on model structs (servers, channels, operations, components.messages, components.schemas, properties, etc.) changed from std::collections::HashMap to indexmap::IndexMap. This makes generated spec output byte-stable across builds β previously HashMap's random iteration order caused churn in downstream TypeScript codegen and other consumers even when the API hadn't changed.
If you construct model structs directly (e.g. in tests or a custom spec builder), replace HashMap::new() with IndexMap::new(). indexmap is re-exported from asyncapi_rust so you don't need to add it to your own Cargo.toml:
use IndexMap;
let mut servers = new;
servers.insert;
Code that only reads from these fields (iterating, .get(), .contains_key()) compiles unchanged β IndexMap has the same API as HashMap for read operations.
Migrating from 0.2.x
Breaking change in 0.3.0: message names in components.messages and asyncapi_message_names() now derive from the Rust variant identifier, not the serde rename string.
| Before (0.2.x) | After (0.3.0) |
|---|---|
messages.get("user.join") |
messages.get("UserJoin") |
asyncapi_message_names() β ["user.join", β¦] |
asyncapi_message_names() β ["UserJoin", β¦] |
The serde rename string remains the wire discriminant inside the payload schema β wire format is unchanged.
Other 0.3.0 additions:
#[asyncapi(message_name = "CustomName")]per-variant override for disambiguation- Runtime collision detection: two enums sharing a variant identifier in the same document panic with a clear error instead of silently overwriting
Schema::Anyhandlesserde_json::Valuefields without panicking- AsyncAPI 3.0βcompliant
Parameterobject (removedschema, addeddefault,enum_values,examples,location) - Shared
$defsare hoisted tocomponents.schemas; message payloads reference them via$ref: "#/components/schemas/X"
Quick Start
Add to your Cargo.toml:
[]
= "0.4"
= { = "1.0", = ["derive"] }
= { = "1.1", = ["derive"] }
# Optional: for chrono datetime support in schemas
= { = "0.4", = ["serde"] }
= { = "1.1", = ["derive", "chrono04"] }
Define your WebSocket messages:
use ;
use ;
/// WebSocket messages for a chat application
Message Integration
Combine message types into complete specifications using #[asyncapi_messages(...)]:
use ;
use ;
// Define your message types
// Reference message types in your API spec
// Automatically includes all messages
;
The #[asyncapi_messages(...)] attribute automatically populates the components/messages section with:
- All message definitions from referenced types
- Complete JSON schemas generated from Rust types
- Message metadata (name, summary, description, content-type)
Server Variables and Channel Parameters
Define dynamic server paths and channel parameters for WebSocket connections:
use AsyncApi;
;
Server variables define placeholders in server URLs with:
name: Variable name (required)description: Human-readable descriptionexamples: Example values for documentationdefault: Default value if not providedenum_values: Restricted set of allowed values
Channel parameters define path parameters with:
name: Parameter name (required)description: Human-readable descriptiondefault: Default value if not providedenum_values: Restricted set of allowed values (e.g.,["v1", "v2"])examples: Example values for documentation (e.g.,["42", "100"])location: Runtime expression for the parameter's location
Message Naming and Disambiguation
By default, message names in components.messages and asyncapi_message_names() are the Rust variant identifiers (UserJoin, Chat), not the serde rename strings ("user.join", "chat.message"). The serde rename is preserved as the wire discriminant inside the payload schema.
If two ToAsyncApiMessage enums in the same AsyncAPI document share a variant identifier, the runtime detects the collision and panics with a clear message. Use #[asyncapi(message_name = "β¦")] to disambiguate:
Both messages appear in components.messages under distinct keys (GetInfo and GetInfoResponse), with "get-info" as the wire value in both payload schemas.
#[asyncapi(message_name = "β¦")] attributes:
message_name = "CustomName": Override the default (variant ident) for a single variant- An empty serde rename (
#[serde(rename = "")]) automatically falls back to the variant identifier β no override needed
Examples
See working examples in the examples/ directory:
simple.rs- Basic message types with schema generationchat_api.rs- Complete AsyncAPI 3.0 specification with server, channels, and operationsmessage_integration.rs- Automatic message integration with#[asyncapi_messages(...)]server_variables.rs- Server variables and channel parameters for dynamic pathsasyncapi_derive.rs- Using#[derive(AsyncApi)]for specsfull_asyncapi_derive.rs- Complete spec with servers, channels, operationsgenerate_spec_file.rs- Generating specification filesactix_websocket.rs- Real-world actix-web + actix-ws integrationaxum_websocket.rs- Real-world axum WebSocket integrationframework_integration_guide.rs- Comprehensive framework integration guide
Run any example:
Motivation
Manually maintaining AsyncAPI specifications is error-prone and time-consuming:
- β Type changes in Rust require manual YAML updates
- β No compile-time validation of documentation accuracy
- β Easy for docs to drift from implementation
- β Repetitive work defining the same types twice
asyncapi-rust solves this by generating AsyncAPI specs directly from your Rust types, providing a single source of truth with compile-time guarantees.
Comparison: Manual vs Generated
Before (Manual YAML):
# asyncapi.yaml - must keep in sync manually!
components:
messages:
SendMessage:
payload:
type: object
properties:
type:
room:
text:
After (Generated from Rust):
/// Send a chat message
// AsyncAPI YAML generated automatically at compile time!
Supported Frameworks
- β actix-ws - Full integration with actix-web WebSocket handlers
- β axum - Integration with axum WebSocket routes
- π Framework-agnostic - Works with any serde-compatible message types
Binary Protocol Support
Document binary WebSocket messages (Arrow IPC, Protobuf, MessagePack):
/// Binary data stream
;
DateTime Support (Chrono)
asyncapi-rust uses schemars 1.1 with full support for chrono datetime types:
use ;
use ;
use ;
Cargo.toml configuration:
[]
= "0.4"
= { = "0.4", = ["serde"] }
= { = "1.1", = ["derive", "chrono04"] }
The chrono04 feature in schemars enables proper JSON schema generation for chrono datetime types. Without this feature, you would need to use #[schemars(skip)] and lose schema information for datetime fields.
Generating Specification Files
Standalone Binary (Recommended)
Create a separate binary in your project to generate AsyncAPI specs:
// bin/generate-asyncapi.rs
use MyApi;
use AsyncApi;
Run with:
Benefits:
- Simple to implement and use
- Works with any build system
- Can commit generated spec to git for CI/CD
- Easy to integrate into workflows
Including in Rustdoc
You can include the generated spec in your crate's documentation:
;
This embeds the AsyncAPI specification directly in your rustdoc output, making it accessible alongside your Rust API documentation.
Workflow:
- Generate the spec file:
cargo run --bin generate-asyncapi - Build docs:
cargo doc - The AsyncAPI spec will be visible in the rustdoc for
MyApi
Future: Cargo Plugin
A cargo-asyncapi plugin for automatic spec generation is planned for a future release. This would allow:
Documentation
Roadmap
- Core macro implementation
- actix-ws integration
- axum integration
- Binary message support
- Embedded AsyncAPI UI
- Additional framework support (tonic/gRPC, Rocket, Warp)
- Cargo plugin (
cargo-asyncapi) for automated spec generation - ~98% test coverage (measured by cargo-tarpaulin)
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
Statement on AI/LLM Usage
There has been a lot of discussion in the Rust community about usage of AI and LLMs. This project has been implemented with the assistance of Claude Code, but it is not vibe-coded. In a few years, using AI Tools will be common practice and these arguments will seem as quaint as those made decades ago against the use of IDEs. A human has designed this project and reviewed all code.
Acknowledgments
Inspired by:
- utoipa - OpenAPI code generation for Rust
- AsyncAPI Initiative - AsyncAPI specification
Author: Mark Lilback (mark@lilback.com) Repository: https://github.com/mlilback/asyncapi-rust