openapi_trait/lib.rs
1//! Generate typed Rust traits from `OpenAPI` specifications.
2//!
3//! This crate exposes the [`axum`] and [`client`] attribute macros, which read
4//! an `OpenAPI` specification file at compile time and generate inside the
5//! annotated `mod`.
6//!
7//! # Examples
8//!
9//! ```rust
10//! #[openapi_trait::axum("assets/testdata/petstore.openapi.yaml")]
11//! pub mod petstore {}
12//!
13//! use petstore::PetstoreApi as _;
14//!
15//! #[derive(Clone)]
16//! struct MyServer;
17//!
18//! #[derive(Clone)]
19//! struct AppState;
20//!
21//! impl petstore::PetstoreApi<AppState> for MyServer {
22//! type Error = std::convert::Infallible;
23//!
24//! async fn get_pet_by_id(
25//! &self,
26//! req: petstore::GetPetByIdRequest,
27//! _state: axum::extract::State<AppState>,
28//! _headers: axum::http::HeaderMap,
29//! ) -> Result<petstore::GetPetByIdResponse, Self::Error> {
30//! Ok(petstore::GetPetByIdResponse::Status200(petstore::Pet {
31//! id: Some(req.pet_id),
32//! name: "doggie".into(),
33//! photo_urls: vec![],
34//! category: None,
35//! tags: None,
36//! status: None,
37//! }))
38//! }
39//! }
40//!
41//! let app: axum::Router = MyServer.router().with_state(AppState);
42//! ```
43//!
44//! The generated trait names come from the annotated module name, so `mod petstore {}`
45//! produces `petstore::PetstoreApi` and `petstore::PetstoreClient`.
46//!
47//! The `reqwest-client` feature is enabled by default. It adds [`ReqwestClient`],
48//! [`ReqwestClientCore`], and the [`reqwest`] re-export used by the generated blanket
49//! client implementation.
50
51#[doc(inline)]
52pub use openapi_trait_axum::openapi_trait as axum;
53
54#[doc(inline)]
55pub use openapi_trait_client::openapi_trait as client;
56
57/// Derive support for user-owned reqwest client carrier structs.
58///
59/// The derive looks for fields named `client` and `base_url` by default.
60/// Override those conventions with `#[openapi_trait(client)]` and
61/// `#[openapi_trait(base_url)]` on the corresponding fields.
62#[cfg(feature = "reqwest-client")]
63#[doc(inline)]
64pub use openapi_trait_client::ReqwestClient;
65
66/// Shared accessors used by generated reqwest client implementations.
67#[cfg(feature = "reqwest-client")]
68pub trait ReqwestClientCore {
69 /// Return the reqwest client used for outbound requests.
70 fn reqwest_client(&self) -> &reqwest::Client;
71
72 /// Return the base URL prepended to generated operation paths.
73 fn base_url(&self) -> &str;
74}
75
76#[cfg(feature = "reqwest-client")]
77pub use percent_encoding;
78#[cfg(feature = "reqwest-client")]
79pub use reqwest;