schemars/
lib.rs

1#![deny(
2    unsafe_code,
3    missing_docs,
4    unused_imports,
5    clippy::cargo,
6    clippy::pedantic,
7    clippy::exhaustive_structs,
8    clippy::exhaustive_enums
9)]
10#![allow(
11    clippy::must_use_candidate,
12    clippy::return_self_not_must_use,
13    clippy::wildcard_imports,
14    clippy::missing_errors_doc
15)]
16#![doc = include_str!("../README.md")]
17#![no_std]
18
19extern crate alloc;
20#[cfg(feature = "std")]
21extern crate std;
22
23mod json_schema_impls;
24mod schema;
25mod ser;
26#[macro_use]
27mod macros;
28
29/// This module is only public for use by `schemars_derive`. It should not need to be used by code
30/// outside of `schemars`, and should not be considered part of the public API.
31#[doc(hidden)]
32#[allow(clippy::exhaustive_structs)]
33pub mod _private;
34pub mod consts;
35pub mod generate;
36pub mod transform;
37
38#[cfg(feature = "schemars_derive")]
39extern crate schemars_derive;
40use alloc::borrow::Cow;
41
42#[cfg(feature = "schemars_derive")]
43pub use schemars_derive::*;
44
45#[doc(inline)]
46pub use generate::SchemaGenerator;
47pub use schema::Schema;
48
49mod _alloc_prelude {
50    pub use alloc::borrow::ToOwned;
51    pub use alloc::boxed::Box;
52    pub use alloc::format;
53    pub use alloc::string::{String, ToString};
54    pub use alloc::vec;
55    pub use alloc::vec::Vec;
56}
57
58#[deprecated = "Only included for backward-compatibility - use the `schemars::generate` module instead."]
59#[doc(hidden)]
60pub mod r#gen {
61    #[deprecated = "Only included for backward-compatibility - use `schemars::SchemaGenerator` or `schemars::generate::SchemaGenerator` instead."]
62    pub type SchemaGenerator = crate::generate::SchemaGenerator;
63    #[deprecated = "Only included for backward-compatibility - use `schemars::generate::SchemaSettings` instead."]
64    pub type SchemaSettings = crate::generate::SchemaSettings;
65    #[deprecated = "Only included for backward-compatibility - use `schemars::generate::GenTransform` instead."]
66    pub use crate::generate::GenTransform;
67}
68
69/// A type which can be described as a JSON Schema document.
70///
71/// This is implemented for many Rust primitive and standard library types.
72///
73/// This can also be automatically derived on most custom types with `#[derive(JsonSchema)]` by
74/// enabling the `derive` feature flag (which is enabled by default).
75/// For more info on deriving `JsonSchema`, see [the derive macro documentation](derive@JsonSchema).
76///
77/// # Examples
78/// Deriving an implementation:
79/// ```
80/// use schemars::{schema_for, JsonSchema};
81///
82/// #[derive(JsonSchema)]
83/// struct MyStruct {
84///     foo: i32,
85/// }
86///
87/// let my_schema = schema_for!(MyStruct);
88/// ```
89///
90/// When manually implementing `JsonSchema`, as well as determining an appropriate schema,
91/// you will need to determine an appropriate name and ID for the type.
92/// For non-generic types, the type name/path are suitable for this:
93/// ```
94/// use schemars::{SchemaGenerator, Schema, JsonSchema, json_schema};
95/// use std::borrow::Cow;
96///
97/// struct NonGenericType;
98///
99/// impl JsonSchema for NonGenericType {
100///     fn schema_name() -> Cow<'static, str> {
101///         // Exclude the module path to make the name in generated schemas clearer.
102///         "NonGenericType".into()
103///     }
104///
105///     fn schema_id() -> Cow<'static, str> {
106///         // Include the module, in case a type with the same name is in another module/crate
107///         concat!(module_path!(), "::NonGenericType").into()
108///     }
109///
110///     fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
111///         json_schema!({
112///             "foo": "bar"
113///         })
114///     }
115/// }
116///
117/// assert_eq!(NonGenericType::schema_id(), <&mut NonGenericType>::schema_id());
118/// ```
119///
120/// But generic type parameters which may affect the generated schema should typically be included
121/// in the name/ID:
122/// ```
123/// use schemars::{SchemaGenerator, Schema, JsonSchema, json_schema};
124/// use std::{borrow::Cow, marker::PhantomData};
125///
126/// struct GenericType<T>(PhantomData<T>);
127///
128/// impl<T: JsonSchema> JsonSchema for GenericType<T> {
129///     fn schema_name() -> Cow<'static, str> {
130///         format!("GenericType_{}", T::schema_name()).into()
131///     }
132///
133///     fn schema_id() -> Cow<'static, str> {
134///         format!(
135///             "{}::GenericType<{}>",
136///             module_path!(),
137///             T::schema_id()
138///         ).into()
139///     }
140///
141///     fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
142///         json_schema!({
143///             "foo": "bar"
144///         })
145///     }
146/// }
147///
148/// assert_eq!(<GenericType<i32>>::schema_id(), <&mut GenericType<&i32>>::schema_id());
149/// ```
150pub trait JsonSchema {
151    /// Only included for backward-compatibility - use `inline_schema()` instead".
152    ///
153    /// This will be removed before schemars 1.0 becomes stable.
154    #[deprecated = "Use `inline_schema()` instead"]
155    fn always_inline_schema() -> bool {
156        false
157    }
158
159    /// Whether JSON Schemas generated for this type should be included directly in parent schemas,
160    /// rather than being re-used where possible using the `$ref` keyword.
161    ///
162    /// For trivial types (such as primitives), this should return `true`. For more complex types,
163    /// it should return `false`. For recursive types, this **must** return `false` to prevent
164    /// infinite cycles when generating schemas.
165    ///
166    /// By default, this returns `false`.
167    fn inline_schema() -> bool {
168        #[allow(deprecated)]
169        Self::always_inline_schema()
170    }
171
172    /// The name of the generated JSON Schema.
173    ///
174    /// This is used as the title for root schemas, and the key within the root's `definitions`
175    /// property for subschemas.
176    fn schema_name() -> Cow<'static, str>;
177
178    /// Returns a string that uniquely identifies the schema produced by this type.
179    ///
180    /// This does not have to be a human-readable string, and the value will not itself be included
181    /// in generated schemas. If two types produce different schemas, then they **must** have
182    /// different `schema_id()`s, but two types that produce identical schemas should *ideally*
183    /// have the same `schema_id()`.
184    ///
185    /// The default implementation returns the same value as
186    /// [`schema_name()`](JsonSchema::schema_name).
187    fn schema_id() -> Cow<'static, str> {
188        Self::schema_name()
189    }
190
191    /// Generates a JSON Schema for this type.
192    ///
193    /// If the returned schema depends on any [non-inlined](JsonSchema::inline_schema)
194    /// schemas, then this method will add them to the [`SchemaGenerator`]'s schema definitions.
195    ///
196    /// This should not return a `$ref` schema.
197    fn json_schema(generator: &mut SchemaGenerator) -> Schema;
198
199    // TODO document and bring into public API?
200    #[doc(hidden)]
201    fn _schemars_private_non_optional_json_schema(generator: &mut SchemaGenerator) -> Schema {
202        Self::json_schema(generator)
203    }
204
205    // TODO document and bring into public API?
206    #[doc(hidden)]
207    fn _schemars_private_is_option() -> bool {
208        false
209    }
210}