# Python & JS Code Runner - $0.50/1K Rows, No API Key (`martin10291/code-runner-sandbox`) Actor

Paste a transform(row) function in Python or JavaScript, give rows as JSON or an Apify dataset ID, get the returned rows in a dataset. One process per run (about 0.1 ms per row after start), per-row errors with line numbers, time and memory limits, filter/split rows, only-new mode with monitorId. Ca

- **URL**: https://apify.com/martin10291/code-runner-sandbox.md
- **Developed by:** [Martin Petrov](https://apify.com/martin10291) (community)
- **Categories:** Developer tools, Automation, Business
- **Features:** Limited permissions
- **Stats:** 3 total users, 2 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.35 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## Python & JS Code Runner - $0.50/1K Rows, No API Key

**Problem:** n8n, Make, Zapier and Apify pipelines often need one small custom step: clean a name, split a field, compute a score, drop junk rows. No-code tools have no safe place for 20 lines of Python or JavaScript, so people host a Lambda or a VPS just for that.

**This actor:** you paste a `transform(row)` function, give rows (JSON or an Apify dataset ID), and get the returned rows back in a dataset. No server, no API key for any third-party service.

### Quick start

Input:

```json
{
  "language": "python",
  "code": "def transform(row):\n    return {\"name\": row[\"name\"].strip().title(), \"domain\": row[\"email\"].split(\"@\")[-1].lower()}",
  "rows": [{"name": "  ada lovelace ", "email": "Ada@Example.COM"}]
}
```

Output row:

```json
{"name": "Ada Lovelace", "domain": "example.com", "_rowIndex": 0}
```

JavaScript works the same way (async functions are fine):

```js
async function transform(row) {
  if (!row.price) return null;            // null = drop the row (filter)
  return { sku: row.sku, priceEur: +(row.price * 0.86).toFixed(2) };
}
```

### What your function can return

| Return value | Result |
|---|---|
| dict / object | one output row |
| list of dicts | several output rows (split one row into many) |
| None / null | row is dropped (filter) |
| a plain value | `{"result": value}` |

`outputMode: "merge"` keeps the input row and adds/overwrites the fields you return.

### Errors are per row, not per run

A row that throws or runs past `rowTimeoutSecs` does not stop the run. It goes to the `ERRORS` key-value record with the error message, the **line number in your code**, the `print()` / `console.log` output of that row and the input row. You are not charged for error rows (unless you turn on `includeErrorRows`). If the code cannot even start (syntax error, no `transform`), the run ends cleanly with that message in the status and `RUN_SUMMARY.lastError`.

### Speed and limits (measured 2026-11-18)

- All rows run in **one child process** per run: about 0.1 ms per row for a simple Python transform after start (4 rows = 0.14 s total), no cold start per row.
- `rowTimeoutSecs` (default 10 s) stops one slow row, including endless loops in JavaScript.
- `totalTimeoutSecs` and `memoryLimitMb` cap the whole step.
- Python 3.12 standard library (`json`, `re`, `datetime`, `hashlib`, `csv`, `math`, `statistics`, `urllib` ...). Node.js built-ins via `require` (`crypto`, `url`, `querystring` ...), plus `fetch`.

### Only-new mode (repeat runs)

Set `monitorId` (any name, e.g. `daily-leads`) and optionally `keyField` (e.g. `id`). The actor remembers the output of every row; on the next run with the same ID only new or changed rows are returned, with `first_seen`, `changed_at` and `is_new`. Good for scheduled runs that should only push changes to your CRM or sheet.

### Use from n8n / Make / Zapier / API

```bash
curl -X POST "https://api.apify.com/v2/acts/martin10291~code-runner-sandbox/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"language":"javascript","code":"function transform(r){return {total: r.qty * r.price}}","rows":[{"qty":3,"price":9.5}]}'
```

Chain it after another actor: pass that run's `defaultDatasetId` as `datasetId`.

### Use from AI agents (MCP)

Add the Apify MCP server (`https://mcp.apify.com`) to Claude, Cursor or any MCP client and call this actor as a tool: the agent sends code + rows and gets clean rows back, with per-row errors it can read and fix.

### Run summary

`RUN_SUMMARY` record: `inputRows`, `saved`, `errorRows`, `skippedUnchanged`, `wallSeconds`, `avgRowMs`, `lastError`.

### Notes

- Your code runs inside your own run's container; nothing is sent to other services unless your code does it.
- Price: $0.50 per 1,000 output rows. Error rows and dropped rows are free.

# Actor input Schema

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

Language of your code: python (Python 3.12, standard library) or javascript (Node.js, async allowed).

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

Define a function transform(row). It gets one input row (a dict / object) and returns a dict, a list of dicts (one row becomes many) or None (row is dropped = filter). print()/console.log output is kept per row in the ERRORS record when a row fails.

## `rows` (type: `array`):

Rows to process, as a JSON array of objects (or values). Used together with datasetId if both are given.

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

Read the input rows from this Apify dataset (for example the output of another actor run in your account). Leave empty to use only the rows field.

## `maxRows` (type: `integer`):

Process at most this many input rows in one run.

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

result = only the fields your function returns; merge = the input row plus the returned fields (returned fields win).

## `rowTimeoutSecs` (type: `number`):

A row that takes longer is stopped and reported as an error; the other rows continue.

## `totalTimeoutSecs` (type: `integer`):

Wall-clock limit for running your code on all rows. Rows not finished in time are reported as errors.

## `memoryLimitMb` (type: `integer`):

Memory cap for the child process that runs your code (keep it below the run memory).

## `includeErrorRows` (type: `boolean`):

Off (default): failed rows go only to the ERRORS key-value record and you pay nothing for them. On: they are also added to the dataset with \_error and \_input fields.

## `monitorId` (type: `string`):

Give any name (for example daily-leads) to remember results between runs: rows whose output did not change since the last run with the same ID are skipped, new/changed rows get first_seen, changed_at and is_new.

## `keyField` (type: `string`):

Field that identifies a row across runs (for example id or url). Empty = the whole input row is the key.

## Actor input object example

```json
{
  "language": "python",
  "code": "def transform(row):\n    # one input row in, one output row out (return None to drop it, a list to split it)\n    email = row.get(\"email\", \"\")\n    return {\n        \"company\": row[\"company\"].strip().title(),\n        \"domain\": email.split(\"@\")[-1].lower() if \"@\" in email else None,\n        \"revenue_eur\": round(float(row[\"revenue_usd\"]) * 0.86, 2),\n        \"is_big\": float(row[\"revenue_usd\"]) >= 1_000_000,\n    }\n",
  "rows": [
    {
      "company": "  acme robotics ",
      "email": "Sales@ACME-Robotics.com",
      "revenue_usd": "2500000"
    },
    {
      "company": "blue fern cafe",
      "email": "hello@bluefern.cafe",
      "revenue_usd": "180000"
    },
    {
      "company": "NORTHWIND traders",
      "email": "info@northwind.example",
      "revenue_usd": "1000000"
    }
  ],
  "maxRows": 1000,
  "outputMode": "result",
  "rowTimeoutSecs": 10,
  "totalTimeoutSecs": 600,
  "memoryLimitMb": 1024,
  "includeErrorRows": false
}
```

# Actor output Schema

## `results` (type: `string`):

Rows returned by your transform(row) function.

## `summary` (type: `string`):

Counts, timing and the last error (RUN_SUMMARY record).

## `errors` (type: `string`):

Failed rows with error message, line number and logs (ERRORS record).

# 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 = {
    "code": `def transform(row):
    # one input row in, one output row out (return None to drop it, a list to split it)
    email = row.get("email", "")
    return {
        "company": row["company"].strip().title(),
        "domain": email.split("@")[-1].lower() if "@" in email else None,
        "revenue_eur": round(float(row["revenue_usd"]) * 0.86, 2),
        "is_big": float(row["revenue_usd"]) >= 1_000_000,
    }`,
    "rows": [
        {
            "company": "  acme robotics ",
            "email": "Sales@ACME-Robotics.com",
            "revenue_usd": "2500000"
        },
        {
            "company": "blue fern cafe",
            "email": "hello@bluefern.cafe",
            "revenue_usd": "180000"
        },
        {
            "company": "NORTHWIND traders",
            "email": "info@northwind.example",
            "revenue_usd": "1000000"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("martin10291/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 = {
    "code": """def transform(row):
    # one input row in, one output row out (return None to drop it, a list to split it)
    email = row.get(\"email\", \"\")
    return {
        \"company\": row[\"company\"].strip().title(),
        \"domain\": email.split(\"@\")[-1].lower() if \"@\" in email else None,
        \"revenue_eur\": round(float(row[\"revenue_usd\"]) * 0.86, 2),
        \"is_big\": float(row[\"revenue_usd\"]) >= 1_000_000,
    }
""",
    "rows": [
        {
            "company": "  acme robotics ",
            "email": "Sales@ACME-Robotics.com",
            "revenue_usd": "2500000",
        },
        {
            "company": "blue fern cafe",
            "email": "hello@bluefern.cafe",
            "revenue_usd": "180000",
        },
        {
            "company": "NORTHWIND traders",
            "email": "info@northwind.example",
            "revenue_usd": "1000000",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("martin10291/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 '{
  "code": "def transform(row):\\n    # one input row in, one output row out (return None to drop it, a list to split it)\\n    email = row.get(\\"email\\", \\"\\")\\n    return {\\n        \\"company\\": row[\\"company\\"].strip().title(),\\n        \\"domain\\": email.split(\\"@\\")[-1].lower() if \\"@\\" in email else None,\\n        \\"revenue_eur\\": round(float(row[\\"revenue_usd\\"]) * 0.86, 2),\\n        \\"is_big\\": float(row[\\"revenue_usd\\"]) >= 1_000_000,\\n    }\\n",
  "rows": [
    {
      "company": "  acme robotics ",
      "email": "Sales@ACME-Robotics.com",
      "revenue_usd": "2500000"
    },
    {
      "company": "blue fern cafe",
      "email": "hello@bluefern.cafe",
      "revenue_usd": "180000"
    },
    {
      "company": "NORTHWIND traders",
      "email": "info@northwind.example",
      "revenue_usd": "1000000"
    }
  ]
}' |
apify call martin10291/code-runner-sandbox --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,martin10291/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/bH3TMvlbcO0h0wW1Y/builds/dnefhhKYS2wrkQw11/openapi.json
