/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.
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.core syntaxpydantic-style reader-metadata props for inline value constraintsmalli validation, detailed error explanations and humanized messagesreitit-friendly coercionmalli introspectionExisting 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.
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.
schemallic.core: schema definitions, s/def, s/defn, pydantic-style props, registry, schema.core -> malli conversionschemallic.malli: validate, explain, humanize, coerce, encode, decode, form, type, json-schemaschemallic.ops: equal, equiv, extend, merge, intersect, patch, infoschemallic.gen: gen-schema, gen-edn, gen-data, data seeds, deterministic rand-seedsSchemallic 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.
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 integrationSchemallic 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]}))
m/validate for quick true/false checks.m/explain for detailed error analysis in development.m/humanize for user-facing error messages.m/decode for config loading and preprocessing.m/coerce for HTTP request validation.m/encoder, m/decoder and m/coercer for hot paths — create once, call many.m/json-schema for API documentation and client generation.m/form for runtime schema introspection.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?
{:id 1, :naem "Alice"} passes validation with open maps. Closed maps catch this immediately.schema.core behavior — if you're migrating from schema.core, closed-by-default means your existing validation semantics stay the same.^{: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 validationReader 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
| Prop | Types | Description |
|---|---|---|
:min, :max | Numeric | malli-native bounds |
:gt, :lt, :ge, :le | Numeric | Greater/less than, including inclusive forms |
:multiple-of | Numeric | Multiple of a number |
:positive, :negative | Numeric | Sign constraints |
:even, :odd | Numeric | Parity |
:min-digits, :max-digits, :decimal-places, :divisor-of, :finite | Numeric | Numeric shape constraints |
:min-length, :max-length | String | Length bounds |
:re, :pattern | String | Regex match |
:starts-with, :ends-with, :contains, :not-contains | String, Collection | Prefix, suffix and containment constraints |
:lower-case, :upper-case, :non-blank, :blank, :format | String | Text shape constraints |
:min-count, :max-count | Collection | Element count bounds |
:non-empty, :empty | String, Collection | Emptiness |
:distinct, :unique-items, :unique | Collection | Distinct elements |
:sorted, :sorted-desc | Collection | Sorted order |
:pred, :fn | Any | Custom 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.
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.)
Schema definitions and validated variables handle metadata differently:
| Form | Metadata target | Result |
|---|---|---|
(s/def Name schema) | schema value | Becomes 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]).
| Source | malli |
|---|---|
^{: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.
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 itPlain 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"}
=>)s/=> produces malli [:-> ...] schemas directly — no Prismatic FnSchema pass-through. Two ways to use it:
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)))
s/defn definitionss/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.
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 Behaviorss/def dispatches on its argument shape:
| Form | Kind | Behavior |
|---|---|---|
(s/def Name schema) | schema definition | Registers a reusable schema; value metadata -> malli properties |
(s/def name :- Schema value) | Validated variable | Validates value against the schema at definition time; throws on failure |
(s/def name value) | Regular variable | Plain 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
| Ctrl+k | Jump to recent docs |
| ← | Move to previous article |
| → | Move to next article |
| Ctrl+/ | Jump to the search field |