OpenAPI and JSON Schema

schemars and aide

Two-way bridge between vld and schemars - vld types as schemars::JsonSchema, and schemars types validated through vld.

Many crates (aide, okapi, paperclip, …) consume schemars::JsonSchema. vld_openapi::schemars0 / schemars1 connect them to vld in both directions:

  • vld → schemars: impl_json_schema!(T) implements schemars::JsonSchema from the vld json_schema().
  • schemars → vld: impl_vld_parse!(T) validates a #[derive(JsonSchema)] type against its schemars schema and implements vld::schema::VldParse, so it works with vld web extractors.

Install

Cargo.toml
[dependencies]
vld = "0.8"
vld-openapi = { version = "0.8", features = ["schemars-1"] }
FeatureModuleschemarsaide
schemars-0vld_openapi::schemars0>=0.9, <10.15
schemars-1vld_openapi::schemars1>=1, <20.16

Both modules have the same API and can be enabled together. Each re-exports its schemars crate as schemars; derive with vld_openapi::schemars1::schemars::JsonSchema to be sure the versions match. The version-independent tools (validator, introspection, to_openapi3) are in vld_openapi::validator, always compiled, and re-exported by both modules. The examples use schemars1.

Example

use vld_openapi::schemars1::prelude::*;
use vld_openapi::schemars1::schemars;

// vld -> schemars
vld::schema! {
    #[derive(Debug)]
    pub struct UserSchema {
        pub name: String  => vld::string().min(2).max(100),
        pub email: String => vld::string().email(),
        pub age: i64      => vld::number().int().min(0).max(150),
    }
}
impl_json_schema!(UserSchema);

let mut gen = schemars::SchemaGenerator::default();
let schema = <UserSchema as schemars::JsonSchema>::json_schema(&mut gen);
assert_eq!(schema.as_value()["properties"]["email"]["format"], "email");

// schemars -> vld
#[derive(Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
struct Product {
    name: String,
    price: f64,
}
impl_vld_parse!(Product);

let json = serde_json::json!({"name": "Widget", "price": 9.99});
let product = Product::vld_parse(&json).unwrap();       // validate + deserialize
assert!(product.vld_validate().is_ok());                 // validate an instance
assert!(Product::vld_validate_json(&serde_json::json!({"name": 1})).is_err());

API

ItemDescription
impl_json_schema!(T) / impl_json_schema!(T, "Name")schemars::JsonSchema for a vld type; nested types are added to the generator's definitions
impl_vld_parse!(T)VldParse + SchemarsValidate for a schemars type
SchemarsValidatevld_validate(&self), vld_validate_json(&Value), vld_parse(&Value)
vld_to_schemars(&Value)JSON Schema value → schemars::Schema (a non-schema value becomes false)
try_vld_to_schemars(&Value)Same, returns an error for a non-schema value
vld_schema_to_schemars(&Value)Alias of vld_to_schemars for a json_schema() result
schemars_to_json, generate_from_schemars::<T>(), generate_schemars::<T>()schemars → serde_json::Value / root schema
validate_with_schema(&schema, &value) / validate_with_schemarsValidate JSON against a JSON Schema, issues as VldError
to_openapi3(&mut Value)Rewrite vld's 2020-12 output into the OpenAPI 3.0 dialect
list_properties, list_properties_schemars, PropertyInfo, schema_type, is_required, get_propertyIntrospection helpers
schemas_equal, merge_schemas, overlay_constraintsCompare / combine schemas
VldSchemarsErrorValidation(VldError) or Deserialization(String)

Gotchas

  • impl_json_schema! rewrites vld's #/components/schemas/X refs to the generator's definitions path (#/$defs/X by default, #/components/schemas/X under SchemaSettings::openapi3()).
  • With an OpenAPI 3.0 generator (SchemaSettings::openapi3()) the output is converted by to_openapi3: tuples become items: {anyOf: [...]}, null branches become nullable: true, numeric exclusive bounds use the boolean 3.0 form.
  • The built-in validator (validate_with_schema, impl_vld_parse!) covers types, required fields, length / numeric / array / object constraints, enum, composites, patternProperties, prefixItems and local $refs. It does not check vld's x-* keywords (x-past, x-minUniqueItems, …) and most formats beyond a basic shape check. Validate with the vld schema itself when those matter.
  • impl_vld_parse! regenerates the schemars schema on every call. Cache the schema yourself on hot paths.

aide

aide builds OpenAPI documents from schemars::JsonSchema, so impl_json_schema! makes a vld type usable in aide::axum::Json<T> and friends; nested vld::nested! types land under aide's #/components/schemas/. vld-openapi does not depend on aide: add it yourself and pick the module of the schemars major it uses (cargo tree -i schemars): aide 0.15 → schemars-0 / schemars0, aide 0.16 → schemars-1 / schemars1.

Cargo.toml
[dependencies]
vld = { version = "0.8", features = ["derive"] }
vld-openapi = { version = "0.8", features = ["schemars-1"] }
aide = { version = "0.16", features = ["axum"] }

The aide body type must also implement serde::Deserialize, so use #[derive(Validate)] instead of schema!:

use aide::axum::{routing::post_with, ApiRouter, Json};
use aide::transform::TransformOperation;

#[derive(Debug, serde::Serialize, serde::Deserialize, vld::Validate)]
struct NewUser {
    #[vld(vld::string().min(2).max(100))]
    name: String,
    #[vld(vld::string().email())]
    email: String,
}
vld_openapi::schemars1::impl_json_schema!(NewUser);

async fn create_user(Json(body): Json<NewUser>) -> Json<serde_json::Value> {
    Json(serde_json::json!({"id": 1, "name": body.name}))
}

fn create_user_docs(op: TransformOperation) -> TransformOperation {
    op.summary("Create a user")
}

let app: ApiRouter = ApiRouter::new().api_route("/users", post_with(create_user, create_user_docs));
  • aide::axum::Json<T> deserializes with serde and does not run vld rules. Validate in the handler (NewUser::validate(&body), see parse vs validate) or use vld_web::axum extractors for the request and keep aide for the documentation.
  • Query and path structs get an object schema; there is no per-parameter IntoParams like in vld_openapi::utoipa5.
  • The full example is crates/vld-openapi/examples/aide_basic.rs (with schemars0).

See also JSON Schema.