Backend Development
Generating OpenAPI with Rust proc-macros: zero boilerplate for Actix-Web
Writing API docs in Rust, I got tired of adding long macro parameters next to every endpoint. So I wrote my own proc-macro engine and published it on crates.io. Here's how it works.
My least favorite moment when building an API in Rust is when I think I'm done and move on to documentation. The code is ready, the types are in place, but for the Swagger UI I have to add long macro parameters to every endpoint and extra trait implementations to every struct. I end up writing the same information twice: once for the compiler, once for the docs.
Anything written twice eventually drifts apart. The endpoint changes, the docs stay old. So I wrote my own solution: ferivonus-swagger-gen, a compile-time OpenAPI 3.0 generator for Actix-Web that I published on crates.io.
The goal: write the code once
The usage I wanted was this: put a short marker above the endpoint and the struct, and leave the rest to the library.
#[derive(Serialize, ApiSchema)]
struct UserResponse {
id: u32,
username: String,
status: UserStatus,
}
#[register_api(
summary = "Get user details by ID",
tags = "User Management",
params = "id:integer",
response_model = "UserResponse"
)]
#[get("/users/{id}")]
async fn get_user(path: web::Path<u32>) -> Result<HttpResponse, ApiError> {
// ...
}When the app starts, all registered endpoints and types are collected and turned into an OpenAPI document. Opening the UI takes a single line on the App: .configure(ferivonus_config). Swagger UI is served at /fer-ui/ and the OpenAPI document at /ferivonus.json. If you want the UI off in production, there's ApiRegistry::new().deactivate_ui().
proc-macros: code that runs inside the compiler
Procedural macros are functions that take your code as a data structure during compilation and produce new code. syn parses the incoming code into Rust's syntax tree (AST), and quote lets you write the code you want to generate. #[derive(ApiSchema)] walks a struct's fields and writes code that produces the OpenAPI equivalent of each one.
Nested types
The most enjoyable part was type resolution. A nested type like Vec<Option<Uuid>> means, in OpenAPI, "an array of UUID-formatted strings whose items may be null". The macro unwraps the type recursively from the outside in: Vec is an array, Option marks nullability, Uuid is a string with format: uuid. Your own structs link to their definitions in the schema with $ref.
Distributed registration: inventory
The real question was: the macro sees each endpoint separately, so how do you collect them in one list? Keeping a global, mutable list in Rust is both hard and undesirable. The inventory crate offers a very elegant answer: records submitted with inventory::submit! in different modules, even different crates, can be iterated from one place at runtime.
// Code generated by the macro (simplified)
inventory::submit! {
RouteMeta { method: "GET", path: "/users/{id}", summary: "Get user details by ID", /* ... */ }
}
// At startup, every record is collected in one place
let registry = ApiRegistry::new();Because of this, users never list endpoints by hand. When they add a new endpoint, it's already in the docs.
The UI side
The presentation layer is embedded HTML that calls SwaggerUIBundle. To show responses as tabs, a small React plugin (TabbedResponsesPlugin) adjusts the DOM at runtime. Users don't need to install a separate front-end package; the UI comes with the dependency.
Publishing on crates.io
There's a big difference between using a library in your own project and publishing it for others. Error messages need to be clear, docs need examples, and versioning needs care. A macro error can reach the user as one of the compiler's most confusing messages, so I made a point of using syn::Error to show errors directly on the offending line.
When should you use it?
There are more mature alternatives; utoipa is the best known, and it offers fine-grained control for large teams. My library is for people who want to start faster with fewer parameters. The right tool depends on how much control versus simplicity a team wants.
Writing macros opened a window into the compiler for me. Once you start seeing code as a tree rather than text, you also see ways to eliminate repetition more easily. Writing a piece of information once is, I think, one of the simplest definitions of good engineering.
Related articles
- A realtime multiplayer Okey server: .NET 9, SignalR and an authoritative serverBackend Development · 4 min read
- A personal assistant with local AI: Ollama, DeepSeek and TauriArtificial Intelligence · 4 min read
- Synced playback across homes without port forwarding: Rust, Axum and Steam lobbiesSystems Programming · 5 min read