# How KCL Validates Configurations Against OpenAPI Specifications for Compliance

> KCL validates configurations against OpenAPI specs using a two-step pipeline. Convert OpenAPI to KCL schemas and run KCL-Vet for runtime constraint checking automatically.

- Repository: [The KCL Programming Language/kcl](https://github.com/kcl-lang/kcl)
- Tags: how-to-guide
- Published: 2026-03-05

---

**KCL validates configurations against OpenAPI specifications through a two-step pipeline that converts OpenAPI documents into native KCL schemas and executes them via the KCL-Vet validation engine, which transforms JSON or YAML input into KCL expressions for runtime constraint checking.**

The KCL-Vet validation engine provides a robust mechanism for ensuring configuration compliance with OpenAPI contracts in the `kcl-lang/kcl` repository. By leveraging schema generation tools and the core validation library located in `crates/tools/src/vet/`, KCL performs a unified transformation that turns OpenAPI schemas into executable KCL code with **check** blocks, then validates external data files against these schemas using the native KCL compiler and runtime.

## The KCL-Vet Validation Architecture

KCL achieves OpenAPI-based configuration validation by treating both the schema and the configuration data as KCL code. This approach unifies validation semantics and allows the existing KCL compiler to handle all type checking and constraint evaluation.

### Step 1: OpenAPI to KCL Schema Conversion

The process begins with the `kcl-openapi` plugin, which parses an OpenAPI document (JSON or YAML) and generates a corresponding KCL schema. According to the source analysis, this generated schema contains regular KCL `schema` declarations enriched with **check** blocks that encode OpenAPI constraints such as `required`, `enum`, `minimum`, `maximum`, and `format`.

The generated schema file mirrors the OpenAPI model definitions and serves as the validation contract. While the `kcl-openapi` crate exists outside the core repository, it produces standard KCL code that the internal validation engine consumes.

### Step 2: Runtime Validation Pipeline

The core validation logic resides in [`crates/tools/src/vet/validator.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/validator.rs). The `validate` function in this file orchestrates a four-phase pipeline:

1. **Loading**: The validator loads the user-provided configuration file (JSON, YAML, or TOML) via a **`LoaderKind`** enum that supports multiple data formats.

2. **Expression Building**: The **`ExprBuilder`** in [`crates/tools/src/vet/expr_builder.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/expr_builder.rs) transforms the loaded data into a KCL expression that constructs an instance of the generated schema.

3. **Program Injection**: The validator injects both the schema definition and the constructed expression into a temporary KCL program.

4. **Execution**: The program executes via **`kcl_runner::execute`**, where the KCL compiler evaluates the schema's `check` blocks. If any constraint fails, the runtime returns a detailed panic payload containing file, line, column, and error code information.

When validation succeeds, the `validate` function returns `true`; otherwise, it returns a comprehensive error describing the exact validation failure.

## Implementing OpenAPI Validation in Code

The KCL-Vet library exposes a Rust API that allows developers to integrate OpenAPI validation into their applications or CI/CD pipelines.

### Generating KCL Schemas from OpenAPI Documents

First, convert your OpenAPI specification into a KCL schema using the `kcl-openapi` crate:

```rust
use kcl_openapi::generator::OpenApiGenerator;

let openapi_path = "specs/petstore.yaml";
let generator = OpenApiGenerator::new(openapi_path)?;
let kcl_schema = generator.generate()?;   // Returns KCL code as String

// Write the schema to a .k file for later validation
std::fs::write("petstore_schema.k", &kcl_schema)?;

```

The generated file contains standard KCL `schema` declarations with `check` blocks that mirror OpenAPI validation keywords, enabling the KCL compiler to enforce constraints natively.

### Validating JSON and YAML Configurations

Once you have the schema file, validate configuration files against it using the `validate` function from [`crates/tools/src/vet/validator.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/validator.rs):

```rust
use kcl_tools::vet::validator::{validate, ValidateOption};
use kcl_tools::util::loader::LoaderKind;

let config_path = "configs/pet.json";
let schema_path = "petstore_schema.k";
let schema_name = Some("Pet".to_string());
let attribute_name = "value".to_string();

let opt = ValidateOption::new(
    schema_name,
    attribute_name,
    config_path.to_string(),
    LoaderKind::JSON,              // Supports JSON, YAML, or TOML
    Some(schema_path.to_string()),
    None,                          // No inline KCL code
    std::collections::HashMap::new(),
);

match validate(opt) {
    Ok(true) => println!("✅ Config conforms to OpenAPI spec"),
    Err(e)   => eprintln!("❌ Validation failed: {:#?}", e),
}

```

The `ExprBuilder` internally constructs a KCL expression that instantiates the schema with your configuration data, allowing the compiler to verify types and constraints.

### Using Inline Schemas for Automated Testing

For CI pipelines or dynamic validation scenarios, you can provide the schema as an inline string rather than a file path:

```rust
let schema_code = r#"
schema Pet:
    id: int
    name: str
    tag?: str

    check:
        id > 0
        name != ""
"#;

let opt = ValidateOption::new(
    Some("Pet".to_string()),
    "value".to_string(),
    "configs/pet.yaml".to_string(),
    LoaderKind::YAML,
    None,                           // No schema file path
    Some(schema_code.to_string()),  // Inline KCL schema
    std::collections::HashMap::new(),
);

assert!(validate(opt).unwrap(), "OpenAPI-derived validation failed");

```

This approach eliminates the need for intermediate schema files and enables programmatic validation workflows.

## Key Source Files and Components

The OpenAPI validation pipeline relies on several critical components within the `kcl-lang/kcl` repository:

- **[`crates/tools/src/vet/validator.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/validator.rs)** — Contains the `validate` function and `ValidateOption` struct that serve as the primary API entry point for configuration validation.

- **[`crates/tools/src/vet/expr_builder.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/expr_builder.rs)** — Implements the `ExprBuilder` that transforms loaded JSON/YAML data into KCL AST expressions for schema instantiation.

- **[`crates/tools/src/vet/tests.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/tests.rs)** — Provides unit tests demonstrating validation scenarios and error handling patterns.

- **[`crates/loader/src/util.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/loader/src/util.rs)** — Supplies helper functions for locating and loading configuration modules used by the validator.

- **`crates/runner/src/exec_err_data/*.stderr.json`** — Contains example error payloads produced when validation fails, demonstrating the detailed diagnostic information available.

## Summary

KCL validates configurations against OpenAPI specifications through a unified compilation approach that leverages existing language infrastructure:

- **OpenAPI schemas** convert to native KCL `schema` declarations with `check` blocks that encode validation constraints.
- **Configuration files** load via `LoaderKind` and transform into KCL expressions using `ExprBuilder` in [`crates/tools/src/vet/expr_builder.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/expr_builder.rs).
- **Unified execution** occurs through `kcl_runner::execute`, where the compiler evaluates constraints and returns precise error diagnostics.
- **Flexible integration** supports both file-based and inline schema validation via the `ValidateOption` API in [`crates/tools/src/vet/validator.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/validator.rs).
- **Multiple format support** enables validation of JSON, YAML, and TOML configurations against the same OpenAPI-derived schema.

## Frequently Asked Questions

### What configuration file formats does KCL-Vet support?

KCL-Vet supports **JSON**, **YAML**, and **TOML** configuration files through the `LoaderKind` enum in the validation API. The `ExprBuilder` handles the syntactic transformation of each format into equivalent KCL expressions, allowing a single OpenAPI-derived schema to validate data regardless of the source format.

### How does KCL enforce OpenAPI constraints like minimum values or enums?

During the OpenAPI-to-KCL conversion process, constraints such as `minimum`, `maximum`, `enum`, and `format` translate into **`check` blocks** within the generated KCL schema. When the KCL compiler executes the validation program in [`crates/tools/src/vet/validator.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/validator.rs), it evaluates these check blocks alongside type constraints, producing detailed error messages if any condition fails.

### Can I validate configurations without generating a schema file?

Yes, the `ValidateOption` struct accepts an optional `schema_code` parameter that allows you to pass KCL schema definitions as inline strings. This capability supports CI/CD pipelines and dynamic validation scenarios where writing intermediate files is impractical, while still providing full access to the validation engine in [`crates/tools/src/vet/validator.rs`](https://github.com/kcl-lang/kcl/blob/main/crates/tools/src/vet/validator.rs).

### What information does KCL provide when validation fails?

When validation fails, the KCL runtime returns a detailed panic payload that includes the **file path**, **line number**, **column number**, and **error code** where the constraint violation occurred. These diagnostics originate from the compiler's evaluation of `check` blocks and provide machine-readable error data suitable for automated reporting systems.