xschema

Quick Start

Getting Started with xschema

Introduction

XSchema converts JSON Schema to native validators (Zod, Pydantic, Effect, and more...) in many languages (Typescript, Python, Go, and more...) with full type inference. Every adapter runs against the official JSON Schema Test Suite, so you know exactly what works.

Components

Under the hood, xschema has these building blocks:

  • CLI - Does the heavy lifting: finds your schemas, handles all the JSON Schema complexity, and calls adapters to generate code. Also runs compliance tests against the official JSON Schema Test Suite
  • Configuration files - Define which schemas to process and how
  • Adapters - Convert bundled schemas to native validation code for each language
  • Clients - Language-specific packages to use generated schemas

These components don't have to be used together (framework mode): if you want to build your own pipeline and just use the conversion and adapters programmatically, see Runtime Mode.

Want to understand the architecture and design philosophy? Read What is XSchema.

Terminology

JSON Schema is a vocabulary for annotating and validating JSON documents. It's used in OpenAPI specs, API contracts, and configuration files. xschema takes JSON Schema as input and generates code for your preferred validation library.

Quick Setup

This example uses TypeScript. xschema supports multiple languages (see later)

Install the client and adapter

bun add @xschemadev/client @xschemadev/zod zod
npm install @xschemadev/client @xschemadev/zod zod
pnpm add @xschemadev/client @xschemadev/zod zod
yarn add @xschemadev/client @xschemadev/zod zod

Create a config file

user.xschema.jsonc
{
  "$schema": "https://xschema.dev/schemas/typescript.jsonc",
  "schemas": [
    {
      "id": "Profile",
      "sourceType": "file",
      "source": "./profile.schema.json",
      "adapter": "@xschemadev/zod"
    }
  ]
}

More on config files in Configuration Reference.

Run the generator

bunx xschema generate
npx xschema generate
pnpm exec xschema generate
yarn dlx xschema generate

This creates .xschema/xschema.gen.ts with your validators.

Use the generated schemas

import {  } from "@xschemadev/client";
import {  } from "./xschema.gen";

const  = ({  });

const profileSchema = ("user:Profile");
const profileSchema: ZodObject<{
    id: ZodString;
    name: ZodOptional<ZodString>;
    email: ZodString;
}, $loose>
const result = .({ : "123", : "alice@example.com" });
const result: ZodSafeParseResult<{
    [x: string]: unknown;
    id: string;
    email: string;
    name?: string | undefined;
}>

Learn More

New to xschema? Don't worry, we welcome your questions.

If you find anything confusing, please give your feedback on GitHub Discussions!

Get Started With Any Language

Reference

On this page