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)implementsschemars::JsonSchemafrom the vldjson_schema(). - schemars → vld:
impl_vld_parse!(T)validates a#[derive(JsonSchema)]type against its schemars schema and implementsvld::schema::VldParse, so it works with vld web extractors.
Install
[dependencies]
vld = "0.8"
vld-openapi = { version = "0.8", features = ["schemars-1"] }
| Feature | Module | schemars | aide |
|---|---|---|---|
schemars-0 | vld_openapi::schemars0 | >=0.9, <1 | 0.15 |
schemars-1 | vld_openapi::schemars1 | >=1, <2 | 0.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
| Item | Description |
|---|---|
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 |
SchemarsValidate | vld_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_schemars | Validate 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_property | Introspection helpers |
schemas_equal, merge_schemas, overlay_constraints | Compare / combine schemas |
VldSchemarsError | Validation(VldError) or Deserialization(String) |
Gotchas
impl_json_schema!rewrites vld's#/components/schemas/Xrefs to the generator's definitions path (#/$defs/Xby default,#/components/schemas/XunderSchemaSettings::openapi3()).- With an OpenAPI 3.0 generator (
SchemaSettings::openapi3()) the output is converted byto_openapi3: tuples becomeitems: {anyOf: [...]},nullbranches becomenullable: 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,prefixItemsand local$refs. It does not check vld'sx-*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.
[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 usevld_web::axumextractors for the request and keep aide for the documentation.- Query and path structs get an object schema; there is no per-parameter
IntoParamslike invld_openapi::utoipa5. - The full example is
crates/vld-openapi/examples/aide_basic.rs(withschemars0).
See also JSON Schema.