schemars/
macros.rs

1/// Generates a [`RootSchema`](crate::schema::RootSchema) for the given type using default settings.
2///
3/// The type must implement [`JsonSchema`](crate::JsonSchema).
4///
5/// # Example
6/// ```
7/// use schemars::{schema_for, JsonSchema};
8///
9/// #[derive(JsonSchema)]
10/// struct MyStruct {
11///     foo: i32,
12/// }
13///
14/// let my_schema = schema_for!(MyStruct);
15/// ```
16#[cfg(doc)]
17#[macro_export]
18macro_rules! schema_for {
19    ($type:ty) => {
20        $crate::gen::SchemaGenerator::default().into_root_schema_for::<$type>()
21    };
22}
23
24/// Generates a [`RootSchema`](crate::schema::RootSchema) for the given type using default settings.
25///
26/// The type must implement [`JsonSchema`](crate::JsonSchema).
27///
28/// # Example
29/// ```
30/// use schemars::{schema_for, JsonSchema};
31///
32/// #[derive(JsonSchema)]
33/// struct MyStruct {
34///     foo: i32,
35/// }
36///
37/// let my_schema = schema_for!(MyStruct);
38/// ```
39#[cfg(not(doc))]
40#[macro_export]
41macro_rules! schema_for {
42    ($type:ty) => {
43        $crate::gen::SchemaGenerator::default().into_root_schema_for::<$type>()
44    };
45    ($_:expr) => {
46        compile_error!("This argument to `schema_for!` is not a type - did you mean to use `schema_for_value!` instead?")
47    };
48}
49
50/// Generates a [`RootSchema`](crate::schema::RootSchema) for the given example value using default settings.
51///
52/// The value must implement [`Serialize`](serde::Serialize). If the value also implements [`JsonSchema`](crate::JsonSchema),
53/// then prefer using the [`schema_for!`](schema_for) macro which will generally produce a more precise schema,
54/// particularly when the value contains any enums.
55///
56/// If the `Serialize` implementation of the value decides to fail, this macro will panic.
57/// For a non-panicking alternative, create a [`SchemaGenerator`](crate::gen::SchemaGenerator) and use
58/// its [`into_root_schema_for_value`](crate::gen::SchemaGenerator::into_root_schema_for_value) method.
59///
60/// # Example
61/// ```
62/// use schemars::schema_for_value;
63///
64/// #[derive(serde::Serialize)]
65/// struct MyStruct {
66///     foo: i32,
67/// }
68///
69/// let my_schema = schema_for_value!(MyStruct { foo: 123 });
70/// ```
71#[macro_export]
72macro_rules! schema_for_value {
73    ($value:expr) => {
74        $crate::gen::SchemaGenerator::default()
75            .into_root_schema_for_value(&$value)
76            .unwrap()
77    };
78}