Liking cljdoc? Tell your friends :D

Introduction

At a glance

/SKEE-muh-lik/

schemallic = schema + malli + pydantic

Schemallic unifies schema.core contracts, malli machinery, and pydantic-like validations — plus much more.

Schemallic is a cross-ecosystem schema toolkit for Clojure: it keeps the schema.core syntax you already know, adds pydantic-style inline constraints, and runs validation, coercion and schema ops through malli. It generates random schemas and seeded data, compares and combines schemas, and offers optional reitit integration.

A semantic bridge between schema.core and malli.

Why Schemallic?

Schemallic started as a way to keep schema.core syntax while using the malli ecosystem. It grew into a full schema toolkit.

Schemallic can be used for:

  • schema definitions, validated vars and validated functions with schema.core syntax
  • pydantic-style reader-metadata props for inline value constraints
  • malli validation, detailed error explanations and humanized messages
  • Coercion, encoding and decoding for HTTP params, JSON and config data
  • JSON Schema output and reitit-friendly coercion
  • Registry-backed named and recursive schemas
  • Random schemas, EDN data and conforming test data with fixed values or deterministic seeds
  • schema comparison, compatibility and composition
  • Custom schema types and malli introspection

Existing schema.core definitions convert to malli forms, so projects can migrate without rewriting their schemas.

The point is not schema.core vs malli. The point is: use everything from malli (and more), and still keep schema.core syntax.

Usage

How it works

Schemallic converts one way: schema.core forms -> malli forms. There is no reverse conversion.

The center is SchemallicConverter (src/schemallic/converter/protocol.clj). Its default implementation lives in converter/core.clj. p/convert delegates to an s->m multimethod dispatched by resolve-type: primitive, predicate, combinator, fn schema, regex, map/vector/set, recursive, or literal fallback. Handlers in converter/handlers.clj call the same dispatch for nested values, so conversion recurses through the whole schema. Maps become closed [:map {:closed true} ...] unless metadata opts out. Results are cached by object identity.

s/def captures reader metadata at macro time when needed, stores named schemas in the protocol-backed def-macro registry, and attaches the converted malli form to the var. Props are split into malli-native props, native [:re] schemas, [:and ...] constraints and gen-only hints. s/recursive #'Name produces [:schema {:registry ...} key]; self-references become [:ref key]. Custom :inst and :number live on default-malli-registry, which schemallic.malli uses automatically; pass it explicitly only for raw malli calls.

malli, gen and ops all consume converted forms. Validation/coercion/introspection go through malli with CoercionTransformer for encode/decode/coerce. gen-data builds data from the converted schema and retries generation failures; ops compare or compose malli forms. Errors are ex-info with a machine-readable :code, and converter failures carry a trail through the schema tree.

Modules

  • schemallic.core: schema definitions, s/def, s/defn, pydantic-style props, registry, schema.core -> malli conversion
  • schemallic.malli: validate, explain, humanize, coerce, encode, decode, form, type, json-schema
  • schemallic.ops: equal, equiv, extend, merge, intersect, patch, info
  • schemallic.gen: gen-schema, gen-edn, gen-data, data seeds, deterministic rand-seeds

Basic usage

Schemallic re-exports the schema.core surface used in these examples -- you can use it without requiring schema.core directly:

(require '[schemallic.core :as s]
         '[schemallic.malli :as m])

;; Define schemas
(s/def User {:id s/Int :name s/Str})
(s/def CreateUserRequest {:name s/Str :email s/Str})

;; Validate variables
(s/def username :- s/Str "alice")

;; Define validated functions
(s/defn create-user :- User
  [req :- CreateUserRequest]
  {:id 1 :name (:name req)})

;; Validate with Malli
(m/validate User {:id 1 :name "Alice"})  ;; => true

The schema.core types and macros shown here (Int, Str, Bool, def, defn, optional-key, etc.) are available under the s/ alias.

Across the ecosystem

The same schema then works across the rest of the ecosystem:

(require '[schemallic.core :as s]
         '[schemallic.malli :as m]
         '[schemallic.ops :as o]
         '[schemallic.gen :as g])

(s/def User {:id s/Int :name s/Str})

(m/validate User {:id 1 :name "Alice"})        ; => true
(m/coerce User {:id "42" :name "Bob"})         ; => {:id 42 :name "Bob"}
(m/explain User {:id "bad" :name "Bob"})       ; => error details
(m/form User)                                  ; => [:map {:closed true} [:id :int] ...]

(s/def UserCopy {:id s/Int :name s/Str})
(g/gen-data User 1)                            ; => {:id -8522515, :name "n2IQ6opic1Pj8"}
(o/equal User UserCopy)                        ; => true

reitit integration

Schemallic schemas can be used directly as reitit route :parameters and :responses with malli coercion.

(require '[schemallic.core :as s]
         '[reitit.ring :as ring]
         '[reitit.coercion.malli :as malli-coercion]
         '[reitit.ring.coercion :as coercion])

(s/def CreateUserRequest {:name s/Str :email s/Str})
(s/def UserResponse {:id s/Int :name s/Str :email s/Str})

(defn create-user-handler [{{:keys [name email]} :body}]
  {:status 201 :body {:id 1 :name name :email email}})

(def router
  (ring/router
   [["/api"
     ["/users" {:post {:parameters {:body CreateUserRequest}
                       :responses {200 {:body UserResponse}}
                       :handler create-user-handler}}]]]
   {:coercion malli-coercion/coercion}))

(def app
  (ring/ring-handler
   router
   (ring/create-default-handler)
   {:middleware [coercion/coerce-exceptions-middleware
                 coercion/coerce-request-middleware
                 coercion/coerce-response-middleware]}))

Choosing the right API

  • Use m/validate for quick true/false checks.
  • Use m/explain for detailed error analysis in development.
  • Use m/humanize for user-facing error messages.
  • Use m/decode for config loading and preprocessing.
  • Use m/coerce for HTTP request validation.
  • Use m/encoder, m/decoder and m/coercer for hot paths — create once, call many.
  • Use m/json-schema for API documentation and client generation.
  • Use m/form for runtime schema introspection.

Features

Closed Maps by Default

Maps default to closed (:closed true) — extra keys are rejected unless explicitly opted out:

(s/def User {:id s/Int :name s/Str})

(m/validate User {:id 1 :name "Alice"})               ;; => true
(m/validate User {:id 1 :name "Alice" :role "admin"}) ;; => false (extra key)

;; Opt out when needed
(s/def FlexibleUser ^{:closed false} {:id s/Int :name s/Str})
(m/validate FlexibleUser {:id 1 :name "Alice" :role "admin"}) ;; => true

Why closed by default?

  • Silent bugs from typos — {:id 1, :naem "Alice"} passes validation with open maps. Closed maps catch this immediately.
  • API safety — extra keys in requests/responses often indicate a mismatch between client and server. Rejecting them early prevents hard-to-debug integration issues.
  • Matches schema.core behavior — if you're migrating from schema.core, closed-by-default means your existing validation semantics stay the same.
  • Explicit over implicit — opting into openness (^{:closed false}) is a deliberate choice. Opting out of strictness should require intent, not be the default.

Nested maps are individually closed as well — the handle-map* converter enforces this at every level.

pydantic-style validation

Reader metadata on schema entry values becomes inline validation, similar to pydantic's Field(...) in Python:

(s/def User
  {:id   ^{:min 1 :positive true}           s/Int
   :name ^{:min 1 :max 50 :re #"^[A-Z]"}    s/Str
   :age  ^{:min 0 :max 150}                 s/Int})

(m/validate User {:id 1 :name "Alice" :age 30})   ;; => true
(m/validate User {:id -5 :name "Alice" :age 30})   ;; => false

Supported Metadata Props

PropTypesDescription
:min, :maxNumericmalli-native bounds
:gt, :lt, :ge, :leNumericGreater/less than, including inclusive forms
:multiple-ofNumericMultiple of a number
:positive, :negativeNumericSign constraints
:even, :oddNumericParity
:min-digits, :max-digits, :decimal-places, :divisor-of, :finiteNumericNumeric shape constraints
:min-length, :max-lengthStringLength bounds
:re, :patternStringRegex match
:starts-with, :ends-with, :contains, :not-containsString, CollectionPrefix, suffix and containment constraints
:lower-case, :upper-case, :non-blank, :blank, :formatStringText shape constraints
:min-count, :max-countCollectionElement count bounds
:non-empty, :emptyString, CollectionEmptiness
:distinct, :unique-items, :uniqueCollectionDistinct elements
:sorted, :sorted-descCollectionSorted order
:pred, :fnAnyCustom predicate

Note: :min/:max are malli-native. String regex, prefix/suffix, case, blank, containment and format props become native [:re] schemas. Numeric, collection and custom-predicate props become [:fn] constraints with custom messages. Some collection props also add gen-only hints so generation produces valid data directly.

Bare Predicates

Schemallic accepts bare predicate fns anywhere a schema is expected. They become opaque [:fn pred] schemas:

(s/def GameCharacterSettings {:id uuid?})   ;; -> [:map {:closed true} [:id [:fn uuid?]]]

When a native schema.core type exists, prefer it — it maps to a first-class malli type with richer error messages and coercion support:

(s/def GameCharacterSettings {:id s/Uuid})  ;; -> [:map {:closed true} [:id :uuid]]

This applies inside s/def/s/defn annotations. (If you define schemas with schema.core's own s/def instead, bare predicates are rejected by schema.core itself — use s/Uuid there.)

Metadata Placement

Schema definitions and validated variables handle metadata differently:

FormMetadata targetResult
(s/def Name schema)schema valueBecomes malli properties (:closed, :examples, etc.)
(s/def Name ^{:closed true} schema)schema value[:map {:closed true} ...]
(s/def name :- schema value)Symbol (var)Preserved as Clojure var metadata

Schema metadata (on the value) -> malli properties via apply-meta:

(s/def StrictUser ^{:closed true} {:id s/Int :name s/Str})
;; => [:map {:closed true} [:id :int] [:name :string]]

Var metadata (on the symbol) -> Clojure tooling (meta, doc):

(s/def ^{:doc {:summary "A user"}} user :- StrictUser {:id 1 :name "Alice"})
;; (doc #'user) => {:summary "A user"}

:doc, :author, :version on a schema definition are stripped from the malli form (they belong on the var, not in the schema). Use a schema definition with metadata on the schema value, then reference it in a validated variable to get both.

Element-level metadata also works on values inside vectors and sets:

(s/def Order {:lines ^{:min-count 1} [^{:gt 0} s/Int]})
;; => [:map {:closed true} [:lines ...]]

Each element's ^{} is applied to that element's type at conversion time — including nested containers ([[^{:gt 0} s/Int]]), set elements (#{^{:min 1} s/Int}), and tuples ([^{:gt 0} s/Int s/Str]).

How it flows

Sourcemalli
^{:min 18} s/Int[:int {:min 18}]
^{:positive true} s/Int[:and :int [:fn pos?]] (props attached to :fn)
^{:re #"^[A-Z]"} s/Str[:re #"^[A-Z]"]
{:name ^{:doc "A name"} s/Str}[:name {:doc "A name"} :string]

^{:doc ...}, ^{:author ...} and ^{:version ...} on a whole schema definition stay on the var. On an individual entry, :doc stays with that malli entry.

Data Generation

All metadata props work with gen-data — constraints are enforced during generation. Collection props get gen-only hints attached to the base schema so generation produces good data directly instead of retry-based such-that:

  • :min-count/:max-count/:non-empty/:empty on vector-like types use a native :min/:max gen schema
  • :sorted/:sorted-desc sort generated data (vectors, and sorted-sets/sorted-maps for sets and maps)
  • :contains appends the value when the generated collection misses it

Plain strings are sampled as mixed-case alphanumeric strings such as n2IQ6opic1Pj8, not prose. A regex pins the shape, so email examples below end in .com. Use the ^{:prop value} reader metadata syntax to attach metadata to schema entries:

(s/def User {:id   ^{:gt 0 :max 999999} s/Int
             :name ^{:min-length 3 :max-length 20} s/Str
             :email ^{:re #"^[a-z]{3,10}@[a-z]{3,10}\.com$"} s/Str})

(g/gen-data User 42)
;; => {:id 483, :name "2rqK9A5Xi2N948j68p1", :email "bax@txhbtjz.com"}

(g/gen-data User {:id 99} 42)  ;; data seed + deterministic seed
;; => {:id 99, :name "2rqK9A5Xi2N948j68p1", :email "bax@txhbtjz.com"}

Function Schema (=>)

s/=> produces malli [:-> ...] schemas directly — no Prismatic FnSchema pass-through. Two ways to use it:

Standalone function schemas

Define a function contract without defining a function:

;; Single arity: last arg is return type, rest are arg types
(s/=> s/Int s/Int s/Int)
;; => [:-> :int :int :int]

;; Multi-arity: each inner form is (=> Ret Arg...)
(s/=> (=> s/Str s/Str)
      (=> s/Str s/Str s/Int))
;; => [:function [:-> :string :string] [:-> :string :int :string]]

;; Name a function schema for reuse
(s/def AddFn (s/=> s/Int s/Int s/Int))
(s/def TransformFn (s/=> (=> s/Str s/Str)
                         (=> s/Str s/Str s/Int)))

In s/defn definitions

s/defn attaches :malli/schema var metadata using => under the hood:

(s/defn add :- s/Int
  [a :- s/Int b :- s/Int]
  (+ a b))

(:malli/schema (meta #'add))
;; => [:-> :int :int :int]

(s/defn greet :- s/Str
  ([name :- s/Str] (str "Hello, " name))
  ([name :- s/Str greeting :- s/Str] (str greeting ", " name)))

(:malli/schema (meta #'greet))
;; => [:function
;;     [:-> :string :string]
;;     [:-> :string :string :string]]

Primitives (s/Int, s/Str, etc.) are resolved at macro time. Complex types emit runtime (schemallic.converter.protocol/convert ...) forms.

Limitations

  • Return schema must be on the function name, not the arg vector
  • Schema metadata is only processed on top-level arguments

Destructuring

s/defn supports destructuring in arg vectors — map, vector, mixed, nested, and rest args — with full validation at every level.

Map destructuring:

(s/defn greet :- s/Str
  [{:keys [name greeting]} :- {:name s/Str :greeting s/Str}]
  (str greeting ", " name))

(greet {:name "Alice" :greeting "Hello"})  ;; => "Hello, Alice"
(greet {:name 123 :greeting "Hello"})      ;; => throws

Vector destructuring:

(s/defn sum-coords :- s/Int
  [[x y] :- [s/Int s/Int]]
  (+ x y))

(sum-coords [1 2])   ;; => 3
(sum-coords ["a" "b"]) ;; => throws

Mixed (map with nested vector):

(s/defn format-location :- s/Str
  [{:keys [city] [lat lng] :coords} :- {:city s/Str :coords [s/Num s/Num]}]
  (str city " (" lat ", " lng ")"))

Rest args:

(s/defn sum-all :- s/Int
  [x :- s/Int & {:keys [y z]} :- {:y s/Int :z s/Int}]
  (+ x (or y 0) (or z 0)))

(sum-all 1 :y 2 :z 3)  ;; => 6

Rest args receive raw sequences at runtime — schemallic converts them to maps/vectors before validation, then destructures as usual.

:or defaults:

Keys listed in :or are automatically marked {:optional true} in the malli schema, so omitted keys use their default value without failing validation:

(s/defn greet :- s/Str
  [{:keys [name greeting] :or {greeting "Hello"}} :- {:name s/Str :greeting s/Str}]
  (str greeting ", " name))

(greet {:name "Alice"})              ;; => "Hello, Alice"
(greet {:name "Alice" :greeting "Hi"}) ;; => "Hi, Alice"

:or works at any nesting level, including inside rest args:

(s/defn greet-opts :- s/Str
  [name :- s/Str & {:keys [greeting prefix] :or {greeting "Hello" prefix "Mr."}} :- {:greeting s/Str :prefix s/Str}]
  (str prefix " " name ", " greeting))

:syms destructuring:

Symbol-based destructuring works the same way as :keys, but with quoted symbols as keys in the schema:

(s/defn get-user :- s/Str
  [{user-name 'name user-age 'age} :- {'name s/Str 'age s/Int}]
  (str user-name " is " user-age))

Multi-arity with destructuring:

(s/defn greet :- s/Str
  ([{:keys [name]} :- {:name s/Str}]
   (str "Hello, " name))
  ([{:keys [name greeting]} :- {:name s/Str :greeting s/Str}
    suffix :- s/Str]
   (str greeting ", " name suffix)))

Any map form in arg position triggers map destructuring; any vector form triggers vector destructuring. It works similarly to schema.core/defn.

s/def: One Macro, Three Behaviors

s/def dispatches on its argument shape:

FormKindBehavior
(s/def Name schema)schema definitionRegisters a reusable schema; value metadata -> malli properties
(s/def name :- Schema value)Validated variableValidates value against the schema at definition time; throws on failure
(s/def name value)Regular variablePlain def, no validation

Warning: the third form — (s/def x 42) — is a plain def. It validates nothing. If you mean to validate a value against a schema you must use the :- form:

(s/def x 42)              ;; regular var — no validation
(s/def x :- s/Int 42)     ;; validated var — ok
(s/def x :- s/Int "nope") ;; => throws ExceptionInfo

Forgetting the :- is easy when migrating from an un-annotated def; it fails silently (you get a plain var instead of a validation error), so check the arg shape when a validated variable doesn't seem to be enforcing anything.

Can you improve this documentation? These fine people already did:
imitelis & D.
Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close