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 (Beta)

Expert guidance for writing Python code in n8n Code nodes.


⚠️ Important: JavaScript First

Recommendation: Use JavaScript for 95% of use cases. Only use Python when:

  • You need specific Python standard library functions
  • You're significantly more comfortable with Python syntax
  • You're doing data transformations better suited to Python

Why JavaScript is preferred:

  • Full n8n helper functions (this.helpers.httpRequest, etc.)
  • Luxon DateTime library for advanced date/time operations
  • No external library limitations
  • Better n8n documentation and community support

Quick Start

# Basic template for Python Code nodes
items = _input.all()

# Process data
processed = []
for item in items:
    processed.append({
        "json": {
            **item["json"],
            "processed": True,
            "timestamp": datetime.now().isoformat()
        }
    })

return processed

Essential Rules

  1. Consider JavaScript first - Use Python only when necessary
  2. Access data: _input.all(), _input.first(), or _input.item
  3. CRITICAL: Must return [{"json": {...}}] format
  4. CRITICAL: Webhook data is under _json["body"] (not _json directly)
  5. CRITICAL LIMITATION: No external libraries (no requests, pandas, numpy)
  6. Standard library only: json, datetime, re, base64, hashlib, urllib.parse, math, random, statistics

Mode Selection Guide

Same as JavaScript - choose based on your use case:

Run Once for All Items (Recommended - Default)

Use this mode for: 95% of use cases

  • How it works: Code executes once regardless of input count
  • Data access: _input.all() or _items array (Native mode)
  • Best for: Aggregation, filtering, batch processing, transformations
  • Performance: Faster for multiple items (single execution)
# Example: Calculate total from all items
all_items = _input.all()
total = sum(item["json"].get("amount", 0) for item in all_items)

return [{
    "json": {
        "total": total,
        "count": len(all_items),
        "average": total / len(all_items) if all_items else 0
    }
}]

Run Once for Each Item

Use this mode for: Specialized cases only

  • How it works: Code executes separately for each input item
  • Data access: _input.item or _item (Native mode)
  • Best for: Item-specific logic, independent operations, per-item validation
  • Performance: Slower for large datasets (multiple executions)
# Example: Add processing timestamp to each item
item = _input.item

return [{
    "json": {
        **item["json"],
        "processed": True,
        "processed_at": datetime.now().isoformat()
    }
}]

Python Modes: Beta vs Native

n8n offers two Python execution modes:

Python (Beta) - Recommended

  • Use: _input, _json, _node helper syntax
  • Best for: Most Python use cases
  • Helpers available: _now, _today, _jmespath()
  • Import: from datetime import datetime
# Python (Beta) example
items = _input.all()
now = _now  # Built-in datetime object

return [{
    "json": {
        "count": len(items),
        "timestamp": now.isoformat()
    }
}]

Python (Native) (Beta)

  • Use: _items, _item variables only
  • No helpers: No _input, _now, etc.
  • More limited: Standard Python only
  • Use when: Need pure Python without n8n helpers
# Python (Native) example
processed = []

for item in _items:
    processed.append({
        "json": {
            "id": item["json"].get("id"),
            "processed": True
        }
    })

return processed

Recommendation: Use Python (Beta) for better n8n integration.


Data Access Patterns

Access input data through underscore-prefixed variables. Each item is a dict shaped {"json": {...}}, so the actual fields live under ["json"].

# Pattern 1: _input.all() - Most common. Arrays, batch ops, aggregations
all_items = _input.all()            # list of {"json": {...}} dicts

# Pattern 2: _input.first() - Very common. Single objects, API responses
data = _input.first()["json"]       # built-in safety vs all_items[0]

# Pattern 3: _input.item - "Run Once for Each Item" mode ONLY
current = _input.item["json"]       # None/error in All Items mode

# Pattern 4: _node - Reference a specific named node
webhook_data = _node["Webhook"]["json"]
http_data = _node["HTTP Request"]["json"]

See: DATA_ACCESS.md for the comprehensive guide — six _input.all() recipes (filter, transform, aggregate, sort, group, deduplicate), _input.first() and _input.item examples, multi-node combining, the JS-vs-Python variable table, and the decision tree.


Critical: Webhook Data Structure

MOST COMMON MISTAKE: Webhook data is nested under ["body"]

# ❌ WRONG - Will raise KeyError
name = _json["name"]
email = _json["email"]

# ✅ CORRECT - Webhook data is under ["body"]
name = _json["body"]["name"]
email = _json["body"]["email"]

# ✅ SAFER - Use .get() for safe access
webhook_data = _json.get("body", {})
name = webhook_data.get("name")

Why: Webhook node wraps all request data under body property. This includes POST data, query parameters, and JSON payloads.

See: DATA_ACCESS.md for full webhook structure details


Return Format Requirements

CRITICAL RULE: Always return list of dictionaries with "json" key

Correct Return Formats

# ✅ Single result
return [{
    "json": {
        "field1": value1,
        "field2": value2
    }
}]

# ✅ Multiple results
return [
    {"json": {"id": 1, "data": "first"}},
    {"json": {"id": 2, "data": "second"}}
]

# ✅ List comprehension
transformed = [
    {"json": {"id": item["json"]["id"], "processed": True}}
    for item in _input.all()
    if item["json"].get("valid")
]
return transformed

# ✅ Empty result (when no data to return)
return []

# ✅ Conditional return
if should_process:
    return [{"json": processed_data}]
else:
    return []

Incorrect Return Formats

# ❌ WRONG: Dictionary without list wrapper
return {
    "json": {"field": value}
}

# ❌ WRONG: List without json wrapper
return [{"field": value}]

# ❌ WRONG: Plain string
return "processed"

# ❌ WRONG: Incomplete structure
return [{"data": value}]  # Should be {"json": value}

Why it matters: Next nodes expect list format. Incorrect format causes workflow execution to fail.

See: ERROR_PATTERNS.md #2 for detailed error solutions


Critical Limitation: No External Libraries

MOST IMPORTANT PYTHON LIMITATION: Cannot import external packages on default installs.

Self-hosted exception: external package availability depends entirely on the instance's Python runner configuration. If the user states their self-hosted instance has specific packages available in the Python runner environment, use them — don't refuse. When unsure, ask or write standard-library-only code.

❌ NOT available (raise ModuleNotFoundError): requests, pandas, numpy, scipy, bs4/BeautifulSoup, lxml.

✅ Available (standard library only): json, datetime, re, base64, hashlib, urllib.parse, math, random, statistics.

Workarounds

Need HTTP requests?

  • ✅ Use HTTP Request node before Code node
  • ✅ Or switch to JavaScript and use this.helpers.httpRequest() (the bare $helpers global is undefined in the task-runner sandbox)

Need data analysis (pandas/numpy)?

  • ✅ Use Python statistics module for basic stats
  • ✅ Or switch to JavaScript for most operations
  • ✅ Manual calculations with lists and dictionaries

Need web scraping (BeautifulSoup)?

  • ✅ Use HTTP Request node + HTML Extract node
  • ✅ Or switch to JavaScript with regex/string methods

See: STANDARD_LIBRARY.md for complete reference


Common Patterns Overview

Based on production workflows, the most useful Python patterns are:

  1. Data Transformation - Transform all items with list comprehensions
  2. Filtering & Aggregation - Sum, filter, count with built-in functions
  3. String Processing with Regex - Extract patterns from text with re
  4. Data Validation - Validate and clean data, attach error lists
  5. Statistical Analysis - Calculate mean/median/stdev with the statistics module

Copy-ready snippets for all five live in COMMON_PATTERNS.md, alongside 10 fully detailed production patterns (multi-source aggregation, markdown parsing, JSON comparison, CRM normalization, dictionary lookup, top-N filtering, and more).


Error Prevention - Top 5 Mistakes

  1. Importing external libraries (Python-specific) → import requests raises ModuleNotFoundError. Use the HTTP Request node or JavaScript instead.
  2. Empty code or missing return → every path must end with return [{"json": ...}].
  3. Incorrect return format → wrap in a list: {"json": {...}} becomes [{"json": {...}}].
  4. KeyError on dictionary access → use .get(): _json.get("user", {}).get("name", "Unknown").
  5. Webhook body nesting → read via ["body"]: _json.get("body", {}).get("email", "no-email").

See: ERROR_PATTERNS.md for the comprehensive guide — each error with wrong-vs-right code, error messages, nested-access fixes, an AttributeError bonus case, a prevention checklist, and a quick-fix table.


Standard Library Reference

Most useful modules: json (parse/generate), datetime (dates + timedelta), re (regex), base64 (encode/decode), hashlib (hashing), urllib.parse (URL ops), and statistics (mean/median/stdev). Also available: math, random, collections, itertools, functools.

For a condensed cheat sheet plus full per-module examples, see [STANDARD_LIBRARY.md](STANDARD_LIBRA


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)72moReviewIntermediate
telegram-bot-builder1066moReviewIntermediate
codex-cli-bridge99moReviewIntermediate
code-to-music1710moReviewAdvanced

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