# Run Python or JavaScript on a Dataset - Code Step for Scrapers (`northbell/code-step`) Actor

Paste a Python or JavaScript function and run it on any Apify dataset, a JSON/CSV link or inline items. Dedupe, flatten, clean, group with pandas. Add it as an integration after your scraper.

- **URL**: https://apify.com/northbell/code-step.md
- **Developed by:** [Northbell](https://apify.com/northbell) (community)
- **Categories:** Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.16 / 1,000 items

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

## Run Python or JavaScript on a Dataset - Code Step for Scrapers

**Paste a function, point it at data, get the result as a dataset.** The Actor reads items from an Apify dataset, a JSON / JSON lines / CSV link, or items you type in, runs your Python or JavaScript on them, and saves what your function returns. Use it to dedupe, flatten, clean or group scraper output, and add it as an integration so it runs by itself after your scraper.

**Try it now — the input is already filled in.** Press **Start**. It runs a short JavaScript function on three example products: it drops the one without a title and adds a `titleLength` field to the others. In our own local run with this input: **3 items in, 2 items out, about 0.3 seconds of code time** (the whole run took about 3 seconds). Cost: 2 returned items = **$0.0004** (plus $0.00005 for the run start).

### What you pay

| Event | Price | When |
| --- | --- | --- |
| `item-out` | $0.0002 | per item your code returns and the Actor saves ($0.20 per 1,000) |
| `apify-actor-start` | $0.00005 | once per run |

- You pay for returned items only, not for items read. Dropping items is free.
- Items are saved and charged in chunks of 1,000. Set "Maximum total charge" on the run as your cap: the Actor stops cleanly when the next chunk does not fit, and everything charged is in the dataset.
- A run that fails before your code returns anything (empty code, no data, a code error) charges only the start event.

### Run it after your scraper

1. In Apify Console, open your scraper and go to **Integrations**.
2. Add **Run Actor** (on "Run succeeded") and pick this Actor.
3. Use an input like this:

```json
{
  "language": "javascript",
  "datasetId": "{{resource.defaultDatasetId}}",
  "mode": "batch",
  "code": "async function transform(items, ctx) {\n  const seen = new Set();\n  return items.filter((i) => i.url && !seen.has(i.url) && seen.add(i.url));\n}"
}
```

Every run of the scraper hands over its dataset, your function runs on it, and the cleaned items appear in this Actor's own dataset (and can feed the next integration).

### How your code looks

You write one function. `ctx.input` is the "Parameters" object from the input; `ctx.log(...)` writes to the run log.

| Mode | JavaScript (Node 24) | Python 3 |
| --- | --- | --- |
| `batch` | `async function transform(items, ctx) { return items }` | `def transform(items, ctx): return items` |
| `perItem` | `async function map(item, ctx) { return item }` | `def map(item, ctx): return item` |

- **Batch** gets the whole list (up to "Max items", 100,000 by default) and returns a list of objects.
- **Per item** gets one item at a time and returns an object, a list of objects (to split an item) or `null` / `None` (to drop it). Data is processed in chunks of 1,000, so memory stays small on big datasets.
- In Python, `ctx` is a dict: `ctx["input"]`, `ctx["log"]("text")`. A pandas DataFrame returned from `transform` is turned into a list of rows; NaN becomes `null`.
- Every returned item must be a JSON object. If not, the run stops with a message that names the item index.

#### JavaScript: dedupe by URL

```js
async function transform(items, ctx) {
  const seen = new Set();
  return items.filter((i) => i.url && !seen.has(i.url) && seen.add(i.url));
}
```

#### JavaScript: flatten nested fields

```js
async function map(item, ctx) {
  const { address, ...rest } = item;
  return { ...rest, city: address?.city ?? null, street: address?.street ?? null };
}
```

#### Python: pandas groupby

Set "Python packages" to `pandas` if you want a specific version (pandas and numpy are already installed in the image), then:

```python
import pandas as pd

def transform(items, ctx):
    df = pd.DataFrame(items)
    return df.groupby("category", as_index=False).agg(
        count=("price", "size"), avg_price=("price", "mean")
    )
```

#### Python: flatten and clean per item

```python
def map(item, ctx):
    price = item.get("price", {})
    if not item.get("title"):
        return None  # drop
    return {"title": item["title"].strip(), "amount": price.get("amount"), "currency": price.get("currency")}
```

### Where the data comes from

If more than one source is given, the order is: Dataset ID, then Source URL, then inline items.

- **Dataset ID**: any dataset you can read. In an integration use `{{resource.defaultDatasetId}}`.
- **Source URL**: a JSON array, a JSON lines file or a CSV file (comma, semicolon or tab; first line = field names; CSV values come as text). Only public http(s) links; private and local addresses are blocked.
- **Items**: a list of objects typed into the input.

### Python packages

Add names to "Python packages" (at most 20, for example `requests>=2.31`). They are installed with `pip install` into a temporary folder at the start of the run, which can take from seconds to a few minutes and is not counted against the code time limit. The image is Alpine Linux. pandas and numpy are installed in the image from Alpine's own packages, so they work without compiling. Other packages that ship only source code or glibc wheels may fail to install on Alpine; the run then stops with pip's message before your code runs.

### Security note

Your code runs in a separate, isolated child process inside **your own** Apify run. Nothing of the Actor's is passed to it except `PATH`, `HOME`, `LANG`, `TZ`, and your own `APIFY_TOKEN` and `APIFY_USER_ID` (so your code can call the Apify API as you, for example to start another Actor). No other environment variable is visible. Data goes to and from your code through temporary files that are deleted when the run ends. Your code can use the network and can do anything your token can do, so only run code you trust.

### Limits

- Output items must be JSON objects; other return values stop the run with an error that names the item.
- "Code time limit" (default 300 seconds) covers all of your code in the run; when it runs out the process is killed and the run fails. Items saved before that stay saved (per item mode saves chunk by chunk).
- Memory: the run has 2048 MB by default. If your code runs out of memory the run fails with a plain message; use per item mode or raise the run memory.
- Batch mode keeps the whole list in memory (up to "Max items"). A Source URL file is read completely before processing (up to 200 MB).
- Per item mode starts your code once per chunk of 1,000 items, so state is not kept between chunks.
- JavaScript code is run as a CommonJS module: use `require(...)` or `await import(...)`, not `import` statements. Only Node's built-in modules are available in JavaScript (no npm install).
- Everything your code prints is shown in the run log (the first 100 lines).

# Actor input Schema

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

The language of your code.

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

JavaScript: async function transform(items, ctx) { return items } (mode batch) or async function map(item, ctx) { return item } (mode perItem; return null to drop an item or an array to split it). Python: def transform(items, ctx): return items, or def map(item, ctx). ctx.input is your 'Parameters' object; ctx.log(...) writes to the run log (Python: ctx\['input'], ctx\['log']).

## `mode` (type: `string`):

Batch loads up to 'Max items' into memory and calls transform once. Per item streams the data in chunks of 1000, so memory stays small.

## `items` (type: `array`):

A list of objects to work on. Used only when no Dataset ID and no Source URL is given.

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

Read the items from this Apify dataset. Use {{resource.defaultDatasetId}} when you add this Actor as an integration after another Actor.

## `sourceUrl` (type: `string`):

Link to a JSON array, a JSON lines file or a CSV file (comma, semicolon or tab separated; the first line holds the field names).

## `params` (type: `object`):

Any JSON object. Your code reads it as ctx.input (JavaScript) or ctx\['input'] (Python).

## `requirements` (type: `array`):

Python only: packages to pip install before your code runs, for example pandas or requests>=2.31. At most 20. pandas and numpy are already installed.

## `maxItems` (type: `integer`):

Read at most this many items from the source.

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

Your code is stopped after this many seconds in total. Installing packages does not count.

## Actor input object example

```json
{
  "language": "javascript",
  "code": "async function transform(items, ctx) {\n  return items\n    .filter((item) => item.title)\n    .map((item) => ({ ...item, titleLength: item.title.length }));\n}",
  "mode": "batch",
  "items": [
    {
      "title": "Blue running shoes",
      "price": 59.9,
      "url": "https://example.com/p/1"
    },
    {
      "title": "Wool socks, 3 pack",
      "price": 12,
      "url": "https://example.com/p/2"
    },
    {
      "price": 8.5,
      "url": "https://example.com/p/3"
    }
  ],
  "params": {},
  "maxItems": 100000,
  "timeoutSecs": 300
}
```

# Actor output Schema

## `items` (type: `string`):

One row per item your function returned.

# 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": "javascript",
    "code": async function transform(items, ctx) {
      return items
        .filter((item) => item.title)
        .map((item) => ({ ...item, titleLength: item.title.length }));
    },
    "mode": "batch",
    "items": [
        {
            "title": "Blue running shoes",
            "price": 59.9,
            "url": "https://example.com/p/1"
        },
        {
            "title": "Wool socks, 3 pack",
            "price": 12,
            "url": "https://example.com/p/2"
        },
        {
            "price": 8.5,
            "url": "https://example.com/p/3"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("northbell/code-step").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": "javascript",
    "code": """async function transform(items, ctx) {
  return items
    .filter((item) => item.title)
    .map((item) => ({ ...item, titleLength: item.title.length }));
}""",
    "mode": "batch",
    "items": [
        {
            "title": "Blue running shoes",
            "price": 59.9,
            "url": "https://example.com/p/1",
        },
        {
            "title": "Wool socks, 3 pack",
            "price": 12,
            "url": "https://example.com/p/2",
        },
        {
            "price": 8.5,
            "url": "https://example.com/p/3",
        },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("northbell/code-step").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": "javascript",
  "code": "async function transform(items, ctx) {\\n  return items\\n    .filter((item) => item.title)\\n    .map((item) => ({ ...item, titleLength: item.title.length }));\\n}",
  "mode": "batch",
  "items": [
    {
      "title": "Blue running shoes",
      "price": 59.9,
      "url": "https://example.com/p/1"
    },
    {
      "title": "Wool socks, 3 pack",
      "price": 12,
      "url": "https://example.com/p/2"
    },
    {
      "price": 8.5,
      "url": "https://example.com/p/3"
    }
  ]
}' |
apify call northbell/code-step --silent --output-dataset

```

## MCP server setup

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

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/kr9YTrveXvEenEiag/builds/GuPcyva9nZL3WgrpF/openapi.json
