| 1 | # Schemars |
| 2 | |
| 3 | [](https://github.com/GREsau/schemars/actions) |
| 4 | [](https://crates.io/crates/schemars) |
| 5 | [](https://docs.rs/schemars/latest) |
| 6 | [](https://graham.cool/schemars) |
| 7 | [](https://blog.rust-lang.org/2023/11/16/Rust-1.74.0/) |
| 8 | |
| 9 | Generate JSON Schema documents from Rust code |
| 10 | |
| 11 | ## Basic Usage |
| 12 | |
| 13 | _For more detailed information, see the full [API documentation on docs.rs](https://docs.rs/schemars/latest), and the [detailed usage documentation website](https://graham.cool/schemars)._ |
| 14 | |
| 15 | If you don't really care about the specifics, the easiest way to generate a JSON schema for your types is to `#[derive(JsonSchema)]` and use the `schema_for!` macro. All fields of the type must also implement `JsonSchema` - Schemars implements this for many standard library types. |
| 16 | |
| 17 | ```rust |
| 18 | use schemars::{schema_for, JsonSchema}; |
| 19 | |
| 20 | #[derive(JsonSchema)] |
| 21 | pub struct MyStruct { |
| 22 | pub my_int: i32, |
| 23 | pub my_bool: bool, |
| 24 | pub my_nullable_enum: Option<MyEnum>, |
| 25 | } |
| 26 | |
| 27 | #[derive(JsonSchema)] |
| 28 | pub enum MyEnum { |
| 29 | StringNewType(String), |
| 30 | StructVariant { floats: Vec<f32> }, |
| 31 | } |
| 32 | |
| 33 | let schema = schema_for!(MyStruct); |
| 34 | println!("{}", serde_json::to_string_pretty(&schema).unwrap()); |
| 35 | ``` |
| 36 | |
| 37 | <details> |
| 38 | <summary>Click to see the output JSON schema...</summary> |
| 39 | |
| 40 | ```json |
| 41 | { |
| 42 | "$schema": "https://json-schema.org/draft/2020-12/schema", |
| 43 | "title": "MyStruct", |
| 44 | "type": "object", |
| 45 | "properties": { |
| 46 | "my_bool": { |
| 47 | "type": "boolean" |
| 48 | }, |
| 49 | "my_int": { |
| 50 | "type": "integer", |
| 51 | "format": "int32" |
| 52 | }, |
| 53 | "my_nullable_enum": { |
| 54 | "anyOf": [ |
| 55 | { |
| 56 | "$ref": "#/$defs/MyEnum" |
| 57 | }, |
| 58 | { |
| 59 | "type": "null" |
| 60 | } |
| 61 | ] |
| 62 | } |
| 63 | }, |
| 64 | "required": ["my_int", "my_bool"], |
| 65 | "$defs": { |
| 66 | "MyEnum": { |
| 67 | "oneOf": [ |
| 68 | { |
| 69 | "type": "object", |
| 70 | "properties": { |
| 71 | "StringNewType": { |
| 72 | "type": "string" |
| 73 | } |
| 74 | }, |
| 75 | "additionalProperties": false, |
| 76 | "required": ["StringNewType"] |
| 77 | }, |
| 78 | { |
| 79 | "type": "object", |
| 80 | "properties": { |
| 81 | "StructVariant": { |
| 82 | "type": "object", |
| 83 | "properties": { |
| 84 | "floats": { |
| 85 | "type": "array", |
| 86 | "items": { |
| 87 | "type": "number", |
| 88 | "format": "float" |
| 89 | } |
| 90 | } |
| 91 | }, |
| 92 | "required": ["floats"] |
| 93 | } |
| 94 | }, |
| 95 | "additionalProperties": false, |
| 96 | "required": ["StructVariant"] |
| 97 | } |
| 98 | ] |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | ``` |
| 103 | |
| 104 | </details> |
| 105 | |
| 106 | ### Serde Compatibility |
| 107 | |
| 108 | One of the main aims of this library is compatibility with [Serde](https://github.com/serde-rs/serde). Any generated schema _should_ match how [serde_json](https://github.com/serde-rs/json) would serialize/deserialize to/from JSON. To support this, Schemars will check for any `#[serde(...)]` attributes on types that derive `JsonSchema`, and adjust the generated schema accordingly. |
| 109 | |
| 110 | ```rust |
| 111 | use schemars::{schema_for, JsonSchema}; |
| 112 | use serde::{Deserialize, Serialize}; |
| 113 | |
| 114 | #[derive(Deserialize, Serialize, JsonSchema)] |
| 115 | #[serde(rename_all = "camelCase", deny_unknown_fields)] |
| 116 | pub struct MyStruct { |
| 117 | #[serde(rename = "myNumber")] |
| 118 | pub my_int: i32, |
| 119 | pub my_bool: bool, |
| 120 | #[serde(default)] |
| 121 | pub my_nullable_enum: Option<MyEnum>, |
| 122 | } |
| 123 | |
| 124 | #[derive(Deserialize, Serialize, JsonSchema)] |
| 125 | #[serde(untagged)] |
| 126 | pub enum MyEnum { |
| 127 | StringNewType(String), |
| 128 | StructVariant { floats: Vec<f32> }, |
| 129 | } |
| 130 | |
| 131 | let schema = schema_for!(MyStruct); |
| 132 | println!("{}", serde_json::to_string_pretty(&schema).unwrap()); |
| 133 | ``` |
| 134 | |
| 135 | <details> |
| 136 | <summary>Click to see the output JSON schema...</summary> |
| 137 | |
| 138 | ```json |
| 139 | { |
| 140 | "$schema": "https://json-schema.org/draft/2020-12/schema", |
| 141 | "title": "MyStruct", |
| 142 | "type": "object", |
| 143 | "properties": { |
| 144 | "myBool": { |
| 145 | "type": "boolean" |
| 146 | }, |
| 147 | "myNullableEnum": { |
| 148 | "anyOf": [ |
| 149 | { |
| 150 | "$ref": "#/$defs/MyEnum" |
| 151 | }, |
| 152 | { |
| 153 | "type": "null" |
| 154 | } |
| 155 | ], |
| 156 | "default": null |
| 157 | }, |
| 158 | "myNumber": { |
| 159 | "type": "integer", |
| 160 | "format": "int32" |
| 161 | } |
| 162 | }, |
| 163 | "additionalProperties": false, |
| 164 | "required": ["myNumber", "myBool"], |
| 165 | "$defs": { |
| 166 | "MyEnum": { |
| 167 | "anyOf": [ |
| 168 | { |
| 169 | "type": "string" |
| 170 | }, |
| 171 | { |
| 172 | "type": "object", |
| 173 | "properties": { |
| 174 | "floats": { |
| 175 | "type": "array", |
| 176 | "items": { |
| 177 | "type": "number", |
| 178 | "format": "float" |
| 179 | } |
| 180 | } |
| 181 | }, |
| 182 | "required": ["floats"] |
| 183 | } |
| 184 | ] |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | ``` |
| 189 | |
| 190 | </details> |
| 191 | |
| 192 | `#[serde(...)]` attributes can be overriden using `#[schemars(...)]` attributes, which behave identically (e.g. `#[schemars(rename_all = "camelCase")]`). You may find this useful if you want to change the generated schema without affecting Serde's behaviour, or if you're just not using Serde. |
| 193 | |
| 194 | ### Schema from Example Value |
| 195 | |
| 196 | If you want a schema for a type that can't/doesn't implement `JsonSchema`, but does implement `serde::Serialize`, then you can generate a JSON schema from a value of that type. However, this schema will generally be less precise than if the type implemented `JsonSchema` - particularly when it involves enums, since schemars will not make any assumptions about the structure of an enum based on a single variant. |
| 197 | |
| 198 | ```rust |
| 199 | use schemars::schema_for_value; |
| 200 | use serde::Serialize; |
| 201 | |
| 202 | #[derive(Serialize)] |
| 203 | pub struct MyStruct { |
| 204 | pub my_int: i32, |
| 205 | pub my_bool: bool, |
| 206 | pub my_nullable_enum: Option<MyEnum>, |
| 207 | } |
| 208 | |
| 209 | #[derive(Serialize)] |
| 210 | pub enum MyEnum { |
| 211 | StringNewType(String), |
| 212 | StructVariant { floats: Vec<f32> }, |
| 213 | } |
| 214 | |
| 215 | let schema = schema_for_value!(MyStruct { |
| 216 | my_int: 123, |
| 217 | my_bool: true, |
| 218 | my_nullable_enum: Some(MyEnum::StringNewType("foo".to_string())) |
| 219 | }); |
| 220 | println!("{}", serde_json::to_string_pretty(&schema).unwrap()); |
| 221 | ``` |
| 222 | |
| 223 | <details> |
| 224 | <summary>Click to see the output JSON schema...</summary> |
| 225 | |
| 226 | ```json |
| 227 | { |
| 228 | "$schema": "http://json-schema.org/draft-07/schema#", |
| 229 | "title": "MyStruct", |
| 230 | "examples": [ |
| 231 | { |
| 232 | "my_bool": true, |
| 233 | "my_int": 123, |
| 234 | "my_nullable_enum": { |
| 235 | "StringNewType": "foo" |
| 236 | } |
| 237 | } |
| 238 | ], |
| 239 | "type": "object", |
| 240 | "properties": { |
| 241 | "my_bool": { |
| 242 | "type": "boolean" |
| 243 | }, |
| 244 | "my_int": { |
| 245 | "type": "integer" |
| 246 | }, |
| 247 | "my_nullable_enum": true |
| 248 | } |
| 249 | } |
| 250 | ``` |
| 251 | |
| 252 | </details> |
| 253 | |
| 254 | ## Versioning and Stability |
| 255 | |
| 256 | Schemars follows semantic versioning, with the following caveats: |
| 257 | |
| 258 | - Increasing MSRV (Minimum Supported Rust Version) is considered a semver-minor change. Schemars aims to support the past year of stable rust versions, but this is not guaranteed. |
| 259 | - External libraries that are supported via optional dependencies (see [Feature Flags](#feature-flags)) _may_ be removed in a minor version change, particularly if a newer semver-incompatible version has been released for a long time. |
| 260 | - The exact structure of generated schemas (both for built-in implementations on standard library types, and for `#[derive(JsonSchema)]` implementations) may change between versions of schemars - this is not considered a breaking change. |
| 261 | - Exported items that are marked with `#[doc(hidden)]` and have names beginning with `_` are not part of the public API, and may be changed or removed without notice. |
| 262 | - If a bug is found in schemars that causes attributes to be incorrectly processed or silently ignored by `#[derive(JsonSchema)]`, a subsequent version of schemars may instead fail compilation when encountering such attributes. This is considered a bug fix, and not a breaking change. |
| 263 | |
| 264 | ## Feature Flags |
| 265 | |
| 266 | - `std` (enabled by default) - implements `JsonSchema` for types in the rust standard library (`JsonSchema` is still implemented on types in `core` and `alloc`, even when this feature is disabled). Disable this feature to use schemars in `no_std` environments. |
| 267 | - `derive` (enabled by default) - provides `#[derive(JsonSchema)]` macro |
| 268 | - `preserve_order` - keep the order of struct fields in `Schema` properties |
| 269 | - `raw_value` - implements `JsonSchema` for `serde_json::value::RawValue` (enables the serde_json `raw_value` feature) |
| 270 | |
| 271 | Schemars can implement `JsonSchema` on types from several popular crates, enabled via feature flags (dependency versions are shown in brackets): |
| 272 | |
| 273 | - `arrayvec07` - [arrayvec](https://crates.io/crates/arrayvec) (^0.7) |
| 274 | - `bigdecimal04` - [bigdecimal](https://crates.io/crates/bigdecimal) (^0.4) |
| 275 | - `bytes1` - [bytes](https://crates.io/crates/bytes) (^1.0) |
| 276 | - `chrono04` - [chrono](https://crates.io/crates/chrono) (^0.4) |
| 277 | - `either1` - [either](https://crates.io/crates/either) (^1.3) |
| 278 | - `indexmap2` - [indexmap](https://crates.io/crates/indexmap) (^2.0) |
| 279 | - `jiff02` - [jiff](https://crates.io/crates/jiff) (^0.2) |
| 280 | - `rust_decimal1` - [rust_decimal](https://crates.io/crates/rust_decimal) (^1.0) |
| 281 | - `semver1` - [semver](https://crates.io/crates/semver) (^1.0.9) |
| 282 | - `smallvec1` - [smallvec](https://crates.io/crates/smallvec) (^1.0) |
| 283 | - `smol_str02` - [smol_str](https://crates.io/crates/smol_str) (^0.2.1) |
| 284 | - `smol_str03` - [smol_str](https://crates.io/crates/smol_str) (^0.3) |
| 285 | - `url2` - [url](https://crates.io/crates/url) (^2.0) |
| 286 | - `uuid1` - [uuid](https://crates.io/crates/uuid) (^1.0) |
| 287 | |
| 288 | Bear in mind that each of these feature flags _may_ be removed in a future semver-minor change of Schemars, particularly if a newer semver-incompatible version of the external library has been released for a long time. This is unfortunately necessary to avoid supporting old/unmaintained libraries indefinitely. |
| 289 | |
| 290 | For example, to implement `JsonSchema` on types from `chrono`, enable it as a feature in the `schemars` dependency in your `Cargo.toml` like so: |
| 291 | |
| 292 | ```toml |
| 293 | [dependencies] |
| 294 | schemars = { version = "1.0", features = ["chrono04"] } |
| 295 | ``` |