fork of rust schemars
Find a file
Alexander Berger 364d0e0192
Add support to enforce inlining of all subschemas instead of using references. (#44)
This is needed to support use cases like openAPIV3Schema in Kubernetes CustomResourceDefinitions.


Co-authored-by: alex.berger@nexiot.ch <alex.berger@nexiot.ch>
2020-09-25 18:50:54 +01:00
.github/workflows Trim leading asterisks from doc block comments 2020-09-21 09:55:31 +01:00
docs Fix broken link in readme 2020-09-24 20:52:20 +01:00
schemars Add support to enforce inlining of all subschemas instead of using references. (#44) 2020-09-25 18:50:54 +01:00
schemars_derive Forbid unsafe code 2020-09-25 18:34:57 +01:00
.gitattributes Ensure json files are have LF line-endings. 2020-02-26 19:17:14 +00:00
.gitignore Initial commit 2019-08-04 16:48:29 +01:00
Cargo.toml Add workspace cargo.toml 2019-09-03 19:26:37 +01:00
CHANGELOG.md Add documentation comments, rename Visitor2 2020-09-24 20:34:30 +01:00
LICENSE Initial commit 2019-08-04 16:48:29 +01:00
README.md Fix broken link in readme 2020-09-24 20:52:20 +01:00
update-examples.sh Add examples to docs 2019-12-26 21:34:08 +00:00
update-tests.sh Add test for invalid schemars attributes 2020-06-05 17:18:48 +01:00

Schemars

CI Build Crates.io Docs rustc 1.36+

Generate JSON Schema documents from Rust code

Basic Usage

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.

use schemars::{schema_for, JsonSchema};

#[derive(JsonSchema)]
pub struct MyStruct {
    pub my_int: i32,
    pub my_bool: bool,
    pub my_nullable_enum: Option<MyEnum>,
}

#[derive(JsonSchema)]
pub enum MyEnum {
    StringNewType(String),
    StructVariant { floats: Vec<f32> },
}

fn main() {
    let schema = schema_for!(MyStruct);
    println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
Click to see the output JSON schema...
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "MyStruct",
  "type": "object",
  "required": [
    "my_bool",
    "my_int"
  ],
  "properties": {
    "my_bool": {
      "type": "boolean"
    },
    "my_int": {
      "type": "integer",
      "format": "int32"
    },
    "my_nullable_enum": {
      "anyOf": [
        {
          "$ref": "#/definitions/MyEnum"
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "definitions": {
    "MyEnum": {
      "anyOf": [
        {
          "type": "object",
          "required": [
            "StringNewType"
          ],
          "properties": {
            "StringNewType": {
              "type": "string"
            }
          }
        },
        {
          "type": "object",
          "required": [
            "StructVariant"
          ],
          "properties": {
            "StructVariant": {
              "type": "object",
              "required": [
                "floats"
              ],
              "properties": {
                "floats": {
                  "type": "array",
                  "items": {
                    "type": "number",
                    "format": "float"
                  }
                }
              }
            }
          }
        }
      ]
    }
  }
}

Serde Compatibility

One of the main aims of this library is compatibility with Serde. Any generated schema should match how serde_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.

use schemars::{schema_for, JsonSchema};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MyStruct {
    #[serde(rename = "myNumber")]
    pub my_int: i32,
    pub my_bool: bool,
    #[serde(default)]
    pub my_nullable_enum: Option<MyEnum>,
}

#[derive(Deserialize, Serialize, JsonSchema)]
#[serde(untagged)]
pub enum MyEnum {
    StringNewType(String),
    StructVariant { floats: Vec<f32> },
}

fn main() {
    let schema = schema_for!(MyStruct);
    println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
Click to see the output JSON schema...
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "MyStruct",
  "type": "object",
  "required": [
    "myBool",
    "myNumber"
  ],
  "properties": {
    "myBool": {
      "type": "boolean"
    },
    "myNullableEnum": {
      "default": null,
      "anyOf": [
        {
          "$ref": "#/definitions/MyEnum"
        },
        {
          "type": "null"
        }
      ]
    },
    "myNumber": {
      "type": "integer",
      "format": "int32"
    }
  },
  "additionalProperties": false,
  "definitions": {
    "MyEnum": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "object",
          "required": [
            "floats"
          ],
          "properties": {
            "floats": {
              "type": "array",
              "items": {
                "type": "number",
                "format": "float"
              }
            }
          }
        }
      ]
    }
  }
}

#[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.

Feature Flags

  • derive (enabled by default) - provides #[derive(JsonSchema)] macro
  • impl_json_schema - implements JsonSchema for Schemars types themselves
  • preserve_order - keep the order of struct fields in Schema and SchemaObject

Optional Dependencies

Schemars can implement JsonSchema on types from several popular crates, enabled via optional dependencies (dependency versions are shown in brackets):