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.zipInstalls 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).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
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
- Consider JavaScript first - Use Python only when necessary
- Access data:
_input.all(),_input.first(), or_input.item - CRITICAL: Must return
[{"json": {...}}]format - CRITICAL: Webhook data is under
_json["body"](not_jsondirectly) - CRITICAL LIMITATION: No external libraries (no requests, pandas, numpy)
- 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_itemsarray (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.itemor_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,_nodehelper 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,_itemvariables 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$helpersglobal 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:
- Data Transformation - Transform all items with list comprehensions
- Filtering & Aggregation - Sum, filter, count with built-in functions
- String Processing with Regex - Extract patterns from text with
re - Data Validation - Validate and clean data, attach error lists
- Statistical Analysis - Calculate mean/median/stdev with the
statisticsmodule
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
- Importing external libraries (Python-specific) →
import requestsraisesModuleNotFoundError. Use the HTTP Request node or JavaScript instead. - Empty code or missing return → every path must end with
return [{"json": ...}]. - Incorrect return format → wrap in a list:
{"json": {...}}becomes[{"json": {...}}]. - KeyError on dictionary access → use
.get():_json.get("user", {}).get("name", "Unknown"). - 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
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.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| n8n-code-python (this skill) | 7 | 2mo | Review | Intermediate |
| telegram-bot-builder | 106 | 6mo | Review | Intermediate |
| codex-cli-bridge | 9 | 9mo | Review | Intermediate |
| code-to-music | 17 | 10mo | Review | Advanced |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by czlonkowski
View all by czlonkowski →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.
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
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.
jianying-editor
luoluoluo22
剪映 (JianYing) AI自动化剪辑的高级封装 API (JyWrapper)。提供开箱即用的 Python 接口,支持录屏、素材导入、字幕生成、Web 动效合成及项目导出。
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.
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.