N8N Code Python
Write Python in n8n Code nodes with safe patterns and no external libs
✨ The solution you've been looking for
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.
See It In Action
Interactive preview & real-world examples
AI Conversation Simulator
See how users interact with this skill
User Prompt
I have customer data from a webhook and need to filter active customers, calculate totals, and format the output for the next node
Skill Processing
Analyzing request...
Agent Response
Clean, transformed data with proper n8n return format, filtered results, and calculated aggregations
Quick Start (3 Steps)
Get up and running in minutes
Install
claude-code skill install n8n-code-python
claude-code skill install n8n-code-pythonConfig
First Trigger
@n8n-code-python helpCommands
| Command | Description | Required Args |
|---|---|---|
| @n8n-code-python data-transformation-and-filtering | Transform and filter data from previous nodes using Python list comprehensions and built-in functions | None |
| @n8n-code-python statistical-analysis-of-workflow-data | Perform statistical calculations on numerical data using Python's statistics module | None |
| @n8n-code-python text-processing-with-regex-patterns | Extract patterns from text data using Python's regex capabilities and string processing | None |
Typical Use Cases
Data transformation and filtering
Transform and filter data from previous nodes using Python list comprehensions and built-in functions
Statistical analysis of workflow data
Perform statistical calculations on numerical data using Python's statistics module
Text processing with regex patterns
Extract patterns from text data using Python's regex capabilities and string processing
Overview
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 ($helpers.httpRequest, etc.)
- Luxon DateTime library for advanced date/time operations
- No external library limitations
- Better n8n documentation and community support
Quick Start
1# Basic template for Python Code nodes
2items = _input.all()
3
4# Process data
5processed = []
6for item in items:
7 processed.append({
8 "json": {
9 **item["json"],
10 "processed": True,
11 "timestamp": datetime.now().isoformat()
12 }
13 })
14
15return 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)
1# Example: Calculate total from all items
2all_items = _input.all()
3total = sum(item["json"].get("amount", 0) for item in all_items)
4
5return [{
6 "json": {
7 "total": total,
8 "count": len(all_items),
9 "average": total / len(all_items) if all_items else 0
10 }
11}]
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)
1# Example: Add processing timestamp to each item
2item = _input.item
3
4return [{
5 "json": {
6 **item["json"],
7 "processed": True,
8 "processed_at": datetime.now().isoformat()
9 }
10}]
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
1# Python (Beta) example
2items = _input.all()
3now = _now # Built-in datetime object
4
5return [{
6 "json": {
7 "count": len(items),
8 "timestamp": now.isoformat()
9 }
10}]
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
1# Python (Native) example
2processed = []
3
4for item in _items:
5 processed.append({
6 "json": {
7 "id": item["json"].get("id"),
8 "processed": True
9 }
10 })
11
12return processed
Recommendation: Use Python (Beta) for better n8n integration.
Data Access Patterns
Pattern 1: _input.all() - Most Common
Use when: Processing arrays, batch operations, aggregations
1# Get all items from previous node
2all_items = _input.all()
3
4# Filter, transform as needed
5valid = [item for item in all_items if item["json"].get("status") == "active"]
6
7processed = []
8for item in valid:
9 processed.append({
10 "json": {
11 "id": item["json"]["id"],
12 "name": item["json"]["name"]
13 }
14 })
15
16return processed
Pattern 2: _input.first() - Very Common
Use when: Working with single objects, API responses
1# Get first item only
2first_item = _input.first()
3data = first_item["json"]
4
5return [{
6 "json": {
7 "result": process_data(data),
8 "processed_at": datetime.now().isoformat()
9 }
10}]
Pattern 3: _input.item - Each Item Mode Only
Use when: In “Run Once for Each Item” mode
1# Current item in loop (Each Item mode only)
2current_item = _input.item
3
4return [{
5 "json": {
6 **current_item["json"],
7 "item_processed": True
8 }
9}]
Pattern 4: _node - Reference Other Nodes
Use when: Need data from specific nodes in workflow
1# Get output from specific node
2webhook_data = _node["Webhook"]["json"]
3http_data = _node["HTTP Request"]["json"]
4
5return [{
6 "json": {
7 "combined": {
8 "webhook": webhook_data,
9 "api": http_data
10 }
11 }
12}]
See: DATA_ACCESS.md for comprehensive guide
Critical: Webhook Data Structure
MOST COMMON MISTAKE: Webhook data is nested under ["body"]
1# ❌ WRONG - Will raise KeyError
2name = _json["name"]
3email = _json["email"]
4
5# ✅ CORRECT - Webhook data is under ["body"]
6name = _json["body"]["name"]
7email = _json["body"]["email"]
8
9# ✅ SAFER - Use .get() for safe access
10webhook_data = _json.get("body", {})
11name = 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
1# ✅ Single result
2return [{
3 "json": {
4 "field1": value1,
5 "field2": value2
6 }
7}]
8
9# ✅ Multiple results
10return [
11 {"json": {"id": 1, "data": "first"}},
12 {"json": {"id": 2, "data": "second"}}
13]
14
15# ✅ List comprehension
16transformed = [
17 {"json": {"id": item["json"]["id"], "processed": True}}
18 for item in _input.all()
19 if item["json"].get("valid")
20]
21return transformed
22
23# ✅ Empty result (when no data to return)
24return []
25
26# ✅ Conditional return
27if should_process:
28 return [{"json": processed_data}]
29else:
30 return []
Incorrect Return Formats
1# ❌ WRONG: Dictionary without list wrapper
2return {
3 "json": {"field": value}
4}
5
6# ❌ WRONG: List without json wrapper
7return [{"field": value}]
8
9# ❌ WRONG: Plain string
10return "processed"
11
12# ❌ WRONG: Incomplete structure
13return [{"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
What’s NOT Available
1# ❌ NOT AVAILABLE - Will raise ModuleNotFoundError
2import requests # ❌ No
3import pandas # ❌ No
4import numpy # ❌ No
5import scipy # ❌ No
6from bs4 import BeautifulSoup # ❌ No
7import lxml # ❌ No
What IS Available (Standard Library)
1# ✅ AVAILABLE - Standard library only
2import json # ✅ JSON parsing
3import datetime # ✅ Date/time operations
4import re # ✅ Regular expressions
5import base64 # ✅ Base64 encoding/decoding
6import hashlib # ✅ Hashing functions
7import urllib.parse # ✅ URL parsing
8import math # ✅ Math functions
9import random # ✅ Random numbers
10import statistics # ✅ Statistical functions
Workarounds
Need HTTP requests?
- ✅ Use HTTP Request node before Code node
- ✅ Or switch to JavaScript and use
$helpers.httpRequest()
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, here are the most useful Python patterns:
1. Data Transformation
Transform all items with list comprehensions
1items = _input.all()
2
3return [
4 {
5 "json": {
6 "id": item["json"].get("id"),
7 "name": item["json"].get("name", "Unknown").upper(),
8 "processed": True
9 }
10 }
11 for item in items
12]
2. Filtering & Aggregation
Sum, filter, count with built-in functions
1items = _input.all()
2total = sum(item["json"].get("amount", 0) for item in items)
3valid_items = [item for item in items if item["json"].get("amount", 0) > 0]
4
5return [{
6 "json": {
7 "total": total,
8 "count": len(valid_items)
9 }
10}]
3. String Processing with Regex
Extract patterns from text
1import re
2
3items = _input.all()
4email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
5
6all_emails = []
7for item in items:
8 text = item["json"].get("text", "")
9 emails = re.findall(email_pattern, text)
10 all_emails.extend(emails)
11
12# Remove duplicates
13unique_emails = list(set(all_emails))
14
15return [{
16 "json": {
17 "emails": unique_emails,
18 "count": len(unique_emails)
19 }
20}]
4. Data Validation
Validate and clean data
1items = _input.all()
2validated = []
3
4for item in items:
5 data = item["json"]
6 errors = []
7
8 # Validate fields
9 if not data.get("email"):
10 errors.append("Email required")
11 if not data.get("name"):
12 errors.append("Name required")
13
14 validated.append({
15 "json": {
16 **data,
17 "valid": len(errors) == 0,
18 "errors": errors if errors else None
19 }
20 })
21
22return validated
5. Statistical Analysis
Calculate statistics with statistics module
1from statistics import mean, median, stdev
2
3items = _input.all()
4values = [item["json"].get("value", 0) for item in items if "value" in item["json"]]
5
6if values:
7 return [{
8 "json": {
9 "mean": mean(values),
10 "median": median(values),
11 "stdev": stdev(values) if len(values) > 1 else 0,
12 "min": min(values),
13 "max": max(values),
14 "count": len(values)
15 }
16 }]
17else:
18 return [{"json": {"error": "No values found"}}]
See: COMMON_PATTERNS.md for 10 detailed Python patterns
Error Prevention - Top 5 Mistakes
#1: Importing External Libraries (Python-Specific!)
1# ❌ WRONG: Trying to import external library
2import requests # ModuleNotFoundError!
3
4# ✅ CORRECT: Use HTTP Request node or JavaScript
5# Add HTTP Request node before Code node
6# OR switch to JavaScript and use $helpers.httpRequest()
#2: Empty Code or Missing Return
1# ❌ WRONG: No return statement
2items = _input.all()
3# Processing...
4# Forgot to return!
5
6# ✅ CORRECT: Always return data
7items = _input.all()
8# Processing...
9return [{"json": item["json"]} for item in items]
#3: Incorrect Return Format
1# ❌ WRONG: Returning dict instead of list
2return {"json": {"result": "success"}}
3
4# ✅ CORRECT: List wrapper required
5return [{"json": {"result": "success"}}]
#4: KeyError on Dictionary Access
1# ❌ WRONG: Direct access crashes if missing
2name = _json["user"]["name"] # KeyError!
3
4# ✅ CORRECT: Use .get() for safe access
5name = _json.get("user", {}).get("name", "Unknown")
#5: Webhook Body Nesting
1# ❌ WRONG: Direct access to webhook data
2email = _json["email"] # KeyError!
3
4# ✅ CORRECT: Webhook data under ["body"]
5email = _json["body"]["email"]
6
7# ✅ BETTER: Safe access with .get()
8email = _json.get("body", {}).get("email", "no-email")
See: ERROR_PATTERNS.md for comprehensive error guide
Standard Library Reference
Most Useful Modules
1# JSON operations
2import json
3data = json.loads(json_string)
4json_output = json.dumps({"key": "value"})
5
6# Date/time
7from datetime import datetime, timedelta
8now = datetime.now()
9tomorrow = now + timedelta(days=1)
10formatted = now.strftime("%Y-%m-%d")
11
12# Regular expressions
13import re
14matches = re.findall(r'\d+', text)
15cleaned = re.sub(r'[^\w\s]', '', text)
16
17# Base64 encoding
18import base64
19encoded = base64.b64encode(data).decode()
20decoded = base64.b64decode(encoded)
21
22# Hashing
23import hashlib
24hash_value = hashlib.sha256(text.encode()).hexdigest()
25
26# URL parsing
27import urllib.parse
28params = urllib.parse.urlencode({"key": "value"})
29parsed = urllib.parse.urlparse(url)
30
31# Statistics
32from statistics import mean, median, stdev
33average = mean([1, 2, 3, 4, 5])
See: STANDARD_LIBRARY.md for complete reference
Best Practices
1. Always Use .get() for Dictionary Access
1# ✅ SAFE: Won't crash if field missing
2value = item["json"].get("field", "default")
3
4# ❌ RISKY: Crashes if field doesn't exist
5value = item["json"]["field"]
2. Handle None/Null Values Explicitly
1# ✅ GOOD: Default to 0 if None
2amount = item["json"].get("amount") or 0
3
4# ✅ GOOD: Check for None explicitly
5text = item["json"].get("text")
6if text is None:
7 text = ""
3. Use List Comprehensions for Filtering
1# ✅ PYTHONIC: List comprehension
2valid = [item for item in items if item["json"].get("active")]
3
4# ❌ VERBOSE: Manual loop
5valid = []
6for item in items:
7 if item["json"].get("active"):
8 valid.append(item)
4. Return Consistent Structure
1# ✅ CONSISTENT: Always list with "json" key
2return [{"json": result}] # Single result
3return results # Multiple results (already formatted)
4return [] # No results
5. Debug with print() Statements
1# Debug statements appear in browser console (F12)
2items = _input.all()
3print(f"Processing {len(items)} items")
4print(f"First item: {items[0] if items else 'None'}")
When to Use Python vs JavaScript
Use Python When:
- ✅ You need
statisticsmodule for statistical operations - ✅ You’re significantly more comfortable with Python syntax
- ✅ Your logic maps well to list comprehensions
- ✅ You need specific standard library functions
Use JavaScript When:
- ✅ You need HTTP requests ($helpers.httpRequest())
- ✅ You need advanced date/time (DateTime/Luxon)
- ✅ You want better n8n integration
- ✅ For 95% of use cases (recommended)
Consider Other Nodes When:
- ❌ Simple field mapping → Use Set node
- ❌ Basic filtering → Use Filter node
- ❌ Simple conditionals → Use IF or Switch node
- ❌ HTTP requests only → Use HTTP Request node
Integration with Other Skills
Works With:
n8n Expression Syntax:
- Expressions use
{{ }}syntax in other nodes - Code nodes use Python directly (no
{{ }}) - When to use expressions vs code
n8n MCP Tools Expert:
- How to find Code node:
search_nodes({query: "code"}) - Get configuration help:
get_node_essentials("nodes-base.code") - Validate code:
validate_node_operation()
n8n Node Configuration:
- Mode selection (All Items vs Each Item)
- Language selection (Python vs JavaScript)
- Understanding property dependencies
n8n Workflow Patterns:
- Code nodes in transformation step
- When to use Python vs JavaScript in patterns
n8n Validation Expert:
- Validate Code node configuration
- Handle validation errors
- Auto-fix common issues
n8n Code JavaScript:
- When to use JavaScript instead
- Comparison of JavaScript vs Python features
- Migration from Python to JavaScript
Quick Reference Checklist
Before deploying Python Code nodes, verify:
- Considered JavaScript first - Using Python only when necessary
- Code is not empty - Must have meaningful logic
- Return statement exists - Must return list of dictionaries
- Proper return format - Each item:
{"json": {...}} - Data access correct - Using
_input.all(),_input.first(), or_input.item - No external imports - Only standard library (json, datetime, re, etc.)
- Safe dictionary access - Using
.get()to avoid KeyError - Webhook data - Access via
["body"]if from webhook - Mode selection - “All Items” for most cases
- Output consistent - All code paths return same structure
Additional Resources
Related Files
- DATA_ACCESS.md - Comprehensive Python data access patterns
- COMMON_PATTERNS.md - 10 Python patterns for n8n
- ERROR_PATTERNS.md - Top 5 errors and solutions
- STANDARD_LIBRARY.md - Complete standard library reference
n8n Documentation
- Code Node Guide: https://docs.n8n.io/code/code-node/
- Python in n8n: https://docs.n8n.io/code/builtin/python-modules/
Ready to write Python in n8n Code nodes - but consider JavaScript first! Use Python for specific needs, reference the error patterns guide to avoid common mistakes, and leverage the standard library effectively.
What Users Are Saying
Real feedback from the community
Environment Matrix
Dependencies
Framework Support
Context Window
Security & Privacy
Information
- Author
- davila7
- Updated
- 2026-01-30
- Category
- scripting
Related Skills
N8N Code Python
Write Python code in n8n Code nodes. Use when writing Python in n8n, using _input/_json/_node …
View Details →N8N Code Javascript
Write JavaScript code in n8n Code nodes. Use when writing JavaScript in n8n, using …
View Details →N8N Code Javascript
Write JavaScript code in n8n Code nodes. Use when writing JavaScript in n8n, using …
View Details →