# Code Runner — Run Python & JavaScript with Input Data (`actor-forge/code-runner-sandbox`) Actor

Run Python 3.12 or JavaScript (Node 22) code in a sandboxed run: pass JSON input or dataset rows, install pip/npm packages, get stdout, stderr, exit code and returned rows. For data pipelines and AI agents (MCP). $0.0003 per execution plus run time.

- **URL**: https://apify.com/actor-forge/code-runner-sandbox.md
- **Developed by:** [ActorForge](https://apify.com/actor-forge) (community)
- **Categories:** Developer tools, AI, Automation
- **Features:** Limited permissions
- **Stats:** 7 total users, 6 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.30 / 1,000 code executeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Code Runner — Run Python & JavaScript with Input Data

Run Python 3.12 or JavaScript (Node 22) code in a sandboxed run: pass JSON input or dataset rows, install pip/npm packages, get stdout, stderr, exit code and returned rows. For data pipelines and AI agents (MCP). $0.0003 per execution plus run time.

**Run a Python or JavaScript snippet on Apify and get its output back as data: no server, no Lambda, no notebook.** Paste code, pick **Python 3.12** or **JavaScript (Node.js 22)**, pass parameters as **Input JSON** and, optionally, an **Apify dataset** to process. Your code sees them as the variables `input` and `rows`, can **`return` a list that becomes dataset rows** (one per item), and can install **pip or npm packages** (pandas, requests, lodash, dayjs, cheerio…) at runtime. Every run returns **stdout, stderr, exit code, duration and the returned value**, so you always see what happened.

**Built for pipelines and AI agents.** Use it as the "code step" between scrapers: reshape, filter, score, dedupe or enrich a scraper's dataset, compute stats, call an API and reformat the response, then feed the rows to Make, n8n, Zapier, Clay or the next actor. AI agents and MCP clients (Claude, ChatGPT, Cursor and other assistants connected to Apify) can call it as a **code-execution tool**: set `outputMode` to `result-row` and every call returns exactly one row with `status`, `stdout`, `stderr`, `exitCode`, `durationMs` and `result`. Errors never crash the run: you get status `error` with the message, the line number and the traceback (or turn on `failOnError` to fail the run and stop a pipeline).

**Safe by design.** Each execution runs in **your own Apify run**, in a fresh temporary folder that is deleted afterwards. A **hard timeout** kills the code and everything it started, output is capped, and no Apify token or other secret is placed in the code's environment. Packages are restricted to registry names with an optional version (no URLs, git refs or installer options).

### How to use it

**Python** (top-level `return`, a final bare expression, or a variable named `result` all work):

```python
import statistics
prices = [r["price"] for r in rows if r.get("price")]
return [{"count": len(prices), "median": statistics.median(prices), "max": max(prices)}]
```

**JavaScript** (runs as the body of an async function, so top-level `await` and `return` work; use `require()` or `await import()`):

```javascript
const res = await fetch(input.apiUrl, { headers: { accept: 'application/json' } });
const data = await res.json();
return data.items.map((i) => ({ id: i.id, title: i.title.trim() }));
```

- **`input`**: the Input JSON (also sent on stdin). **`rows`**: items of the Input dataset (up to `maxInputRows`). **`push(row)`**: add a row to the output while the code runs.
- **Returned list** → one dataset row per item (non-objects become `{"value": …}`); **any other value** → the `result` field of the result row. The full execution record (stdout, stderr, exit code, billing) is always in the run's `OUTPUT` record.
- **From the API / an agent:** call actor `actor-forge~code-runner-sandbox` with `{"language": "python", "code": "return 6*7", "outputMode": "result-row"}` and read the dataset items of the run.

**Priced for small, frequent executions: $0.0003 per execution** including the first 2 GB-seconds of run time (about 8 seconds at the default 256 MB) and the first 100 rows, then $0.0001 per extra GB-second and $0.01 per 1,000 extra rows. Invalid input, failed package installs and dataset errors are free.

### What data does it return?

Every run outputs clean, schema-validated rows like these:

| name | length | upper |
| --- | --- | --- |
| Ada | 3 | ADA |
| Grace | 5 | GRACE |
| Linus | 5 | LINUS |

### How much does it cost?

Transparent pay-per-event pricing — you only pay for what you get, and the
actor **always respects your run budget**: set a maximum total charge and it
stops cleanly at the cap instead of overrunning.

| Event | Price | Charged | Worked example |
| --- | --- | --- | --- |
| `code-executed` | $0.0003 | per execution of your code (includes the first 2 GB-seconds of run time and the first 100 output rows; invalid input, failed package installs and dataset errors are free) | The prefill example (3 rows, about 3 seconds at 256 MB) = $0.0003 (measured) |
| `compute-second` | $0.0001 | per extra GB-second of run time (seconds × memory in GB) beyond the 2 included | A 60-second job at 256 MB = 15 GB-s − 2 included = 13 × $0.0001 = $0.0013, plus $0.0003 = $0.0016 |
| `row-output` | $0.00001 | per dataset row beyond the first 100 of a run | Transform a 10,000-row dataset in 20 s at 512 MB = $0.0003 + 8 × $0.0001 + 9,900 × $0.00001 ≈ $0.10 |
| `apify-actor-start` | $0.00005 | per run per GB of memory (platform start fee) | One run at 256 MB = $0.00005 |

### Input options

| Field | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `language` | string | no | `"python"` | Language of the code: "python" (Python 3.12) or "javascript" (Node.js 22). Aliases py, python3, js, node are accepted via the API. |
| `code` | string | yes | — | The code to run (up to 1 MB). In scope: `input` (the Input JSON below, also sent on stdin), `rows` (list of rows loaded from the dataset, empty if none) and `push(row)` (adds a row to the output dataset). Return the result with a top-level `return` (Python and JavaScript); in Python a final bare expression or a variable named `result` also works. A returned list/array becomes dataset rows (one per item); any other value is saved in the `result` field. print()/console.log() go to `stdout`. JavaScript runs as the body of an async function: top-level `await` works, use `require()` or `await import()` for modules. |
| `input` | object | no | — | Any JSON object passed to the code as the variable `input` (also written to stdin as JSON). Use it for parameters, API responses or small data sets. |
| `datasetId` | string | no | — | Optional Apify dataset (ID or name) whose items are loaded into the variable `rows`, e.g. the output of a scraper to transform, filter or enrich. Picking it here gives this run read access to that dataset only. |
| `maxInputRows` | integer | no | `10000` | Maximum number of dataset items loaded into `rows` (first N items). |
| `packages` | array | no | — | Optional pip packages (Python) or npm packages (JavaScript) installed before the code runs, e.g. "pandas", "requests==2.32.3", "lodash", "dayjs@1.11.13". Registry names with an optional version only (no URLs or options), at most 15. Installation is limited to 180 seconds and counts as run time. The standard library (json, csv, re, datetime, math, statistics, urllib; Node fetch, fs, crypto) needs no install. |
| `timeoutSecs` | integer | no | `60` | Hard limit for the code's run time. The process and anything it started are killed when it is reached and status "timeout" is returned. It is lowered automatically to fit the run's maximum charge and the run timeout. |
| `outputMode` | string | no | `"auto"` | auto: a returned list (and anything passed to push()) is saved as dataset rows, and stdout/stderr/exit code go to the OUTPUT record; if nothing is returned as a list, the dataset gets one result row. result-row: the dataset always gets exactly one row with status, stdout, stderr, exit code, duration and the returned value in `result` (best for AI agents and MCP clients). |
| `maxOutputRows` | integer | no | `10000` | Maximum number of rows saved to the dataset; extra rows are dropped (and not charged). |
| `failOnError` | boolean | no | `false` | If on, the Apify run ends as FAILED when the code raises an error, exits non-zero or times out (useful to stop a pipeline). If off, the run succeeds and the row has status "error" or "timeout" with the error and stderr. |

### Limits & honest notes

- Runtimes: Python 3.12 (Alpine Linux, musl) and Node.js 22. Most popular pip packages ship compatible wheels (pandas, numpy, requests, beautifulsoup4, pydantic…); packages that must compile C code may fail to install. Installation is limited to 180 seconds and its time counts as run time.
- The default memory is 256 MB, which also means a small CPU share. For pandas/numpy work or large datasets raise the run memory (up to 4 GB); run-time charges scale with memory (GB-seconds).
- Timeout: 1–900 seconds per execution (default 60). It is lowered automatically so the run stays within your maximum charge and the run timeout. On timeout the code and its child processes are killed and status is "timeout".
- stdout and stderr are kept up to 100,000 characters each in the row (1 MB per stream is read; the rest is discarded). A returned value is limited to 200 MB, a single row to 8 MB, and the `result` field to 2 MB of JSON.
- Input dataset: up to 100,000 items are loaded into memory as `rows`. The run can read only the dataset you pick (or pass by ID in the API input).
- The code has normal outbound internet access from the run (for APIs and downloads). It runs as your own Apify run, so anything it does uses your account; do not paste untrusted code you would not run yourself.
- Files written by the code are not kept after the run; return the data (or rows) you need. Python's `input()` is replaced by the `input` variable — read stdin with `sys.stdin` instead.
- Each execution starts a fresh environment: nothing is cached between runs, so packages are reinstalled each time.

### Related ActorForge actors

- [Merge & Deduplicate Datasets](https://apify.com/actor-forge/dataset-merge-dedupe) — merge and dedupe scraper outputs without code
- [HTTP Request Runner](https://apify.com/actor-forge/http-request-runner) — call any REST API in bulk without writing code

### Changelog

- **2026-11-12** — Initial release: Python 3.12 and Node.js 22, Input JSON and dataset rows, pip/npm packages, returned list → dataset rows, push(), result-row mode for AI agents, hard timeouts and output caps.

***

*Built and maintained by **ActorForge**. Reliability first: every actor in the
portfolio is monitored by an automated nightly self-test, and breakages are
typically fixed the same day.*

# Actor input Schema

## `language` (type: `string`):

Language of the code: "python" (Python 3.12) or "javascript" (Node.js 22). Aliases py, python3, js, node are accepted via the API.

## `code` (type: `string`):

The code to run (up to 1 MB). In scope: `input` (the Input JSON below, also sent on stdin), `rows` (list of rows loaded from the dataset, empty if none) and `push(row)` (adds a row to the output dataset). Return the result with a top-level `return` (Python and JavaScript); in Python a final bare expression or a variable named `result` also works. A returned list/array becomes dataset rows (one per item); any other value is saved in the `result` field. print()/console.log() go to `stdout`. JavaScript runs as the body of an async function: top-level `await` works, use `require()` or `await import()` for modules.

## `input` (type: `object`):

Any JSON object passed to the code as the variable `input` (also written to stdin as JSON). Use it for parameters, API responses or small data sets.

## `datasetId` (type: `string`):

Optional Apify dataset (ID or name) whose items are loaded into the variable `rows`, e.g. the output of a scraper to transform, filter or enrich. Picking it here gives this run read access to that dataset only.

## `maxInputRows` (type: `integer`):

Maximum number of dataset items loaded into `rows` (first N items).

## `packages` (type: `array`):

Optional pip packages (Python) or npm packages (JavaScript) installed before the code runs, e.g. "pandas", "requests==2.32.3", "lodash", "dayjs@1.11.13". Registry names with an optional version only (no URLs or options), at most 15. Installation is limited to 180 seconds and counts as run time. The standard library (json, csv, re, datetime, math, statistics, urllib; Node fetch, fs, crypto) needs no install.

## `timeoutSecs` (type: `integer`):

Hard limit for the code's run time. The process and anything it started are killed when it is reached and status "timeout" is returned. It is lowered automatically to fit the run's maximum charge and the run timeout.

## `outputMode` (type: `string`):

auto: a returned list (and anything passed to push()) is saved as dataset rows, and stdout/stderr/exit code go to the OUTPUT record; if nothing is returned as a list, the dataset gets one result row. result-row: the dataset always gets exactly one row with status, stdout, stderr, exit code, duration and the returned value in `result` (best for AI agents and MCP clients).

## `maxOutputRows` (type: `integer`):

Maximum number of rows saved to the dataset; extra rows are dropped (and not charged).

## `failOnError` (type: `boolean`):

If on, the Apify run ends as FAILED when the code raises an error, exits non-zero or times out (useful to stop a pipeline). If off, the run succeeds and the row has status "error" or "timeout" with the error and stderr.

## Actor input object example

```json
{
  "language": "python",
  "code": "# `input` = the Input JSON, `rows` = rows from the dataset (if any).\n# Return a list of dicts -> one dataset row each. print() goes to stdout.\nnames = input.get(\"names\", [\"Ada\", \"Grace\", \"Linus\"])\nprint(f\"Processing {len(names)} names\")\nreturn [{\"name\": n, \"length\": len(n), \"upper\": n.upper()} for n in names]\n",
  "input": {
    "names": [
      "Ada",
      "Grace",
      "Linus"
    ]
  },
  "maxInputRows": 10000,
  "timeoutSecs": 60,
  "outputMode": "auto",
  "maxOutputRows": 10000,
  "failOnError": false
}
```

# Actor output Schema

## `rows` (type: `string`):

Rows returned by the code, or one result row with status, stdout, stderr, exit code, duration and the returned value.

## `execution` (type: `string`):

status, exitCode, durationMs, stdout, stderr, result, error, rowsOutput and the billing summary of the run.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "language": "python",
    "code": "# `input` = the Input JSON, `rows` = rows from the dataset (if any).\n# Return a list of dicts -> one dataset row each. print() goes to stdout.\nnames = input.get(\"names\", [\"Ada\", \"Grace\", \"Linus\"])\nprint(f\"Processing {len(names)} names\")\nreturn [{\"name\": n, \"length\": len(n), \"upper\": n.upper()} for n in names]\n",
    "input": {
        "names": [
            "Ada",
            "Grace",
            "Linus"
        ]
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("actor-forge/code-runner-sandbox").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "language": "python",
    "code": """# `input` = the Input JSON, `rows` = rows from the dataset (if any).
# Return a list of dicts -> one dataset row each. print() goes to stdout.
names = input.get(\"names\", [\"Ada\", \"Grace\", \"Linus\"])
print(f\"Processing {len(names)} names\")
return [{\"name\": n, \"length\": len(n), \"upper\": n.upper()} for n in names]
""",
    "input": { "names": [
            "Ada",
            "Grace",
            "Linus",
        ] },
}

# Run the Actor and wait for it to finish
run = client.actor("actor-forge/code-runner-sandbox").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "language": "python",
  "code": "# `input` = the Input JSON, `rows` = rows from the dataset (if any).\\n# Return a list of dicts -> one dataset row each. print() goes to stdout.\\nnames = input.get(\\"names\\", [\\"Ada\\", \\"Grace\\", \\"Linus\\"])\\nprint(f\\"Processing {len(names)} names\\")\\nreturn [{\\"name\\": n, \\"length\\": len(n), \\"upper\\": n.upper()} for n in names]\\n",
  "input": {
    "names": [
      "Ada",
      "Grace",
      "Linus"
    ]
  }
}' |
apify call actor-forge/code-runner-sandbox --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,actor-forge/code-runner-sandbox"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/88BAz3SlqDBwh9jH6/builds/zHuMDmxKZgDOEFem6/openapi.json
