---
name: n8n-code-python
description: "สกิลสำหรับ N8n โค้ด Python ใช้เมื่อต้องการแนวทาง ขั้นตอน Template หรือคำแนะนำเชิงปฏิบัติสำหรับงาน DevOps, Cloud, Infrastructure, Automation, Deployment และ Monitoring ในหัวข้อนี้"
---

# N8n โค้ด Python

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

```python
# N8n โค้ด Python
items = _input.all()

# N8n โค้ด Python
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)

```python
# N8n โค้ด Python
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)

```python
# N8n โค้ด Python
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
# N8n โค้ด Python
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
# N8n โค้ด Python
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

### Pattern 1: _input.all() - Most Common

**Use when**: Processing arrays, batch operations, aggregations

```python
# N8n โค้ด Python
all_items = _input.all()

# N8n โค้ด Python
valid = [item for item in all_items if item["JSON"].get("status") == "active"]

processed = []
for item in valid:
    processed.append({
        "JSON": {
            "id": item["JSON"]["id"],
            "name": item["JSON"]["name"]
        }
    })

return processed
```

### Pattern 2: _input.first() - Very Common

**Use when**: Working with single objects, API responses

```python
# N8n โค้ด Python
first_item = _input.first()
data = first_item["JSON"]

return [{
    "JSON": {
        "result": process_data(data),
        "processed_at": datetime.now().isoformat()
    }
}]
```

### Pattern 3: _input.item - Each Item Mode Only

**Use when**: In "Run Once for Each Item" mode

```python
# N8n โค้ด Python
current_item = _input.item

return [{
    "JSON": {
        **current_item["JSON"],
        "item_processed": True
    }
}]
```

### Pattern 4: _node - Reference Other Nodes

**Use when**: Need data from specific nodes in workflow

```python
# N8n โค้ด Python
webhook_data = _node["Webhook"]["JSON"]
http_data = _node["HTTP Request"]["JSON"]

return [{
    "JSON": {
        "combined": {
            "webhook": webhook_data,
            "API": http_data
        }
    }
}]
```

**See**: [DATA_ACCESS.md](DATA_ACCESS.md) for comprehensive guide

---

## Critical: Webhook Data Structure

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

```python
# N8n โค้ด Python
name = _JSON["name"]
email = _JSON["email"]

# N8n โค้ด Python
name = _JSON["body"]["name"]
email = _JSON["body"]["email"]

# N8n โค้ด Python
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](DATA_ACCESS.md) for full webhook structure details

---

## Return Format Requirements

**CRITICAL RULE**: Always return list of dictionaries with `"JSON"` key

### Correct Return Formats

```python
# N8n โค้ด Python
return [{
    "JSON": {
        "field1": value1,
        "field2": value2
    }
}]

# N8n โค้ด Python
return [
    {"JSON": {"id": 1, "data": "first"}},
    {"JSON": {"id": 2, "data": "second"}}
]

# N8n โค้ด Python
transformed = [
    {"JSON": {"id": item["JSON"]["id"], "processed": True}}
    for item in _input.all()
    if item["JSON"].get("valid")
]
return transformed

# N8n โค้ด Python
return []

# N8n โค้ด Python
if should_process:
    return [{"JSON": processed_data}]
else:
    return []
```

### Incorrect Return Formats

```python
# N8n โค้ด Python
return {
    "JSON": {"field": value}
}

# N8n โค้ด Python
return [{"field": value}]

# N8n โค้ด Python
return "processed"

# N8n โค้ด Python
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](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

```python
# N8n โค้ด Python
import requests  # ❌ No
import pandas  # ❌ No
import numpy  # ❌ No
import scipy  # ❌ No
from bs4 import BeautifulSoup  # ❌ No
import lxML  # ❌ No
```

### What IS Available (Standard Library)

```python
# N8n โค้ด Python
import JSON  # ✅ JSON parsing
import datetime  # ✅ Date/time operations
import re  # ✅ Regular expressions
import base64  # ✅ Base64 encoding/decoding
import hashlib  # ✅ Hashing functions
import urllib.parse  # ✅ URL parsing
import math  # ✅ Math functions
import random  # ✅ Random numbers
import 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](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

```python
items = _input.all()

return [
    {
        "JSON": {
            "id": item["JSON"].get("id"),
            "name": item["JSON"].get("name", "Unknown").upper(),
            "processed": True
        }
    }
    for item in items
]
```

### 2. Filtering & Aggregation
Sum, filter, count with built-in functions

```python
items = _input.all()
total = sum(item["JSON"].get("amount", 0) for item in items)
valid_items = [item for item in items if item["JSON"].get("amount", 0) > 0]

return [{
    "JSON": {
        "total": total,
        "count": len(valid_items)
    }
}]
```

### 3. String Processing with Regex
Extract patterns from text

```python
import re

items = _input.all()
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

all_emails = []
for item in items:
    text = item["JSON"].get("text", "")
    emails = re.findall(email_pattern, text)
    all_emails.extend(emails)

# N8n โค้ด Python
unique_emails = list(set(all_emails))

return [{
    "JSON": {
        "emails": unique_emails,
        "count": len(unique_emails)
    }
}]
```

### 4. Data Validation
Validate and clean data

```python
items = _input.all()
validated = []

for item in items:
    data = item["JSON"]
    errors = []

    # Validate fields
    if not data.get("email"):
        errors.append("Email required")
    if not data.get("name"):
        errors.append("Name required")

    validated.append({
        "JSON": {
            **data,
            "valid": len(errors) == 0,
            "errors": errors if errors else None
        }
    })

return validated
```

### 5. Statistical Analysis
Calculate statistics with statistics module

```python
from statistics import mean, median, stdev

items = _input.all()
values = [item["JSON"].get("value", 0) for item in items if "value" in item["JSON"]]

if values:
    return [{
        "JSON": {
            "mean": mean(values),
            "median": median(values),
            "stdev": stdev(values) if len(values) > 1 else 0,
            "min": min(values),
            "max": max(values),
            "count": len(values)
        }
    }]
else:
    return [{"JSON": {"error": "No values found"}}]
```

**See**: [COMMON_PATTERNS.md](COMMON_PATTERNS.md) for 10 detailed Python patterns

---

## Error Prevention - Top 5 Mistakes

### #1: Importing External Libraries (Python-Specific!)

```python
# N8n โค้ด Python
import requests  # ModuleNotFoundError!

# N8n โค้ด Python
# N8n โค้ด Python
# N8n โค้ด Python
```

### #2: Empty Code or Missing Return

```python
# N8n โค้ด Python
items = _input.all()
# N8n โค้ด Python
# N8n โค้ด Python

# N8n โค้ด Python
items = _input.all()
# N8n โค้ด Python
return [{"JSON": item["JSON"]} for item in items]
```

### #3: Incorrect Return Format

```python
# N8n โค้ด Python
return {"JSON": {"result": "success"}}

# N8n โค้ด Python
return [{"JSON": {"result": "success"}}]
```

### #4: KeyError on Dictionary Access

```python
# N8n โค้ด Python
name = _JSON["user"]["name"]  # KeyError!

# N8n โค้ด Python
name = _JSON.get("user", {}).get("name", "Unknown")
```

### #5: Webhook Body Nesting

```python
# N8n โค้ด Python
email = _JSON["email"]  # KeyError!

# N8n โค้ด Python
email = _JSON["body"]["email"]

# N8n โค้ด Python
email = _JSON.get("body", {}).get("email", "no-email")
```

**See**: [ERROR_PATTERNS.md](ERROR_PATTERNS.md) for comprehensive error guide

---

## Standard Library Reference

### Most Useful Modules

```python
# N8n โค้ด Python
import JSON
data = JSON.loads(json_string)
json_output = JSON.dumps({"key": "value"})

# N8n โค้ด Python
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
formatted = now.strftime("%Y-%m-%d")

# N8n โค้ด Python
import re
matches = re.findall(r'\d+', text)
cleaned = re.sub(r'[^\w\s]', '', text)

# N8n โค้ด Python
import base64
encoded = base64.b64encode(data).decode()
decoded = base64.b64decode(encoded)

# N8n โค้ด Python
import hashlib
hash_value = hashlib.sha256(text.encode()).hexdigest()

# N8n โค้ด Python
import urllib.parse
params = urllib.parse.urlencode({"key": "value"})
parsed = urllib.parse.urlparse(url)

# N8n โค้ด Python
from statistics import mean, median, stdev
average = mean([1, 2, 3, 4, 5])
```

**See**: [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md) for complete reference

---

## Best Practices

### 1. Always Use .get() for Dictionary Access

```python
# N8n โค้ด Python
value = item["JSON"].get("field", "default")

# N8n โค้ด Python
value = item["JSON"]["field"]
```

### 2. Handle None/Null Values Explicitly

```python
# N8n โค้ด Python
amount = item["JSON"].get("amount") or 0

# N8n โค้ด Python
text = item["JSON"].get("text")
if text is None:
    text = ""
```

### 3. Use List Comprehensions for Filtering

```python
# N8n โค้ด Python
valid = [item for item in items if item["JSON"].get("active")]

# N8n โค้ด Python
valid = []
for item in items:
    if item["JSON"].get("active"):
        valid.append(item)
```

### 4. Return Consistent Structure

```python
# N8n โค้ด Python
return [{"JSON": result}]  # Single result
return results  # Multiple results (already formatted)
return []  # No results
```

### 5. Debug with print() Statements

```python
# N8n โค้ด Python
items = _input.all()
print(f"Processing {len(items)} items")
print(f"First item: {items[0] if items else 'None'}")
```

---

## When to Use Python vs JavaScript

### Use Python When:
- ✅ You need `statistics` module 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](DATA_ACCESS.md) - Comprehensive Python data access patterns
- [COMMON_PATTERNS.md](COMMON_PATTERNS.md) - 10 Python patterns for n8n
- [ERROR_PATTERNS.md](ERROR_PATTERNS.md) - Top 5 errors and solutions
- [STANDARD_LIBRARY.md](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.
