Skip to main content
Version: 0.13

Java API

Looking for the cross-language FFI contract? See ./ffi-abi.md for call, call_with_plugin_agent, the "ERROR:" prefix, the 4 MiB BUFFER_SIZE, and the kcl_lib_jni shared library. The com.kcl.api.API class below is a thin JNI wrapper over that single dispatcher; every typed method funnels through call(args).

The Java binding ships as a Maven artifact published via GitHub Packages. Two layers:

  • com.kcl.api.API — Java class implementing the typed RPC surface. Every method serialises its Spec.*Args proto, calls the native call(args) via JNI, parses the result proto, and surfaces the dispatcher "ERROR:..." reply as a thrown Exception.
  • com.kcl.api.Spec — auto-generated protobuf classes from spec/spec.proto.

Installation​

Refer to this to configure your Maven; set up your GitHub account and Token in the settings.xml.

Maven​

In your project's pom.xml, configure our repository as follows:

<repositories>
<repository>
<id>github</id>
<url>https://maven.pkg.github.com/kcl-lang/*</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>

This way you'll be able to import the above dependency to use the SDK.

<dependency>
<groupId>com.kcl</groupId>
<artifactId>kcl-lib</artifactId>
<version>0.13.0</version>
</dependency>

Quick Start​

import com.kcl.api.API;
import com.kcl.api.Spec.ExecProgramArgs;
import com.kcl.api.Spec.ExecProgramResult;

public class ExecProgramTest {
public static void main(String[] args) throws Exception {
API api = new API();
ExecProgramResult result = api
.execProgram(ExecProgramArgs.newBuilder().addKFilenameList("path/to/kcl.k").build());
System.out.println(result.getYamlResult());
}
}

API Reference​

execProgram​

Execute KCL file with arguments and return the JSON/YAML result.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Java Code

import com.kcl.api.*;

ExecProgramArgs args = ExecProgramArgs.newBuilder().addKFilenameList("schema.k").build();
API apiInstance = new API();
ExecProgramResult result = apiInstance.execProgram(args);

parseFile​

Parse KCL single file to Module AST JSON string with import dependencies and parse errors.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Java Code

import com.kcl.api.*;

ParseFileArgs args = ParseFileArgs.newBuilder().setPath("schema.k").build();
API apiInstance = new API();
ParseFileResult result = apiInstance.parseFile(args);

parseProgram​

Parse KCL program with entry files and return the AST JSON string.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Java Code

import com.kcl.api.*;
import com.kcl.ast.*;
import com.kcl.util.JsonUtil;

API api = new API();
ParseProgramResult result = api.parseProgram(
ParseProgramArgs.newBuilder().addPaths("path/to/kcl.k").build()
);
System.out.println(result.getAstJson());
Program program = JsonUtil.deserializeProgram(result.getAstJson());

loadPackage​

loadPackage provides users with the ability to parse KCL program and semantic model information including symbols, types, definitions, etc.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Java Code

import com.kcl.api.*;

API api = new API();
LoadPackageResult result = api.loadPackage(LoadPackageArgs.newBuilder().setResolveAst(true)
.setWithAstIndex(true)
.setParseArgs(ParseProgramArgs.newBuilder().addPaths("schema.k").build()).build());

listVariables​

listVariables provides users with the ability to parse KCL program and get all variables by specs.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Java Code

import com.kcl.api.*;

API api = new API();
ListVariablesResult result = api.listVariables(
ListVariablesArgs.newBuilder().setResolveAst(true).setParseArgs(
ParseProgramArgs.newBuilder().addPaths("/path/to/kcl.k").build())
.build());
result.getSymbolsMap().values().forEach(s -> System.out.println(s));

listOptions​

listOptions provides users with the ability to parse KCL program and get all option information.

Example

The content of options.k is

a = option("key1")
b = option("key2", required=True)
c = {
metadata.key = option("metadata-key")
}

Java Code

import com.kcl.api.*;

ParseProgramArgs args = ParseProgramArgs.newBuilder().addPaths("./src/test_data/option/main.k").build();
API apiInstance = new API();
ListOptionsResult result = apiInstance.listOptions(args);

getSchemaTypeMapping​

Get schema type mapping defined in the program.

Example

The content of schema.k is

schema AppConfig:
replicas: int

app: AppConfig {
replicas: 2
}

Java Code

import com.kcl.api.*;

ExecProgramArgs execArgs = ExecProgramArgs.newBuilder().addKFilenameList("schema.k").build();
GetSchemaTypeMappingArgs args = GetSchemaTypeMappingArgs.newBuilder().setExecArgs(execArgs).build();
API apiInstance = new API();
GetSchemaTypeMappingResult result = apiInstance.getSchemaTypeMapping(args);
KclType appSchemaType = result.getSchemaTypeMappingMap().get("app");
String replicasType = appSchemaType.getPropertiesOrThrow("replicas").getType();

getSchemaTypeMappingUnderPath​

Get schema type mapping defined in the program and its dependency packages, keyed by package name. Different from getSchemaTypeMapping, schemas imported from external dependency packages are keyed under their own package name instead of being flattened into __main__.

Example

Java Code

import com.kcl.api.*;
import java.nio.file.Path;
import java.nio.file.Paths;

Path root = Paths.get("test_data/get_schema_ty_under_path").toAbsolutePath();
ExecProgramArgs execArgs = ExecProgramArgs.newBuilder()
.addKFilenameList(root.resolve("aaa").toString())
.addExternalPkgs(ExternalPkg.newBuilder().setPkgName("bbb")
.setPkgPath(root.resolve("bbb").toString()).build())
.build();
GetSchemaTypeMappingArgs args = GetSchemaTypeMappingArgs.newBuilder().setExecArgs(execArgs).build();
API apiInstance = new API();
GetSchemaTypeMappingUnderPathResult result = apiInstance.getSchemaTypeMappingUnderPath(args);
KclType base = result.getSchemaTypeMappingOrThrow("bbb").getSchemaTypeList().stream()
.filter(s -> s.getSchemaName().equals("Base")).findFirst().orElseThrow();

overrideFile​

Override KCL file with arguments. See https://www.kcl-lang.io/docs/user_docs/guides/automation for more override spec guide.

Example

The content of main.k is

a = 1

b = {
"a": 1
"b": 2
}

Java Code

import com.kcl.api.*;

API api = new API();
String spec = "a=2";
OverrideFileResult result = api.overrideFile(OverrideFileArgs.newBuilder()
.setFile("./src/test_data/override_file/main.k").addSpecs(spec).build());

formatCode​

Format the code source.

Example

Java Code

import com.kcl.api.*;

String sourceCode = "schema Person:\n" + " name: str\n" + " age: int\n" + " check:\n"
+ " 0 < age < 120\n";
FormatCodeArgs args = FormatCodeArgs.newBuilder().setSource(sourceCode).build();
API apiInstance = new API();
FormatCodeResult result = apiInstance.formatCode(args);
String expectedFormattedCode = "schema Person:\n" + " name: str\n" + " age: int\n\n" + " check:\n"
+ " 0 < age < 120\n\n";

formatPath​

Format KCL file or directory path contains KCL files and returns the changed file paths.

Example

The content of format_path.k is

schema Person:
name: str
age: int

check:
0 < age < 120

Java Code

import com.kcl.api.*;

FormatPathArgs args = FormatPathArgs.newBuilder().setPath("format_path.k").build();
API apiInstance = new API();
FormatPathResult result = apiInstance.formatPath(args);
Assert.assertTrue(result.getChangedPathsList().isEmpty());

lintPath​

Lint files and return error messages including errors and warnings.

Example

The content of lint_path.k is

import math

a = 1

Java Code

import com.kcl.api.*;

LintPathArgs args = LintPathArgs.newBuilder().addPaths("lint_path.k").build();
API apiInstance = new API();
LintPathResult result = apiInstance.lintPath(args);
boolean foundWarning = result.getResultsList().stream()
.anyMatch(warning -> warning.contains("Module 'math' imported but unused"));

validateCode​

Validate code using schema and JSON/YAML data strings.

Example

Java Code

import com.kcl.api.*;

String code = "schema Person:\n" + " name: str\n" + " age: int\n" + " check:\n"
+ " 0 < age < 120\n";
String data = "{\"name\": \"Alice\", \"age\": 10}";
ValidateCodeArgs args = ValidateCodeArgs.newBuilder().setCode(code).setData(data).setFormat("json").build();
API apiInstance = new API();
ValidateCodeResult result = apiInstance.validateCode(args);

rename​

Rename all the occurrences of the target symbol in the files. This API will rewrite files if they contain symbols to be renamed. Return the file paths that got changed.

Example

The content of main.k is

a = 1
b = a

Java Code

import com.kcl.api.*;

RenameArgs args = RenameArgs.newBuilder().setPackageRoot(".").setSymbolPath("a")
.addFilePaths("main.k").setNewName("a2").build();
API apiInstance = new API();
RenameResult result = apiInstance.rename(args);

renameCode​

Rename all the occurrences of the target symbol and return the modified code if any code has been changed. This API won't rewrite files but return the changed code.

Example

Java Code

import com.kcl.api.*;

API api = new API();
RenameCodeArgs args = RenameCodeArgs.newBuilder().setPackageRoot("/mock/path").setSymbolPath("a")
.putSourceCodes("/mock/path/main.k", "a = 1\nb = a").setNewName("a2").build();
RenameCodeResult result = api.renameCode(args);

test​

Test KCL packages with test arguments.

Example

Java Code

import com.kcl.api.*;

API apiInstance = new API();
TestArgs args = TestArgs.newBuilder().addPkgList("/path/to/test/package").build();
TestResult result = apiInstance.test(args);

loadSettingsFiles​

Load the setting file config defined in kcl.yaml

Example

The content of kcl.yaml is

kcl_cli_configs:
strict_range_check: true
kcl_options:
- key: key
value: value

Java Code

import com.kcl.api.*;

API api = new API();
LoadSettingsFilesArgs args = LoadSettingsFilesArgs.newBuilder().addFiles("kcl.yaml")
.build();
LoadSettingsFilesResult result = api.loadSettingsFiles(args);

updateDependencies​

Download and update dependencies defined in the kcl.mod file and return the external package name and location list.

Example

The content of module/kcl.mod is

[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"

[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }

Java Code

import com.kcl.api.*;

API api = new API();

UpdateDependenciesResult result = api.updateDependencies(
UpdateDependenciesArgs.newBuilder().setManifestPath("module").build());

Call execProgram with external dependencies

Example

The content of module/kcl.mod is

[package]
name = "mod_update"
edition = "0.0.1"
version = "0.0.1"

[dependencies]
helloworld = { oci = "oci://ghcr.io/kcl-lang/helloworld", tag = "0.1.0" }
flask = { git = "https://github.com/kcl-lang/flask-demo-kcl-manifests", commit = "ade147b" }

The content of module/main.k is

import helloworld
import flask

a = helloworld.The_first_kcl_program

Java Code

import com.kcl.api.*;

API api = new API();

UpdateDependenciesResult result = api.updateDependencies(
UpdateDependenciesArgs.newBuilder().setManifestPath("./src/test_data/update_dependencies").build());

ExecProgramArgs execArgs = ExecProgramArgs.newBuilder(). addAllExternalPkgs(result.getExternalPkgsList())
.addKFilenameList("./src/test_data/update_dependencies/main.k").build();

ExecProgramResult execResult = api.execProgram(execArgs);

getVersion​

Return the KCL service version information.

Example

Java Code

import com.kcl.api.*;

API api = new API();
GetVersionArgs version_args = GetVersionArgs.newBuilder().build();
GetVersionResult result = api.getVersion(version_args);

(The exact version / checksum / git_sha values vary per release; assert only on non-empty.)

ping​

Round-trip a value through the dispatcher.

Example

import com.kcl.api.*;

API api = new API();
PingResult result = api.ping(PingArgs.newBuilder().setValue("hello").build());
assert result.getValue().equals("hello");

listMethod​

List the KCL service method names supported by the underlying runtime.

Example

import com.kcl.api.*;

API api = new API();
for (String name : api.listMethod().getMethodNameList()) {
System.out.println(name);
}

Notes​

The legacy BuildProgram and ExecArtifact RPCs were removed from spec/spec.proto in v0.13.0 (see lib commit 815acac); they are no longer recognised by the com.kcl.api.API dispatcher. If you previously called api.buildProgram(...) or api.execArtifact(...), switch to api.execProgram(...).