Skip to main content

openapi_trait_axum/
lib.rs

1//! Axum backend proc-macro for `openapi-trait`.
2//!
3//! This crate is not intended for direct use. Use the
4//! [`openapi-trait`](https://docs.rs/openapi-trait) crate instead, which
5//! re-exports the [`openapi_trait`] attribute macro from here as
6//! `openapi_trait::axum`.
7
8/// Code-generation modules for the axum backend.
9mod codegen;
10
11use proc_macro::TokenStream;
12use proc_macro2::Span;
13use quote::quote;
14use syn::{parse_macro_input, ItemMod, LitStr};
15
16/// Generates typed Rust code from an `OpenAPI` specification file.
17///
18/// Apply this attribute to a `mod` block. The macro reads the `OpenAPI`
19/// document at the given path (resolved relative to `CARGO_MANIFEST_DIR`) at
20/// compile time and replaces the module's contents with:
21///
22/// - Schema structs derived from `components/schemas`
23/// - A `{OperationId}Request` struct per operation (bundles path, query,
24///   header params and the request body)
25/// - Per-operation `{OperationId}Response` enums implementing
26///   [`axum::response::IntoResponse`](https://docs.rs/axum/latest/axum/response/trait.IntoResponse.html)
27/// - A `{ModName}Api<S = ()>` trait with one `async fn` per operation (keyed by
28///   `operationId`). Trait methods have a default implementation that returns
29///   `500 Internal Server Error`, so you only need to override the operations
30///   your server handles.
31/// - A `router` method on the trait that wires all operations to an
32///   [`axum::Router`](https://docs.rs/axum/latest/axum/struct.Router.html)
33///
34/// The generated trait name is derived from the annotated module name, so
35/// `mod petstore {}` produces `petstore::PetstoreApi`.
36///
37/// The crate recompiles automatically whenever the spec file changes.
38///
39/// # Arguments
40///
41/// First positional argument: path to the `OpenAPI` YAML or JSON file,
42/// relative to the crate root (`CARGO_MANIFEST_DIR`).
43///
44/// # Debugging
45///
46/// Set the `OPENAPI_TRAIT_DEBUG` environment variable to dump a prettyprinted
47/// copy of the code this macro generates (one level deep, without recursively
48/// expanding nested derives). Use `1`/`true` to write to a default directory
49/// (`$OUT_DIR/openapi-trait-debug`, or the system temp dir), or set it to a
50/// directory path to choose the location. The resolved file path is printed to
51/// stderr during the build.
52///
53/// # Errors
54///
55/// The macro emits a compile error if:
56///
57/// - The file cannot be found or read.
58/// - The `OpenAPI` document is malformed or cannot be parsed.
59/// - An operation is missing an `operationId`.
60#[proc_macro_attribute]
61pub fn openapi_trait(attr: TokenStream, item: TokenStream) -> TokenStream {
62    let path_lit = parse_macro_input!(attr as LitStr);
63    run_macro(&path_lit, item)
64}
65
66/// Run the core macro logic with the resolved spec path literal.
67fn run_macro(path_lit: &LitStr, item: TokenStream) -> TokenStream {
68    let module = parse_macro_input!(item as ItemMod);
69    let mod_ident = &module.ident;
70    let mod_vis = &module.vis;
71
72    let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") else {
73        return syn::Error::new(
74            Span::call_site(),
75            "CARGO_MANIFEST_DIR is not set; cannot resolve spec path",
76        )
77        .to_compile_error()
78        .into();
79    };
80
81    let spec_path = std::path::PathBuf::from(&manifest_dir).join(path_lit.value());
82    let spec_path_str = spec_path.to_string_lossy().into_owned();
83
84    let content = match std::fs::read_to_string(&spec_path) {
85        Ok(c) => c,
86        Err(e) => {
87            let msg = format!("cannot read OpenAPI spec `{spec_path_str}`: {e}");
88            return syn::Error::new(path_lit.span(), msg)
89                .to_compile_error()
90                .into();
91        }
92    };
93
94    let openapi: openapiv3::OpenAPI = match serde_yaml::from_str(&content) {
95        Ok(o) => o,
96        Err(e) => {
97            let msg = format!("cannot parse OpenAPI spec `{spec_path_str}`: {e}");
98            return syn::Error::new(path_lit.span(), msg)
99                .to_compile_error()
100                .into();
101        }
102    };
103
104    let body = codegen::generate_axum(mod_ident, &openapi);
105
106    let expanded = quote! {
107        // Re-compile when the spec file changes.
108        const _: &str = ::core::include_str!(#spec_path_str);
109
110        #[allow(
111            missing_docs,
112            missing_debug_implementations,
113            dead_code,
114            unused_imports,
115            clippy::all,
116            clippy::nursery,
117            clippy::pedantic,
118        )]
119        #mod_vis mod #mod_ident {
120            #body
121        }
122    };
123
124    openapi_trait_shared::debug::write_debug_output(mod_ident, &expanded);
125
126    expanded.into()
127}