| Crates.io | asyncapi-rust-codegen |
| lib.rs | asyncapi-rust-codegen |
| version | 0.2.0 |
| created_at | 2025-11-06 17:23:33.568204+00 |
| updated_at | 2025-11-07 17:19:53.171773+00 |
| description | Procedural macro implementation for asyncapi-rust |
| homepage | https://github.com/mlilback/asyncapi-rust |
| repository | https://github.com/mlilback/asyncapi-rust |
| max_upload_size | |
| id | 1920043 |
| size | 71,356 |
⚠️ Early Development Notice
This project is in the early stages of development. Documentation, examples, and some links may be incomplete or broken. The API is not yet stable and may change significantly. Stay tuned for updates!
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.
utoipa, serde, and clapAdd to your Cargo.toml:
[dependencies]
asyncapi-rust = "0.2"
serde = { version = "1.0", features = ["derive"] }
schemars = { version = "1.1", features = ["derive"] }
# Optional: for chrono datetime support in schemas
chrono = { version = "0.4", features = ["serde"] }
schemars = { version = "1.1", features = ["derive", "chrono04"] }
Define your WebSocket messages:
use asyncapi_rust::{schemars::JsonSchema, ToAsyncApiMessage};
use serde::{Deserialize, Serialize};
/// WebSocket messages for a chat application
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
pub enum ChatMessage {
/// User joins a chat room
#[serde(rename = "user.join")]
UserJoin { username: String, room: String },
/// Send a chat message
#[serde(rename = "chat.message")]
Chat { username: String, room: String, text: String },
}
fn main() {
// Get message names
let names = ChatMessage::asyncapi_message_names();
println!("Messages: {:?}", names); // ["user.join", "chat.message"]
// Generate messages with JSON schemas
let messages = ChatMessage::asyncapi_messages();
// Each message includes:
// - name and title
// - contentType: "application/json"
// - payload: Full JSON Schema from schemars
let json = serde_json::to_string_pretty(&messages).unwrap();
println!("{}", json);
}
Combine message types into complete specifications using #[asyncapi_messages(...)]:
use asyncapi_rust::{AsyncApi, ToAsyncApiMessage, schemars::JsonSchema};
use serde::{Deserialize, Serialize};
// Define your message types
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
pub enum ChatMessage {
#[serde(rename = "user.join")]
UserJoin { username: String, room: String },
#[serde(rename = "chat.message")]
Chat { username: String, text: String },
}
// Reference message types in your API spec
#[derive(AsyncApi)]
#[asyncapi(title = "Chat API", version = "1.0.0")]
#[asyncapi_messages(ChatMessage)] // Automatically includes all messages
struct ChatApi;
fn main() {
let spec = ChatApi::asyncapi_spec();
// spec.components.messages now contains all ChatMessage variants
// with full JSON schemas
}
The #[asyncapi_messages(...)] attribute automatically populates the components/messages section with:
Define dynamic server paths and channel parameters for WebSocket connections:
use asyncapi_rust::AsyncApi;
#[derive(AsyncApi)]
#[asyncapi(title = "User WebSocket API", version = "1.0.0")]
#[asyncapi_server(
name = "production",
host = "api.enlightenhq.com",
protocol = "wss",
pathname = "/api/ws/{userId}",
variable(
name = "userId",
description = "Authenticated user ID",
examples = ["12", "13"]
)
)]
#[asyncapi_channel(
name = "rtMessaging",
address = "/api/ws/{userId}",
parameter(
name = "userId",
description = "User ID for this WebSocket connection",
schema_type = "integer",
format = "int64"
)
)]
struct UserApi;
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 valuesChannel parameters define typed path parameters with:
name: Parameter name (required)description: Human-readable descriptionschema_type: JSON Schema type (e.g., "integer", "string")format: JSON Schema format (e.g., "int64", "uuid")See working examples in the examples/ directory:
simple.rs - Basic message types with schema generation
cargo run --example simple
chat_api.rs - Complete AsyncAPI 3.0 specification with server, channels, and operations
cargo run --example chat_api
message_integration.rs - Demonstrates automatic message integration with #[asyncapi_messages(...)]
cargo run --example message_integration
server_variables.rs - Server variables and channel parameters for dynamic paths
cargo run --example server_variables
Manually maintaining AsyncAPI specifications is error-prone and time-consuming:
asyncapi-rust solves this by generating AsyncAPI specs directly from your Rust types, providing a single source of truth with compile-time guarantees.
Before (Manual YAML):
# asyncapi.yaml - must keep in sync manually!
components:
messages:
SendMessage:
payload:
type: object
properties:
type: { type: string, const: SendMessage }
room: { type: string }
text: { type: string }
After (Generated from Rust):
/// Send a chat message
#[derive(Serialize, Deserialize, ToAsyncApiMessage)]
#[serde(tag = "type", rename = "SendMessage")]
pub struct SendMessage {
pub room: String,
pub text: String,
}
// AsyncAPI YAML generated automatically at compile time!
Document binary WebSocket messages (Arrow IPC, Protobuf, MessagePack):
/// Binary data stream
#[derive(ToAsyncApiMessage)]
#[asyncapi(
name = "BinaryData",
content_type = "application/octet-stream",
binary = true,
description = "Binary data payload",
)]
pub struct BinaryData;
asyncapi-rust uses schemars 1.1 with full support for chrono datetime types:
use asyncapi_rust::{schemars::JsonSchema, ToAsyncApiMessage};
use chrono::{DateTime, NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, JsonSchema, ToAsyncApiMessage)]
#[serde(tag = "type")]
pub enum TimestampedMessage {
/// Event with timestamp
Event {
timestamp: DateTime<Utc>, // RFC3339 format
created_at: NaiveDateTime, // ISO8601 without timezone
message: String,
},
}
Cargo.toml configuration:
[dependencies]
asyncapi-rust = "0.2"
chrono = { version = "0.4", features = ["serde"] }
schemars = { version = "1.1", features = ["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.
Create a separate binary in your project to generate AsyncAPI specs:
// bin/generate-asyncapi.rs
use my_project::MyApi;
use asyncapi_rust::AsyncApi;
fn main() {
let spec = MyApi::asyncapi_spec();
let json = serde_json::to_string_pretty(&spec)
.expect("Failed to serialize spec");
std::fs::write("docs/asyncapi.json", json)
.expect("Failed to write spec file");
println!("✅ Generated docs/asyncapi.json");
}
Run with:
cargo run --bin generate-asyncapi
Benefits:
You can include the generated spec in your crate's documentation:
#[doc = include_str!("../docs/asyncapi.json")]
#[derive(AsyncApi)]
#[asyncapi(title = "My API", version = "1.0.0")]
struct MyApi;
This embeds the AsyncAPI specification directly in your rustdoc output, making it accessible alongside your Rust API documentation.
Workflow:
cargo run --bin generate-asyncapicargo docMyApiA cargo-asyncapi plugin for automatic spec generation is planned for a future release. This would allow:
cargo asyncapi generate
cargo asyncapi serve # Start AsyncAPI UI viewer
The examples/ directory contains working demonstrations:
simple.rs - Basic message types with schema generationchat_api.rs - Complete AsyncAPI 3.0 specificationasyncapi_derive.rs - Using #[derive(AsyncApi)] for specsgenerate_spec_file.rs - Generating specification filesfull_asyncapi_derive.rs - Complete spec with servers, channels, operationsmessage_integration.rs - Automatic message integration with #[asyncapi_messages(...)]actix_websocket.rs - Real-world actix-web + actix-ws integrationaxum_websocket.rs - Real-world axum WebSocket integrationframework_integration_guide.rs - Comprehensive framework integration guideRun any example:
cargo run --example message_integration
cargo run --example actix_websocket
cargo run --example axum_websocket
cargo-asyncapi) for automated spec generationContributions are welcome! Please see CONTRIBUTING.md for guidelines.
Licensed under either of:
at your option.
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.
Inspired by:
Author: Mark Lilback (mark@lilback.com) Repository: https://github.com/mlilback/asyncapi-rust