Code Workflows
Define a whole workflow in code - the Java, JavaScript and Python contracts, the task context, typed authoring, editing in ByteChef and deploying through the API.
A code workflow is a workflow defined entirely in code. You write a project in Java, JavaScript or Python, and ByteChef runs its workflows on the same execution engine and with the same execution history as a workflow built on the canvas. Only the authoring and the lifecycle differ.
Enterprise Edition only
Code workflows require an Enterprise Edition deployment (bytechef.edition=EE).
When to use one
- The logic is easier to express and review as code than as a node graph, for example heavy branching, data structures or algorithms.
- Workflows must live in Git, be reviewed in pull requests and ship through CI.
- You generate workflows programmatically.
For a comparison with the canvas and the Script step, see Build approaches.
The same contract also builds two embedded artifacts: catalog code projects, which your connected users run by reference, and code integrations. This page describes the contract; those pages describe what is specific to each.
Languages
The language is taken from the uploaded file's extension.
| Language | Artifact | Extension | Edit in ByteChef |
|---|---|---|---|
| Java | jar | .jar | No - upload only |
| JavaScript | script file | .js | Yes |
| Python | script file | .py | Yes |
JavaScript and Python run on the GraalVM polyglot runtime - the same runtime behind the Script component. Anything else is rejected as an unsupported language. An administrator can turn off Java uploads; see Restricting Java code workflows.
Sample projects
Every combination has a sample repository with a working project, a local check that evaluates the file the way the server does, and deploy instructions. Start from one of them: clone it, run its check, and deploy the file it names. Sample Repositories lists every ByteChef sample.
| Java | JavaScript | Python | |
|---|---|---|---|
| Automation project | java | javascript | python |
| Embedded catalog project | java | javascript | python |
| Embedded code integration | java | javascript | python |
The three automation project samples define the same project, named "Sample Code Project JavaScript", "Sample Code Project Python" or "Sample Code Project Java", with five workflows:
sampleWorkflow1takes a requirednameinput and returnsHello, <name>!as itsgreetingoutput.summarizeNewEmailstarts with the Gmail New Email polling trigger (googleMail/v1/newEmailPolling) and returns a one-line summary of each new email.fetchRecentEmailstakes an optionalfrominput and calls the Gmail Search Email action through a declaredgmailconnection.notifySlackOnNewEmailposts each new email to Slack through a declaredslackconnection. Itschannelinput takes its options from Slack's ownchannelinput.listOrdersstarts with the API Platform New API Request trigger. ItsfetchOrderstask returns a list of orders, and itsrespondcomponent task answers the API caller with them.
To check a sample locally and find the file to deploy:
| Sample | Local check | File to deploy |
|---|---|---|
| JavaScript | npm run check | src/sample_code_project.js |
| Python | python3 scripts/check.py src/sample_code_project.py name=Ada | src/sample_code_project.py |
| Java | ./gradlew build (JDK 25) | build/libs/sample-code-project-java-1.0.0.jar |
The JavaScript and Python checks evaluate the file the way the server does, check its shape and run each task once against a stub context that stands in for Gmail. They need only Node.js or Python 3.9 or later; there is nothing to install. Deploy the file from Automation → Projects (see Creating and editing in ByteChef) or through the deploy endpoint:
curl -X POST "$BYTECHEF_URL/api/automation/v1/projects/deploy?workspaceId=1" \
-H "Authorization: Bearer $BYTECHEF_API_KEY" \
-H "X-ENVIRONMENT: DEVELOPMENT" \
-F "projectFile=@src/sample_code_project.js"The script contract
A JavaScript or Python code workflow is a single file. ByteChef evaluates it and reads the value it evaluates to:
- JavaScript: the file is one parenthesized object expression,
({ ... }). Keep it a bare expression - a bundler or a module wrapper (export,module.exports) hides the object from the server. - Python: the file's last expression is the definition. Define your
performfunctions withdef, build the definition as adict, and end the file with the variable on a line of its own. An object with the same members as attributes (atypes.SimpleNamespace) works too.
ByteChef re-evaluates the file for every task run, so top-level code should only build the definition.
Project
| Member | Type | Required | |
|---|---|---|---|
name | string | Yes | The project's identity. Deploying again under the same name updates the project; a name already used by a visual project is refused. |
version | string | No | Defaults to 0.0.1. |
description | string | No | |
workflows | list of workflows | No |
A code integration is identified by componentName (string) and
componentVersion (integer), both required, and takes an optional name as its display name.
Workflow
| Member | Type | Required | |
|---|---|---|---|
name | string | Yes | Unique within the project. |
label | string | No | Shown in the UI. |
description | string | No | |
inputs | list of inputs | No | See Inputs, outputs and triggers. |
outputs | list of outputs | No | |
triggers | list of triggers | No | |
tasks | list of tasks and groups | No | Run in order. See Running tasks concurrently for groups. |
Task
| Member | Type | Required | |
|---|---|---|---|
name | string | Yes | Unique across the workflow, nesting included: the engine keys the task's output by it. |
perform | function | Yes, unless the task is a component task | Called with (input, context) or (input, connection, context) when the task runs; see The task context. Its return value is the task's output. |
label | string | No | |
description | string | No | |
connections | list or map | No | See Declaring connections. Not allowed on a component task. |
type | string | No | parallel or forkJoin for a group, or <component>/v<version>/<action> for a component task. |
parameters | map | No | A component task's action inputs. |
A complete example
The sampleWorkflow1 workflow of the automation project samples, with the project's other three
workflows left out. It takes a name input, runs one task and returns its result as the greeting output:
({
name: "Sample Code Project JavaScript",
version: "1",
description: "Sample code project description.",
workflows: [
{
name: "sampleWorkflow1",
label: "Sample workflow 1",
description: "Greets the name it is given.",
inputs: [{name: "name", label: "Name", type: "STRING", required: true}],
outputs: [{name: "greeting", task: "greet"}],
tasks: [
{
name: "greet",
label: "Greet",
description: "Builds a greeting from the name input.",
perform: function (input, context) {
const name = input.name;
context.log("info", "Greeting " + name);
return "Hello, " + name + "!";
}
}
]
}
]
})The Python file imports the type definitions only under TYPE_CHECKING, so the server, which skips
that block, never needs them. The Java classes use static imports from ProjectDsl and WorkflowDsl; see the
Java sample for the full sources.
The task context
perform takes (input, context), or (input, connection, context) when it declares three required parameters - the
same model as the Script component. ByteChef counts the parameters a JavaScript
function declares (perform.length) and the parameters without a default a Python function declares; a Java task picks
the form through the lambda it passes.
inputholds the workflow's inputs plus the output of every task that already ran, keyed by name. A workflow input and a task output sit side by side at the top level, each under its own name - including names a${...}reference could never reach, likemy-task-1, which you read asinput["my-task-1"]. The snapshot is taken when the task is dispatched, so it does not change while the task runs, and a task that has not run yet is simply absent from it.connectionmaps each connection the task declares, by its declared name, to that connection's parameters, for when you build a request yourself rather than through a component action: a region, tenant or account id, a base URL. The map carries the connection's credentials too, so treat it as sensitive. Only the three-parameter form receives it.context.component.<componentName>.<actionName>(input, connectionName, clusterElements)invokes any built-in component action.inputis the action's input parameters;connectionName(optional) names one of the task's declared connections. A name with no wired connection, on an action that requires one, fails with an error naming the connection.clusterElements(optional) wires an action that reads cluster elements - an AI agent's chat above all; see Calling an AI agent.context.log(level, message)writes to the task's execution log. A script names the level as a string ("trace","debug","info","warn","error", case-insensitive), and anything else fails rather than being logged at a level you did not ask for. Java tasks pass theTaskContext.LogLevelenum.
perform: function (input, connection, context) {
const previous = input["fetch_customer"];
const accountId = connection["my_connection"].accountId;
const response = context.component.httpClient.get(
{uri: "https://api.example.com/accounts/" + accountId + "/customers/" + input.customerId + "/items"},
"my_connection");
context.log("info", "fetched " + response.body.length + " items for " + previous.name);
return response.body;
}A task that reads no connection parameters declares two: perform(input, context).
Inputs, outputs and triggers
A workflow can declare what it accepts, what it returns, and what starts it:
{
name: "orders",
inputs: [{name: "orderId", label: "Order ID", type: "STRING", required: true}],
outputs: [{name: "customer", task: "fetch_customer"}, {name: "ok", value: true}],
triggers: [{name: "daily", type: "schedule/v1/interval", parameters: {interval: 1, unit: "DAY"}}],
tasks: [ /* ... */ ]
}Inputs are what test configuration prompts for and what a caller passes. An input has a name, an optional
label, a type (STRING by default; also BOOLEAN, DATE, DATE_TIME, INTEGER, NUMBER, TIME and, in
embedded, FIELD_MAPPING) and required. At run time each arrives in perform's input under its own name, in the
same namespace as the task outputs - so an input and a task cannot share a name.
An input can also take its options from an input a component declares, so whoever fills it in picks from a list
instead of typing - Slack's channel, for example, lists the workspace's channels. Set componentName,
componentVersion and groupName together; a partial reference fails the deploy:
inputs: [
{
name: "channel", label: "Slack Channel", type: "STRING", required: true,
componentName: "slack", componentVersion: 1, groupName: "channel"
}
]The deployment dialog and an embedded integration's instance configuration and connect dialog list the options, loaded through the connection picked for that component.
Outputs are evaluated when the workflow completes and become its result - the body a synchronous caller receives,
and what a workflow-execution read reports for an asynchronous run. An entry names either a task, whose output
becomes the value, or a literal or ${...} expression value. Prefer task for a task output: a task name here is
free-form, and a hyphenated one cannot be written as a ${...} reference at all.
Triggers are not code - a trigger names a component trigger the platform already provides
(schedule/v1/interval, workflow/v1/newWorkflowCall, a webhook) with its parameters, so a code workflow starts
exactly the way a visually built one does. Without one, it runs only when something calls it.
Running tasks concurrently
Tasks run in order by default. To run independent work at the same time, group it: a parallel group dispatches its
tasks all at once, and a forkJoin group runs each branch concurrently while the tasks within a branch stay in order.
tasks: [
{name: "fetch_order", perform: (input, context) => /* ... */},
{
name: "enrich",
type: "parallel",
tasks: [
{name: "fetch_customer", perform: (input, context) => /* ... */},
{name: "fetch_inventory", perform: (input, context) => /* ... */}
]
},
{
name: "notify",
type: "forkJoin",
branches: [
[{name: "post_slack", perform: /* ... */}, {name: "record_slack", perform: /* ... */}],
[{name: "send_email", perform: /* ... */}]
]
},
{name: "summarize", perform: (input, context) => input["fetch_customer"]}
]A parallel group's tasks cannot read each other. They start together, so a sibling has not produced anything yet
and its name is absent from input. Whatever they need must come from before the group; a
task after the group reads all of their outputs normally. Tasks within one fork/join branch do run in sequence, so
they can read each other.
Two more rules, both checked when the source is saved or uploaded rather than when it runs: task names are flat and
must be unique across the whole workflow, nesting included, and a group cannot contain another group (a
component task inside a group is fine). A group has no
perform of its own, and its type is either parallel or forkJoin (fork-join and fork_join are accepted too).
Concurrency has to come from these groups rather than from threads inside a perform - script tasks run in a strict
sandbox with thread creation off, and work a task spawns itself would be invisible to the engine.
Component tasks
A task can also run a component action directly, the same way the task runs in a visual workflow. Give it a type
that names the action as <component>/v<version>/<action> and the action's inputs as parameters, instead of a
perform:
{
name: "respond",
type: "apiPlatform/v1/responseToAPIRequest",
parameters: {responseType: "SUCCESS", response: {success: "${fetch_orders}"}}
}- Parameters are passed as written. A string value may hold a
${...}expression, which the engine evaluates when the task runs, exactly as in a visual workflow:${fetch_orders}is the output of the task namedfetch_orders, and a workflow input is read by its name. A task whose output you reference this way needs a name that is a valid identifier, such asfetch_ordersrather thanfetch-orders. - No
performand noconnections. The task's connection is its component's, supplied by the deployment the same way as for that task in a visual workflow; a deploy withenable=trueleaves the workflow disabled while a required connection is missing. - Anywhere a task can stand. A component task may sit at the top level or inside a
parallelgroup or aforkJoinbranch. Its name counts toward the unique task names. - Checked when the source is saved or deployed. A malformed
type, a component or component version the instance doesn't have, or an action the component doesn't have rejects the save with a message naming the task.
Component task or context.component? Inside a perform, context.component.<component>.<action>(...) calls an
action as part of your own logic, and its result is yours to shape. A component task is a step of its own: the engine
runs it, shows it in the execution, and evaluates its parameters. Use one where a step must be a real workflow task,
such as the response of an API endpoint.
An API endpoint in code
An API Platform endpoint serves a workflow that starts with an
apiPlatform/v1/newApiRequest trigger. Write the logic as perform tasks and answer the caller with an
apiPlatform/v1/responseToAPIRequest component task. Its responseType picks the status (SUCCESS answers 200,
INVALID_INPUT 400, INTERNAL_ERROR 500, FORBIDDEN 403), and response holds the body under the matching key
(success, invalidInput, internalError or forbidden):
({
name: "orders-api",
workflows: [
{
name: "list_orders",
triggers: [{name: "request", type: "apiPlatform/v1/newApiRequest", parameters: {request: {}}}],
tasks: [
{
name: "fetch_orders",
connections: [{componentName: "httpClient", name: "orders_api"}],
perform: (input, connection, context) =>
context.component.httpClient.get({uri: "https://api.example.com/orders"}, "orders_api")
},
{
name: "respond",
type: "apiPlatform/v1/responseToAPIRequest",
parameters: {responseType: "SUCCESS", response: {success: "${fetch_orders}"}}
}
]
}
]
})Compile the TypeScript file with tsc and deploy the emitted .js; see Typed authoring. Then add
the deployed workflow to an API collection as an endpoint, as you would a visual one.
Declaring connections
A task declares the connections its perform uses, making the requirement readable from the generated workflow definition and validated at save and deploy time (a declared name with no matching connection logs a warning):
{
name: "my_task",
connections: [
{componentName: "httpClient", name: "billing_api"},
{componentName: "slack", componentVersion: 1, name: "slack_prod"}
],
perform: function (input, connection, context) { /* ... */ }
}A map keyed by connection name is accepted too, if you prefer it:
connections: {
"billing_api": {componentName: "httpClient"},
"slack_prod": {componentName: "slack", componentVersion: 1}
}The declared name is the same value the perform passes as connectionName, and the key under which a
three-parameter perform finds the connection's parameters in connection, for example connection["billing_api"].
Declaring a connection makes it appear
wherever the platform asks you to wire connections - the Test Configuration dialog in the editor and the
deployment's connection step - so each environment picks its own credentials, exactly like a visual workflow's nodes.
A connectionName that was never declared and wired cannot resolve, so the call fails at run time.
componentVersion is optional and pins to the component's latest version at save time.
In an embedded code integration, a call to the integration's
own component needs neither: ByteChef declares that connection on every code task under the component's name, so
context.component.googleMail.searchEmail({maxResults: 10}) works without a connection name. Declare only connections
to other components.
Calling an AI agent
Some actions read more than input and a connection. The AI Agent's chat resolves its model, tools, memory and RAG
from cluster elements - on a canvas those are the nodes you drag onto the agent. A code workflow has no such node,
so it composes them as a third argument to the call:
{
name: "ask_agents",
connections: [
{componentName: "openAi", name: "openai_prod"},
{componentName: "anthropic", name: "anthropic_prod"},
{componentName: "slack", name: "slack_prod"}
],
perform: function (input, context) {
const draft = context.component.aiAgent.chat({messages: [{role: "user", content: "Draft a reply"}]}, null, {
model: {type: "openAi/v1/model", connection: "openai_prod", parameters: {model: "gpt-4o"}},
tools: [{type: "slack/v1/sendMessage", connection: "slack_prod", name: "post_to_slack"}]
});
return context.component.aiAgent.chat({messages: [{role: "user", content: "Review: " + draft}]}, null, {
model: {type: "anthropic/v1/model", connection: "anthropic_prod",
parameters: {model: "claude-sonnet-5"}}
});
}
}Elements go on the call rather than on the task because a code task orchestrates: the example above drafts with one model and reviews with another, and declaring one element set per task would force each of those into its own task - which is the opposite of why you wrote the orchestration as code.
The map is keyed by cluster element type (model, tools, chatMemory, rag, ...). A type that takes several
elements takes a list. Each element is:
| Member | ||
|---|---|---|
type | required | <componentName>/v<version>/<elementName>, e.g. openAi/v1/model |
connection | optional | names one of the task's declared connections |
name | optional | for a tool, what the model calls it; defaults to the element name in type |
parameters | optional | the element's own parameters |
What you cannot write here is a connection. An element names one the task declared, so credentials stay wired by the
user per environment exactly as for any other task, and a name the task never declared fails the call. Naming a tool
matters more in code than on a canvas: the list is written by hand, and without a name the model sees the
platform's generated SLACK_SendMessage.
Java tasks compose the same thing through the SDK, which builds the identical structure:
WorkflowDsl.task("ask_agent")
.connections(connection("openAi", "openai_prod"), connection("slack", "slack_prod"))
.perform((input, context) -> context.component(
"aiAgent", "chat", Map.of("messages", messages), null,
clusterElements()
.element(
"model",
clusterElement("openAi/v1/model")
.connection("openai_prod")
.parameter("model", "gpt-4o"))
.elements(
"tools",
clusterElement("slack/v1/sendMessage")
.connection("slack_prod")
.name("post_to_slack"))));Nothing about an element is checked when you save. Elements are written in code rather than declared, so a wrong type or a misspelled parameter surfaces when the task runs, not before - only the connection reference can be checked, and only at call time. For the same reason the composition is invisible to the platform: no definition records which model a task uses, so nothing can report or govern it the way it can for a visual agent node.
Composing elements is supported in code workflow tasks only. The Script component shares the same
context.component surface, but a script task declares no connections for an element to name, so passing elements
there fails with an error saying so.
Running a step on a task runner
A JavaScript or Python code workflow's tasks run inside ByteChef, in the same sandbox as a script: no native libraries, no filesystem, and a CPU time and memory limit. When one step needs more - pandas or numpy, an npm package, or a long computation that shouldn't hold a worker - hand just that step to the Script component and run it on a task runner: a local process or a Docker container. The task around it stays where it is and keeps calling components and reading connections as usual.
{
name: "summarize",
perform: function (input, context) {
const result = context.component.script.python({
script: "import pandas as pd\n\ndef perform(input, context):\n frame = pd.DataFrame(input['rows'])\n return frame.describe().to_dict()\n",
input: {rows: input.fetchRows},
taskRunner: {type: "docker", image: "registry.example.com/python-pandas:3.12"}
});
return result.vars;
}
}taskRunner.type picks the runner:
| Type | Runs the script | Notes |
|---|---|---|
graalvm | Inside ByteChef | The default when taskRunner is omitted. Same sandbox as the task itself. |
process | As a child process on the ByteChef host | Uses the host's python3 or node, with whatever packages it has installed. |
docker | In a container | image defaults to python:3.12-slim or node:22-alpine; name your own image for extra packages. |
The Enterprise kubernetes and aws-batch runners take their cluster or account from a connection named
taskRunner. A visual Script node gets it added when the workflow is saved; in code, declare it on the task - a
kubernetes connection for kubernetes, an aws connection for aws-batch - and bind it like any other connection.
It is never handed to the script.
{
name: "summarize",
connections: [{name: "taskRunner", componentName: "kubernetes", componentVersion: 1}],
perform: function (input, context) {
return context.component.script.python({
script: "...",
input: {rows: input.fetchRows},
taskRunner: {type: "kubernetes", image: "registry.example.com/python-pandas:3.12"}
}).vars;
}
}On process and docker the call returns the run, not just the value: vars holds what the script's perform
returned, alongside exitCode, stdout, stderr and outputFiles. On graalvm it returns the value itself.
Things to know:
-
The script on the runner can't call back.
context.componentand every other context member throw "is not available under the … runner" there. Fetch data and call components in the task, pass what the script needs ininput, and act on its result in the task. -
The task's connections go with it. With
bytechef.script.inject-connectionson (as in the shipped configuration), every connection the task declares excepttaskRunneris written to aconnections.jsonfile beside the script's input, as a map from connection name to parameters - the same shape agraalvmscript gets. Declare the script'sperformwith three parameters to receive it:perform(input, connection, context), then readconnection["name"]["param"]. Aperform(input, context)keeps working and gets no connections. The values are never environment variables;BYTECHEF_CONNECTIONS_FILEnames the file for a shell script or the Commands component, and the values are masked instdout,stderrand the logs (not invarsor output files). That is every connection the task declares, not only the ones the step uses, so keep runner steps in tasks that declare only what they need. Theprocessrunner withholds the server's own environment unless the operator allowsinheritEnvironment.def perform(input, connection, context): token = connection["github"]["accessToken"] return {"authorized": bool(token)} -
The operator decides. Out-of-process runners are off until enabled with
bytechef.script.runners.<type>.enabled: true(for exampleBYTECHEF_SCRIPT_RUNNERS_DOCKER_ENABLED=true), and choosing a disabled runner fails the task. Enablingdockerlets workflow authors run any image with any user, so turn it on only where they are trusted with the Docker host. The Script component reference covers the runners and their result shapes. -
A runner costs start-up time. A container start adds noticeably more latency than an in-process call, so keep runner steps for work that needs them.
Task Runners covers setting the runners up.
Typed authoring
The script contract has type definitions for TypeScript and Python, so an editor or a type checker catches a missing
name, a misspelled perform or an unknown input type before you deploy, and types the arguments of every
perform. Both packages carry types only: ByteChef evaluates the file as a plain script, so nothing they add
survives to runtime. Both describe projects (ProjectDefinition) and code integrations (IntegrationDefinition).
Install the type packages from source
@bytechef/workflow-api and bytechef-workflow-api are not published to npm or PyPI yet, so installing them by
name fails, and so do the samples' npm install, npm run check:ts and pip install -r requirements-dev.txt
steps. Their sources live in the ByteChef repository, under
sdks/backend/typescript/workflow-api
and sdks/backend/python/workflow-api.
Until they are published, install them from a ByteChef checkout, as below. The samples' plain npm run check
and python3 scripts/check.py checks need neither package.
# TypeScript: build the package, then add it to your project as a dev dependency
npm --prefix <bytechef>/sdks/backend/typescript/workflow-api install
npm --prefix <bytechef>/sdks/backend/typescript/workflow-api run build
npm install --save-dev <bytechef>/sdks/backend/typescript/workflow-api
# Python
pip install <bytechef>/sdks/backend/python/workflow-api mypyTypeScript - add @bytechef/workflow-api
as a dev dependency, reference it with a triple-slash directive and check the project with satisfies. A code
workflow file can't import anything, so the types live in the global ByteChef namespace:
/// <reference types="@bytechef/workflow-api" />
({
name: "orders",
version: "1.0.0",
workflows: [
{
name: "sync_orders",
inputs: [{name: "customerId", label: "Customer ID", type: "STRING", required: true}],
outputs: [{name: "orders", task: "fetch_orders"}],
tasks: [
{
name: "fetch_orders",
connections: [{componentName: "httpClient", name: "orders_api"}],
perform: (input, connection, context) =>
context.component.httpClient.get(
{uri: "https://api.example.com/customers/" + input.customerId + "/orders"},
"orders_api")
}
]
}
]
}) satisfies ByteChef.ProjectDefinition;Compile the file with tsc and deploy the emitted .js file. satisfies and the directive leave nothing behind, so
the output is the plain object expression ByteChef expects. Don't import or export anything in the .ts file:
either one turns it into a module, and the output stops being a bare expression. Plain JavaScript files get the same
checks through // @ts-check and a JSDoc @type {ByteChef.ProjectDefinition} annotation.
A three-parameter perform is typed without annotations. TypeScript can't infer a two-parameter perform from the
union of both forms, so annotate its parameters: (input: ByteChef.TaskInput, context: ByteChef.TaskContext) => ....
Each JavaScript sample carries a TypeScript version of its project next to the .js file, for example
src/sample_code_project.ts in the automation sample. npm run check:ts compiles it to dist/ and runs the same check
on the output; deploy the .js file from dist/. The TypeScript project has a name of its own ("Sample Code Project
TypeScript"), so deploying it creates a second project next to the JavaScript one.
Python - install bytechef-workflow-api
where your type checker runs (mypy, Pyright) and import it under TYPE_CHECKING, since the ByteChef runtime can't
import it. Standard-library imports are fine in a code workflow; nothing else is available on the server:
from typing import TYPE_CHECKING, Any, Dict
if TYPE_CHECKING:
from bytechef_workflow_api import ProjectDefinition, TaskContext
def fetch_orders(input: Dict[str, Any], context: "TaskContext") -> Any:
return context.component.httpClient.get(
{"uri": "https://api.example.com/customers/" + input["customerId"] + "/orders"}, "orders_api"
)
project: "ProjectDefinition" = {
"name": "orders",
"version": "1.0.0",
"workflows": [
{
"name": "sync_orders",
"inputs": [{"name": "customerId", "label": "Customer ID", "type": "STRING", "required": True}],
"outputs": [{"name": "orders", "task": "fetch_orders"}],
"tasks": [
{
"name": "fetch_orders",
"connections": [{"componentName": "httpClient", "name": "orders_api"}],
"perform": fetch_orders,
}
],
}
],
}
projectThe types follow the definition as a dict; a SimpleNamespace definition loads too, but a type checker can't check
it. The Python samples are annotated this way; type check one with mypy --strict src scripts.
The Java contract
A Java code workflow is a jar containing a ProjectHandler implementation, discovered through the standard Java
ServiceLoader mechanism - so the jar must carry a META-INF/services/com.bytechef.automation.project.ProjectHandler
entry naming your class, whether you write that file yourself or generate it (Google's @AutoService is the usual
way). The handler returns a ProjectDefinition, which the ProjectDsl and WorkflowDsl builders assemble - see
A complete example. A task's perform is a lambda taking (input, context) or
(input, connection, context): input and connection are Map<String, ?>, and context is the SDK's
TaskContext, the Java side of the task context, with component(...) and log(...).
ProjectHandler, ProjectDefinition, WorkflowDsl and TaskContext come from the ByteChef backend SDK
(sdks/backend/java/automation/project-api and sdks/backend/java/workflow-api) - compile the jar against those and
nothing else from the platform. A code integration implements IntegrationHandler from
sdks/backend/java/embedded/integration-api instead.
Each loaded jar gets its own isolating class loader, so two code workflows can depend on different versions of the
same library without colliding. Only com.bytechef.* and the packages of the JDK's runtime modules (java.*, most of jdk.*,
and JDK packages such as javax.net.ssl and org.w3c.dom) come from the server; bundle every other dependency in
the jar. The JDK's tool modules, such as the compiler and attach APIs, are not available.
Creating and editing in ByteChef
JavaScript and Python code workflows can be created and edited directly in ByteChef, without a separate build and upload step. On an Enterprise Edition deployment, the arrow next to New Project on Automation → Projects opens a menu with New Project, From Template, Import Project, New Code Project and Import Code Project. The Community Edition menu has no code project items:
- New Code Project opens a dialog that asks for a Language (JavaScript or Python), a Project Name, and an optional Description, Category and Tags. ByteChef creates the project as a draft from a starter source and opens it in the code editor. The name must not already be used in the workspace and must not contain quotes, backslashes or line breaks.
- Import Code Project uploads a
.js,.pyor.jarfile and publishes it, like the deploy endpoint withoutenable: existing deployments stay on the version they run. The dialog offers.jaronly while Java uploads are allowed.
A code project's row shows a language badge, and its workflow rows list the components its tasks declare connections to. The actions that change a project's workflow structure, such as New Workflow, are hidden for a code project: its workflows come from the source.
A code project opens a source editor in place of the visual canvas. Saves are checked before they are stored -
source that fails to load is rejected with the loader's error and the draft stays as it was. The name declared in
the code and the project's name stay in sync: change the name in the source and saving renames the project, unless
another project already uses that name; rename the project and the name in the draft source is rewritten to match. A
Java code workflow takes its name from its JAR, so rename it there and upload the JAR again.
Restoring a version from the project's version history restores that version's source into the draft, under the project's current name.
Editor saves update the project's draft only: deployments keep running the last published version until you publish from the project header, exactly like visual workflows. Iterating on a draft is safe - a workflow keeps its identity across saves and publishes as long as its name doesn't change, so test configurations and connections carry over. A workflow removed from the source and later added back under the same name gets its old identity back.
Java code workflows are uploaded only; the editor does not open them.
Autocomplete in the source editor
The source editor suggests names as you type inside a task's perform: the context members, every component
under context.component and its actions, the action's property keys and option values inside the call's first
argument, the workflow's inputs and earlier task names after input., and the declared connections after
connection. in the three-parameter form. Picking an action inserts the
call with the task's declared connection name already in place, and options and dynamic properties that need a
connection use the one selected in Test Configuration. The Script step's editor described under
Editing and running a script completes context.component calls the same way,
plus the step's input keys and connection names. See
Code Editor Autocomplete for examples in each
language, and try them on a sample project.
Deploying through the API
Code workflows also deploy programmatically; the natural home is your CI pipeline - build the artifact, then push it through the deploy endpoint:
POST /api/automation/v1/projects/deployA multipart/form-data request:
| Parameter | |
|---|---|
projectFile (file part) | Required. The .jar, .js or .py file. The file name's extension picks the language. |
workspaceId | Required. The workspace the project belongs to. Send it as a query parameter or as a form field. |
enable (query parameter) | Optional, false by default. See below. |
X-ENVIRONMENT (header) | Optional. DEVELOPMENT, STAGING or PRODUCTION (case-insensitive); PRODUCTION when absent. |
It is part of the public Projects API. Authenticate with
Authorization: Bearer <API key>, using a workspace API key (Settings → Current Workspace → API Keys) that
belongs to an administrator - deploying requires the admin role. Only an automation workspace key is accepted: an
Embedded API key is rejected. The key is looked up in the environment named by the X-ENVIRONMENT header, so send the
environment the key was created in; the same header picks the environment enable acts on.
curl -X POST "$BYTECHEF_URL/api/automation/v1/projects/deploy?workspaceId=1&enable=true" \
-H "Authorization: Bearer $BYTECHEF_API_KEY" \
-H "X-ENVIRONMENT: DEVELOPMENT" \
-F "projectFile=@src/sample_code_project.py"What the endpoint does:
- It saves and publishes. The upload is saved as the project's draft and published in the same call, so the deployed version becomes the published one. An upload replaces any unpublished editor changes.
- It upserts by name. The project is matched on the
namein the definition within the workspace. The first deploy creates the project; every deploy after that publishes a new version of it, and each workflow keeps its identity by name. A deploy whose name matches a visual project (one not created from code) is refused with a name clash and changes nothing; rename the project in the source or the visual project, then deploy again. The caller must also be allowed to edit and publish the matched project. - Without
enable, deployments don't move. Existing deployments keep running the version they are on until you move them in the UI. enable=truemakes it live in the request's environment. When the project has no deployment there, ByteChef creates one at the published version and enables it; otherwise it moves the existing deployment to the published version and enables it if it was disabled.
With enable=true, a workflow that can't run without configuration is added to the deployment but left disabled:
one that declares a required input, or whose trigger or tasks need a connection. Every other workflow is enabled,
and so is the deployment. Open the deployment, set the input values and pick the connections for those workflows,
then enable them. On a move to a new version this applies to workflows the version adds; workflows that were already
deployed keep their enabled state, their input values and their connections. In the
automation samples, sampleWorkflow1 (required name input) and the three Gmail workflows
(Gmail trigger or connection, plus Slack for notifySlackOnNewEmail) all wait for configuration this way.
Responses:
| Status | When |
|---|---|
204 No Content | The project was saved and published, and enabled when enable=true. |
400 Bad Request | The file is missing or fails to load, its language is unsupported or Java uploads are disabled, or a required parameter is missing. The body names the reason. |
401 Unauthorized | The API key is unknown in that environment, is not a workspace API key, or X-ENVIRONMENT is not a valid environment. |
403 Forbidden | The key's user is not an administrator. |
A second endpoint, POST /api/automation/v1/projects/{id}/git/pull, pulls a project from its configured Git
repository instead of taking an upload.
Restricting Java code workflows
A Java code workflow runs in-process. Administrators who don't want that can turn off Java uploads with
BYTECHEF_WORKFLOW_CODE_WORKFLOW_JAVA_ENABLED=false (default true): new Java uploads are rejected on every path -
automation projects, catalog code projects and code integrations - while JavaScript and Python uploads and
previously uploaded Java artifacts keep working.
Scripting languages
When a single step needs a transformation that no component provides, for example reshaping a payload, computing a value or parsing an unusual format, add the Script component to the workflow. The script runs as one step of a visual workflow, without a separate toolchain or deploy step.
Two languages, one runtime
The Script component has two actions:
| Action | Typical use |
|---|---|
| JavaScript | The default for most scripting; convenient JSON handling, familiar syntax. |
| Python | Data manipulation and transformations where the Python idiom is cleaner. |
Both run on GraalVM, so the platform needs no per-language toolchain installed alongside it.
Each action's entry point is a perform function taking the step's input and a context:
function perform(input, context) {
return input.items.filter((item) => item.active);
}Calling a component from a script
context.component.<componentName>.<actionName>(input) runs a built-in component action from the
script. Connections are configured in the script editor, not in code: open the code editor, add the
component, name the connection and select the credential. If a component has more than one connection,
pass the connection name as the second argument:
function perform(input, context) {
context.component.googleMaps.getAddress({latitude: 12.5, longitude: 45.8}, "googleMaps2");
return null;
}See the Script component reference for the full walkthrough.
A Script step runs inside the server by default. Its Task Runner property can send it to a child process, a Docker container, a Kubernetes pod or an AWS Batch job instead, with input files, output files and environment variables; see Task runners.
Beyond a plain step
The Script component also provides cluster elements in JavaScript and Python: tools, which an AI agent calls like any other tool, and processors for data streams.
Editing and running a script
Open the script property full-screen to edit it in a code editor with syntax highlighting for the action's language. Run executes the script against the step input and shows the result. A side panel lists the step input data and the component connections the script can use. The script is saved with the workflow.
Limits
Scripts, and the tasks of a JavaScript or Python code workflow, execute in a GraalVM guest context with no host class access, no filesystem access, no environment access, no subprocess execution and no thread creation. Concurrency inside a script is therefore not available - use the workflow's own flow controls, or a code workflow's task groups, to parallelize.
The guest context also runs inside a resource sandbox, on by default. Each execution gets a CPU time limit (5
minutes by default) and a heap memory limit (512 MB by default), and the number of guest executions that run at once is
capped; an execution that passes a limit is stopped and its task fails. Operators tune these under
bytechef.script.sandbox (max-cpu-time, max-heap-memory, max-concurrent-executions, enabled); see
Script Sandbox. On a JVM that can't enforce the heap
limit, the server logs a warning and only the CPU limit applies.
For work the sandbox doesn't allow - native libraries, packages from npm or PyPI, long computations - run the step on a task runner instead: a local process or a container. See Running a step on a task runner.
JavaScript and Python custom components run in the same sandbox as a script; a Java custom component runs in-process, outside it.
Script or custom component?
| Use a script when | Use a custom component when |
|---|---|
| The logic is small and used in one place. | The logic is reused across workflows. |
| The logic is one-off. | The logic needs its own typed schema. |
| You are iterating. | Others depend on the behavior. |
A common progression: prototype in a script, promote it to a custom component once it stabilizes. Make that call for reuse and schema. When a step needs more CPU, memory or packages than the sandbox allows, the answer is a task runner, not a custom component.
One cost worth knowing about: every script execution builds a fresh guest context and re-evaluates the source, so a script step pays a small start-up cost on each run that a Java custom component, loaded once, does not. A JavaScript or Python custom component re-evaluates its source on every call too. For most workflows the difference is invisible.
Not yet available
Copilot
The AI Copilot and the AI Hub don't know about code workflows yet: there is no code-workflow-aware assistant in the code editor and no AI Hub specialist that creates or edits a code workflow. Write the source yourself, starting from a sample.
How is this guide?
Last updated on
Build Approaches
Choose how you build automations in ByteChef - no-code on the visual canvas, low-code with a Script step, or full-code as a Code Workflow - all running on the same engine.
Task Runners
Choose where Script and Commands tasks run - in the server's GraalVM sandbox, in a child process, in a Docker container, on Kubernetes or on AWS Batch - and how input files, output files, environment variables, timeouts and connections reach the code.