N8

n8n-code-python

Assistance for writing Python code within n8n automation nodes.

Install

mkdir -p .claude/skills/n8n-code-python && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/365" && unzip -o skill.zip -d .claude/skills/n8n-code-python && rm skill.zip

Installs to .claude/skills/n8n-code-python

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Write Python code in n8n Code nodes. Use when writing Python in n8n, using _input/_json/_node syntax, working with standard library, or need to understand Python limitations in n8n Code nodes. Use this skill when the user specifically requests Python for an n8n Code node. Note — JavaScript is recommended for 95% of use cases — only use Python when the user explicitly prefers it or the task requires Python-specific standard library capabilities (regex, hashlib, statistics). EXCEPTION — for Python in the AI-agent-callable Custom Code Tool (@n8n/n8n-nodes-langchain.toolCode), use the n8n-code-tool skill instead (input is _query, return must be a string).
659 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • →Apply _input.all() for iteration
  • →Handle webhook body via _json["body"]
  • →Implement regex pattern matching
  • →Apply hashlib for secure hashing
  • →Generate formatted JSON outputs

How it works

Executes user-provided code within an isolated Python runtime environment. It maps the node input data to specific pre-defined variables like _input and _json.

Inputs & outputs

You give it
Python code block using _input syntax
You get back
JSON array in [{"json": {...}}] format

When to use n8n-code-python

  • →Processing data in n8n nodes
  • →Performing statistics in n8n
  • →Writing regex transformations
  • →Handling JSON payloads with Python

About this skill

Python Code Node (native)

Since n8n 2.0 the Code node's Python runs as native Python in a task runner (language: "pythonNative"). The old Pyodide "Python (Beta)" is gone, and with it every n8n helper it had: _input, _json, _node, _now, _today and _jmespath all raise NameError now. Code copied from old templates, forum posts or older docs usually breaks on this.


JavaScript first — stronger than before

Native Python gives you two variables and plain Python, and by default no imports: no json, datetime or re. Everything n8n-specific ($('Node'), $jmespath, Luxon, this.helpers.httpRequest, static data) exists only in JavaScript. Use Python only when the user explicitly asks for it. Even then, first check whether an expression, Edit Fields, or a native node (Crypto, Date & Time, HTML, XML) does the job. See n8n-code-javascript and the transform gatekeeper in n8n-expression-syntax.


Quick start

# Run Once for All Items (default mode)
return [
    {"json": {"name": it["json"]["name"], "revenue": it["json"]["revenue"]}}
    for it in _items
    if it["json"].get("active")
]
# Run Once for Each Item
row = _item["json"]
return {"json": {**row, "name_upper": (row.get("name") or "").upper()}}

Node config: {"language": "pythonNative", "mode": "runOnceForAllItems" | "runOnceForEachItem", "pythonCode": "..."} on n8n-nodes-base.code typeVersion 2.


The only inputs: _items and _item

ModeVariableShape
Run Once for All Items_itemslist of plain dicts {"json": {...}, "pairedItem": {...}}
Run Once for Each Item_itemone plain dict {"json": {...}, "pairedItem": {...}}
  • Each variable exists only in its own mode. _items in each-item mode (or _item in all-items mode) raises NameError.
  • Dict access only. it["json"]["name"] or it["json"].get("name"). it.json.name raises AttributeError: 'dict' object has no attribute 'json'.
  • No other nodes. There is no _node / $('Node') equivalent. If you need data from another branch, bring it in with Merge first, or read it in JavaScript.
  • Webhook payloads are under ["body"]: _items[0]["json"].get("body", {}).get("email").
  • Binary data isn't covered here. Read and write binary in JavaScript (see n8n-binary-and-data).
  • pairedItem: returning _items / _item keeps it. When you build new dicts and downstream uses $('Node').item, add "pairedItem": {"item": i} to each returned item. That isn't verified on native Python yet, so test-run before relying on it.
  • Missing keys: prefer .get(key, default). row["missing"] raises KeyError.

Migration table for legacy code:

Legacy (Pyodide)Native
_input.all()_items
_input.first()["json"]_items[0]["json"] (guard if _items)
_input.item / _json_item / _item["json"]
_node["X"]not available: Merge upstream, or use JS
_now, _todaynot available: pass {{ $now.toISO() }} in via Edit Fields, or use JS
_jmespath(data, q)not available: $jmespath in an expression, or a comprehension
item.json.fielditem["json"]["field"]

Imports: blocked by default

Every import (standard library and third-party) is checked against an allowlist before the code runs. The default allowlist is empty, so even import json rejects the whole node:

Security violations detected
Line 1: Import of standard library module 'json' is disallowed. Allowed stdlib modules: none
  • n8n Cloud: no imports at all.
  • Self-hosted: the admin can allowlist modules in the task-runner config (see n8n-self-hosting → TASK_RUNNERS.md). Some instances therefore allow json, datetime and re, and most don't.
  • Default to import-free code. If an import would really help, confirm it first: a one-line test node import json + return [{"json": {"ok": True}}], or ask the user. Never assume.
  • Without imports: parse JSON strings upstream ({{ JSON.parse($json.payload) }} in Edit Fields). Do date math in expressions (Luxon) or JS. ISO-8601 strings still compare and sort correctly as plain strings. Use the Crypto node for hashing.
  • requests, pandas and numpy are never available unless the admin built a custom runner image. Use the HTTP Request node for HTTP.

Sandbox limits (these fail even without imports)

You writeWhat happensUse instead
eval, exec, compile, open, input, type, getattr, setattr, hasattr, vars, dir, globals, locals, object, memoryview, breakpointNameError: name 'type' is not defined (runtime)isinstance(x, dict); key in d / d.get(key)
class Foo: ...__build_class__ not found (runtime)dicts + functions
x.__class__, "{0.__class__}".format(x), __import__("json")Security violations detected (whole node rejected before running)—
global counter inside a functionNameError: name 'counter' is not defined, because your code runs inside a wrapper functionnonlocal counter

Everything else in plain Python works (verified): comprehensions, generators, lambdas, closures, recursion, try/except, f-strings / .format() / %, sorted/min/max/sum/any/all/ enumerate/zip/round, sets, isinstance, print() (output goes to the browser console).


Return shapes (verified)

Observed on n8n 2.38.5. The auto-wrapping and passthrough behaviours below are undocumented and could change in a later release. Re-check with a test run after upgrading n8n.

Run Once for All Items

ReturnResult
[{"json": {...}}, ...]canonical, N items
[{...}, ...] (plain dicts)auto-wrapped under json, N items
{"json": {...}} or a single plain dict1 item
_items (mutated in place)passthrough with your changes
None / no returnerror Cannot read properties of null (reading 'json')

Run Once for Each Item

ReturnResult
{"json": {...}}, a plain dict, or _item1 item
Nonethe item is dropped (a built-in filter)
a listerror A 'json' property isn't a dictionary [item 0]

Value conversion on output: tuple becomes a list, set becomes the string "{1, 2}", and a datetime becomes str(dt) ("2026-09-16 10:18:00.025792", not ISO). Convert explicitly (sorted(s), dt.isoformat()).

Prefer the explicit [{"json": ...}] in all-items mode and {"json": ...} in each-item mode. The auto-wrapping works, but the explicit shape makes the intent obvious to the next reader.


Errors and onError

A plain raise ValueError("bad row") fails the node with that message. When the node has an onError continue mode, the three failure kinds behave differently (verified):

FailurecontinueErrorOutputcontinueRegularOutput
Runtime exception (raise, KeyError, NameError, denied builtin){"error": "<message>"} on the error output (main[1]) ✅{"error": "<message>"} on the main output
Static rejection (Security violations detected: import, dunder)node marked failed, but the input items, unchanged, go out the success output; main[1] stays emptyinput items, unchanged, on the main output
Bad return shape (list in each-item mode, None in all-items mode)same: unchanged input on the success outputsame

The last two are silent-data traps: downstream nodes receive unprocessed input as if the code had run, and the execution still shows success. No error branch catches them. Prevent them (no imports unless confirmed, correct return shape) and confirm with a real test run, checking the Code node's status and output (see n8n-error-handling).

Other messages:

  • Python runner unavailable: Python 3 is missing from this system: the self-hosted instance has no Python task runner (the stock image ships none). It's an infrastructure problem, not a code problem. See n8n-self-hosting → TASK_RUNNERS.md.
  • validate_node / validate_workflow catch a few Python mistakes (import requests, missing return, return None). They do not catch _input/_json, dot access, blocked stdlib imports, dunder access or classes. A test execution is the only reliable check.

Performance

Each Python Code node costs roughly 0.4 s (about 1 s when the runner is cold), noticeably more than a JS Code node or an expression. Process lists in Run Once for All Items mode rather than per item, and don't chain several small Python nodes where one would do.


Checklist

  • The user actually asked for Python. Otherwise JS, an expression, or a native node.
  • Mode matches the variable: _items (all items) / _item (each item).
  • Only dict access. No _input, _json, _node, _now or _jmespath.
  • No import unless confirmed allowlisted on this instance.
  • No classes, type(), getattr/hasattr or dunders. nonlocal instead of global.
  • Return shape fits the mode. Sets and datetimes converted explicitly.
  • Ran a real test execution and inspected the output items (validation alone won't catch the traps above).

Reference

  • COMMON_PATTERNS.md: 12 import-free patterns, each verified on a live n8n instance (filter, aggregate, group, dedupe, top N, flatten, validate, drop items, text report, safe nested access, running totals, ISO timestamps).

Related skills

  • n8n-code-javascript: the default for Code nodes, with all n8n helpers.
  • n8n-expression-syntax: $jmespath, Luxon and the transform gatekeeper, often a better fit than any Code node.
  • n8n-code-tool: Python in the AI-agent Custom Code Tool (_query, returns a string).
  • n8n-error-handling: wiring error outputs; the passthrough trap above.
  • n8n-self-hosting

Content truncated.

When not to use it

  • →Standard JavaScript provides a simpler solution
  • →Task requires external dependencies like pandas or numpy

Prerequisites

N8n instanceAccess to n8n Code nodes

Limitations

  • →No external library support like pandas or numpy
  • →Standard library only

How it compares

It specifically restricts the user to the Python standard library to ensure compatibility with n8n's sandbox environment.

Compared to similar skills

n8n-code-python side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
n8n-code-python (this skill)73moReviewIntermediate
telegram-bot-builder1068moReviewIntermediate
codex-cli-bridge911moReviewIntermediate
code-to-music1711moReviewAdvanced

Try saying

Example prompts that trigger this skill in your AI assistant.

More by czlonkowski

View all by czlonkowski →

n8n-workflow-patterns

czlonkowski

Proven workflow architectural patterns from real n8n workflows. Use when building new workflows, designing workflow structure, choosing workflow patterns, planning workflow architecture, or asking about webhook processing, HTTP API integration, database operations, AI agent workflows, or scheduled tasks.

16115

n8n-code-javascript

czlonkowski

Write JavaScript code in n8n Code nodes. Use when writing JavaScript in n8n, using $input/$json/$node syntax, making HTTP requests with $helpers, working with dates using DateTime, troubleshooting Code node errors, or choosing between Code node modes.

7122

n8n-mcp-tools-expert

czlonkowski

Expert guide for using n8n-mcp MCP tools effectively. Use when searching for nodes, validating configurations, accessing templates, managing workflows, or using any n8n-mcp tool. Provides tool selection guidance, parameter formats, and common patterns.

7128

n8n-node-configuration

czlonkowski

Operation-aware node configuration guidance. Use when configuring nodes, understanding property dependencies, determining required fields, choosing between get_node_essentials and get_node_info, or learning common configuration patterns by node type.

7108

n8n-expression-syntax

czlonkowski

Validate n8n expression syntax and fix common errors. Use when writing n8n expressions, using {{}} syntax, accessing $json/$node variables, troubleshooting expression errors, or working with webhook data in workflows.

6111

n8n-validation-expert

czlonkowski

Interpret validation errors and guide fixing them. Use when encountering validation errors, validation warnings, false positives, operator structure issues, or need help understanding validation results. Also use when asking about validation profiles, error types, or the validation loop process.

697

You might also like

telegram-bot-builder

davila7

Expert in building Telegram bots that solve real problems - from simple automation to complex AI-powered bots. Covers bot architecture, the Telegram Bot API, user experience, monetization strategies, and scaling bots to thousands of users. Use when: telegram bot, bot api, telegram automation, chat bot telegram, tg bot.

106130

codex-cli-bridge

alirezarezvani

Bridge between Claude Code and OpenAI Codex CLI - generates AGENTS.md from CLAUDE.md, provides Codex CLI execution helpers, and enables seamless interoperability between both tools

9180

code-to-music

Cam10001110101

Tools, patterns, and utilities for creating music with code. Output as a .mp3 file with realistic instrument sounds. Write custom compositions to bring creativity to life through music. This skill should be used whenever the user asks for music to be created. Never use this skill for replicating songs, beats, riffs, or other sensitive works. The skill is not suitable for vocal/lyrical music, audio mixing/mastering (reverb, EQ, compression), real-time MIDI playback, or professional studio recording quality.

17164

jianying-editor

luoluoluo22

剪映 (JianYing) AI自动化剪辑的高级封装 API (JyWrapper)。提供开箱即用的 Python 接口,支持录屏、素材导入、字幕生成、Web 动效合成及项目导出。

38110

pdf-processing-pro

davila7

Production-ready PDF processing with forms, tables, OCR, validation, and batch operations. Use when working with complex PDF workflows in production environments, processing large volumes of PDFs, or requiring robust error handling and validation.

17110

async-python-patterns

wshobson

Master Python asyncio, concurrent programming, and async/await patterns for high-performance applications. Use when building async APIs, concurrent systems, or I/O-bound applications requiring non-blocking operations.

1299

Search skills

Search the agent skills registry