MCPcopy Index your code
hub / github.com/GREsau/schemars

github.com/GREsau/schemars @v1.2.1

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.2.1 ↗ · + Follow
840 symbols 1,944 edges 140 files 45 documented · 5%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Schemars

CI Build Crates.io API Docs Usage Docs MSRV 1.74+

Generate JSON Schema documents from Rust code

Basic Usage

For more detailed information, see the full API documentation on docs.rs, and the detailed usage documentation website.

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> },
}

let schema = schema_for!(MyStruct);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());

Click to see the output JSON schema...

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "MyStruct",
  "type": "object",
  "properties": {
    "my_bool": {
      "type": "boolean"
    },
    "my_int": {
      "type": "integer",
      "format": "int32"
    },
    "my_nullable_enum": {
      "anyOf": [
        {
          "$ref": "#/$defs/MyEnum"
        },
        {
          "type": "null"
        }
      ]
    }
  },
  "required": ["my_int", "my_bool"],
  "$defs": {
    "MyEnum": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "StringNewType": {
              "type": "string"
            }
          },
          "additionalProperties": false,
          "required": ["StringNewType"]
        },
        {
          "type": "object",
          "properties": {
            "StructVariant": {
              "type": "object",
              "properties": {
                "floats": {
                  "type": "array",
                  "items": {
                    "type": "number",
                    "format": "float"
                  }
                }
              },
              "required": ["floats"]
            }
          },
          "additionalProperties": false,
          "required": ["StructVariant"]
        }
      ]
    }
  }
}

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> },
}

let schema = schema_for!(MyStruct);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());

Click to see the output JSON schema...

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "MyStruct",
  "type": "object",
  "properties": {
    "myBool": {
      "type": "boolean"
    },
    "myNullableEnum": {
      "anyOf": [
        {
          "$ref": "#/$defs/MyEnum"
        },
        {
          "type": "null"
        }
      ],
      "default": null
    },
    "myNumber": {
      "type": "integer",
      "format": "int32"
    }
  },
  "additionalProperties": false,
  "required": ["myNumber", "myBool"],
  "$defs": {
    "MyEnum": {
      "anyOf": [
        {
          "type": "string"
        },
        {
          "type": "object",
          "properties": {
            "floats": {
              "type": "array",
              "items": {
                "type": "number",
                "format": "float"
              }
            }
          },
          "required": ["floats"]
        }
      ]
    }
  }
}

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

Schema from Example Value

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.

use schemars::schema_for_value;
use serde::Serialize;

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

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

let schema = schema_for_value!(MyStruct {
    my_int: 123,
    my_bool: true,
    my_nullable_enum: Some(MyEnum::StringNewType("foo".to_string()))
});
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",
  "examples": [
    {
      "my_bool": true,
      "my_int": 123,
      "my_nullable_enum": {
        "StringNewType": "foo"
      }
    }
  ],
  "type": "object",
  "properties": {
    "my_bool": {
      "type": "boolean"
    },
    "my_int": {
      "type": "integer"
    },
    "my_nullable_enum": true
  }
}

Versioning and Stability

Schemars follows semantic versioning, with the following caveats:

  • 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.
  • External libraries that are supported via optional dependencies (see Feature Flags) may be removed in a minor version change, particularly if a newer semver-incompatible version has been released for a long time.
  • 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.
  • 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.
  • 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.

Feature Flags

  • 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.
  • derive (enabled by default) - provides #[derive(JsonSchema)] macro
  • preserve_order - keep the order of struct fields in Schema properties
  • raw_value - implements JsonSchema for serde_json::value::RawValue (enables the serde_json raw_value feature)

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

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.

For example, to implement JsonSchema on types from chrono, enable it as a feature in the schemars dependency in your Cargo.toml like so:

[dependencies]
schemars = { version = "1.0", features = ["chrono04"] }

Extension points exported contracts — how you extend this code

Transform (Interface)
Trait used to modify a constructed schema and optionally its subschemas. See the [module documentation](self) for more [13 …
schemars/src/transform.rs
FromSerde (Interface)
(no doc) [4 implementers]
schemars_derive/src/ast/from_serde.rs
JsonSchema (Interface)
A type which can be described as a JSON Schema document. This is implemented for many Rust primitive and standard libra [22 …
schemars/src/lib.rs
GenTransform (Interface)
A [`Transform`] which implements additional traits required to be included in a [`SchemaSettings`]. You will rarely nee [1 …
schemars/src/generate.rs
NoSerialize (Interface)
(no doc) [1 implementers]
schemars/src/_private/mod.rs
NoJsonSchema (Interface)
(no doc) [1 implementers]
schemars/src/_private/mod.rs

Core symbols most depended-on inside this repo

insert
called by 64
schemars/src/schema.rs
remove
called by 30
schemars/src/schema.rs
get
called by 29
schemars/src/schema.rs
error_spanned_by
called by 28
schemars_derive/src/attr/mod.rs
clone
called by 27
schemars/src/generate.rs
duplicate_error
called by 25
schemars_derive/src/attr/mod.rs
path
called by 18
schemars_derive/src/attr/custom_meta.rs
mutual_exclusive_error
called by 17
schemars_derive/src/attr/mod.rs

Shape

Function 322
Method 220
Class 195
Enum 97
Interface 6

Languages

Rust100%

Modules by API surface

schemars/src/generate.rs50 symbols
schemars/src/schema.rs29 symbols
schemars/src/_private/mod.rs29 symbols
schemars/tests/integration/enums_option_flattened.rs28 symbols
schemars/tests/integration/enums_flattened.rs28 symbols
schemars/src/ser.rs25 symbols
schemars_derive/src/schema_exprs.rs23 symbols
schemars_derive/src/attr/mod.rs22 symbols
schemars/tests/integration/test_helper.rs22 symbols
schemars/tests/integration/enums.rs21 symbols
schemars_derive/src/attr/parse_meta.rs18 symbols
schemars/tests/integration/enums_ref_variants.rs18 symbols

For agents

$ claude mcp add schemars \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact