[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7F3JJYHW8G6Z6E7KWD90VC4":3,"skill-same:01M7F3JJYHW8G6Z6E7KWD90VC4":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M7F3JJYHW8G6Z6E7KWD90VC4","n8n-code-python",null,"Write Python code in n8n Code nodes. Use when writing Python in n8n, using _input\u002F_json\u002F_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\u002Fn8n-nodes-langchain.toolCode), use the n8n-code-tool skill instead (input is _query, return must be a string).","26BB\u002Fagent-fleet-os","26BB","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F113676969?v=4","01M7F3AVX9MTTAHCYTANRGEE52","Bhushan Vijay Bhosale","01M7F3AVY15DJBX1CE4H25P52T",0,"MIT","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002FN8N agent\u002Fplaybooks\u002Fn8n-code-python\u002FSKILL.md",[],[],"2026-11-16 10:05:34",false,"---\nname: n8n-code-python\ndescription: Write Python code in n8n Code nodes. Use when writing Python in n8n, using _input\u002F_json\u002F_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\u002Fn8n-nodes-langchain.toolCode), use the n8n-code-tool skill instead (input is _query, return must be a string).\n---\n\n# Python Code Node (Beta)\n\nExpert guidance for writing Python code in n8n Code nodes.\n\n---\n\n## ⚠️ Important: JavaScript First\n\n**Recommendation**: Use **JavaScript for 95% of use cases**. Only use Python when:\n- You need specific Python standard library functions\n- You're significantly more comfortable with Python syntax\n- You're doing data transformations better suited to Python\n\n**Why JavaScript is preferred:**\n- Full n8n helper functions (`this.helpers.httpRequest`, etc.)\n- Luxon DateTime library for advanced date\u002Ftime operations\n- No external library limitations\n- Better n8n documentation and community support\n\n---\n\n## Quick Start\n\n```python\n# Basic template for Python Code nodes\nitems = _input.all()\n\n# Process data\nprocessed = []\nfor item in items:\n    processed.append({\n        \"json\": {\n            **item[\"json\"],\n            \"processed\": True,\n            \"timestamp\": datetime.now().isoformat()\n        }\n    })\n\nreturn processed\n```\n\n### Essential Rules\n\n1. **Consider JavaScript first** - Use Python only when necessary\n2. **Access data**: `_input.all()`, `_input.first()`, or `_input.item`\n3. **CRITICAL**: Must return `[{\"json\": {...}}]` format\n4. **CRITICAL**: Webhook data is under `_json[\"body\"]` (not `_json` directly)\n5. **CRITICAL LIMITATION**: **No external libraries** (no requests, pandas, numpy)\n6. **Standard library only**: json, datetime, re, base64, hashlib, urllib.parse, math, random, statistics\n\n---\n\n## Mode Selection Guide\n\nSame as JavaScript - choose based on your use case:\n\n### Run Once for All Items (Recommended - Default)\n\n**Use this mode for:** 95% of use cases\n\n- **How it works**: Code executes **once** regardless of input count\n- **Data access**: `_input.all()` or `_items` array (Native mode)\n- **Best for**: Aggregation, filtering, batch processing, transformations\n- **Performance**: Faster for multiple items (single execution)\n\n```python\n# Example: Calculate total from all items\nall_items = _input.all()\ntotal = sum(item[\"json\"].get(\"amount\", 0) for item in all_items)\n\nreturn [{\n    \"json\": {\n        \"total\": total,\n        \"count\": len(all_items),\n        \"average\": total \u002F len(all_items) if all_items else 0\n    }\n}]\n```\n\n### Run Once for Each Item\n\n**Use this mode for:** Specialized cases only\n\n- **How it works**: Code executes **separately** for each input item\n- **Data access**: `_input.item` or `_item` (Native mode)\n- **Best for**: Item-specific logic, independent operations, per-item validation\n- **Performance**: Slower for large datasets (multiple executions)\n\n```python\n# Example: Add processing timestamp to each item\nitem = _input.item\n\nreturn [{\n    \"json\": {\n        **item[\"json\"],\n        \"processed\": True,\n        \"processed_at\": datetime.now().isoformat()\n    }\n}]\n```\n\n---\n\n## Python Modes: Beta vs Native\n\nn8n offers two Python execution modes:\n\n### Python (Beta) - Recommended\n- **Use**: `_input`, `_json`, `_node` helper syntax\n- **Best for**: Most Python use cases\n- **Helpers available**: `_now`, `_today`, `_jmespath()`\n- **Import**: `from datetime import datetime`\n\n```python\n# Python (Beta) example\nitems = _input.all()\nnow = _now  # Built-in datetime object\n\nreturn [{\n    \"json\": {\n        \"count\": len(items),\n        \"timestamp\": now.isoformat()\n    }\n}]\n```\n\n### Python (Native) (Beta)\n- **Use**: `_items`, `_item` variables only\n- **No helpers**: No `_input`, `_now`, etc.\n- **More limited**: Standard Python only\n- **Use when**: Need pure Python without n8n helpers\n\n```python\n# Python (Native) example\nprocessed = []\n\nfor item in _items:\n    processed.append({\n        \"json\": {\n            \"id\": item[\"json\"].get(\"id\"),\n            \"processed\": True\n        }\n    })\n\nreturn processed\n```\n\n**Recommendation**: Use **Python (Beta)** for better n8n integration.\n\n---\n\n## Data Access Patterns\n\nAccess input data through underscore-prefixed variables. Each item is a dict shaped `{\"json\": {...}}`, so the actual fields live under `[\"json\"]`.\n\n```python\n# Pattern 1: _input.all() - Most common. Arrays, batch ops, aggregations\nall_items = _input.all()            # list of {\"json\": {...}} dicts\n\n# Pattern 2: _input.first() - Very common. Single objects, API responses\ndata = _input.first()[\"json\"]       # built-in safety vs all_items[0]\n\n# Pattern 3: _input.item - \"Run Once for Each Item\" mode ONLY\ncurrent = _input.item[\"json\"]       # None\u002Ferror in All Items mode\n\n# Pattern 4: _node - Reference a specific named node\nwebhook_data = _node[\"Webhook\"][\"json\"]\nhttp_data = _node[\"HTTP Request\"][\"json\"]\n```\n\n**See**: [DATA_ACCESS.md](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.\n\n---\n\n## Critical: Webhook Data Structure\n\n**MOST COMMON MISTAKE**: Webhook data is nested under `[\"body\"]`\n\n```python\n# ❌ WRONG - Will raise KeyError\nname = _json[\"name\"]\nemail = _json[\"email\"]\n\n# ✅ CORRECT - Webhook data is under [\"body\"]\nname = _json[\"body\"][\"name\"]\nemail = _json[\"body\"][\"email\"]\n\n# ✅ SAFER - Use .get() for safe access\nwebhook_data = _json.get(\"body\", {})\nname = webhook_data.get(\"name\")\n```\n\n**Why**: Webhook node wraps all request data under `body` property. This includes POST data, query parameters, and JSON payloads.\n\n**See**: [DATA_ACCESS.md](DATA_ACCESS.md) for full webhook structure details\n\n---\n\n## Return Format Requirements\n\n**CRITICAL RULE**: Always return list of dictionaries with `\"json\"` key\n\n### Correct Return Formats\n\n```python\n# ✅ Single result\nreturn [{\n    \"json\": {\n        \"field1\": value1,\n        \"field2\": value2\n    }\n}]\n\n# ✅ Multiple results\nreturn [\n    {\"json\": {\"id\": 1, \"data\": \"first\"}},\n    {\"json\": {\"id\": 2, \"data\": \"second\"}}\n]\n\n# ✅ List comprehension\ntransformed = [\n    {\"json\": {\"id\": item[\"json\"][\"id\"], \"processed\": True}}\n    for item in _input.all()\n    if item[\"json\"].get(\"valid\")\n]\nreturn transformed\n\n# ✅ Empty result (when no data to return)\nreturn []\n\n# ✅ Conditional return\nif should_process:\n    return [{\"json\": processed_data}]\nelse:\n    return []\n```\n\n### Incorrect Return Formats\n\n```python\n# ❌ WRONG: Dictionary without list wrapper\nreturn {\n    \"json\": {\"field\": value}\n}\n\n# ❌ WRONG: List without json wrapper\nreturn [{\"field\": value}]\n\n# ❌ WRONG: Plain string\nreturn \"processed\"\n\n# ❌ WRONG: Incomplete structure\nreturn [{\"data\": value}]  # Should be {\"json\": value}\n```\n\n**Why it matters**: Next nodes expect list format. Incorrect format causes workflow execution to fail.\n\n**See**: [ERROR_PATTERNS.md](ERROR_PATTERNS.md) #2 for detailed error solutions\n\n---\n\n## Critical Limitation: No External Libraries\n\n**MOST IMPORTANT PYTHON LIMITATION**: Cannot import external packages on default installs.\n\n> **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.\n\n**❌ NOT available** (raise `ModuleNotFoundError`): `requests`, `pandas`, `numpy`, `scipy`, `bs4`\u002FBeautifulSoup, `lxml`.\n\n**✅ Available** (standard library only): `json`, `datetime`, `re`, `base64`, `hashlib`, `urllib.parse`, `math`, `random`, `statistics`.\n\n### Workarounds\n\n**Need HTTP requests?**\n- ✅ Use **HTTP Request node** before Code node\n- ✅ Or switch to **JavaScript** and use `this.helpers.httpRequest()` (the bare `$helpers` global is undefined in the task-runner sandbox)\n\n**Need data analysis (pandas\u002Fnumpy)?**\n- ✅ Use Python **statistics** module for basic stats\n- ✅ Or switch to **JavaScript** for most operations\n- ✅ Manual calculations with lists and dictionaries\n\n**Need web scraping (BeautifulSoup)?**\n- ✅ Use **HTTP Request node** + **HTML Extract node**\n- ✅ Or switch to **JavaScript** with regex\u002Fstring methods\n\n**See**: [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md) for complete reference\n\n---\n\n## Common Patterns Overview\n\nBased on production workflows, the most useful Python patterns are:\n\n1. **Data Transformation** - Transform all items with list comprehensions\n2. **Filtering & Aggregation** - Sum, filter, count with built-in functions\n3. **String Processing with Regex** - Extract patterns from text with `re`\n4. **Data Validation** - Validate and clean data, attach error lists\n5. **Statistical Analysis** - Calculate mean\u002Fmedian\u002Fstdev with the `statistics` module\n\nCopy-ready snippets for all five live in [COMMON_PATTERNS.md](COMMON_PATTERNS.md#quick-pattern-snippets), alongside 10 fully detailed production patterns (multi-source aggregation, markdown parsing, JSON comparison, CRM normalization, dictionary lookup, top-N filtering, and more).\n\n---\n\n## Error Prevention - Top 5 Mistakes\n\n1. **Importing external libraries** (Python-specific) → `import requests` raises `ModuleNotFoundError`. Use the HTTP Request node or JavaScript instead.\n2. **Empty code or missing return** → every path must end with `return [{\"json\": ...}]`.\n3. **Incorrect return format** → wrap in a list: `{\"json\": {...}}` becomes `[{\"json\": {...}}]`.\n4. **KeyError on dictionary access** → use `.get()`: `_json.get(\"user\", {}).get(\"name\", \"Unknown\")`.\n5. **Webhook body nesting** → read via `[\"body\"]`: `_json.get(\"body\", {}).get(\"email\", \"no-email\")`.\n\n**See**: [ERROR_PATTERNS.md](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.\n\n---\n\n## Standard Library Reference\n\nMost useful modules: `json` (parse\u002Fgenerate), `datetime` (dates + `timedelta`), `re` (regex), `base64` (encode\u002Fdecode), `hashlib` (hashing), `urllib.parse` (URL ops), and `statistics` (mean\u002Fmedian\u002Fstdev). Also available: `math`, `random`, `collections`, `itertools`, `functools`.\n\nFor a condensed cheat sheet plus full per-module examples, see [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md#quick-reference-most-useful-modules).\n\n---\n\n## Best Practices\n\n### 1. Always Use .get() for Dictionary Access\n\n```python\n# ✅ SAFE: Won't crash if field missing\nvalue = item[\"json\"].get(\"field\", \"default\")\n\n# ❌ RISKY: Crashes if field doesn't exist\nvalue = item[\"json\"][\"field\"]\n```\n\n### 2. Handle None\u002FNull Values Explicitly\n\n```python\n# ✅ GOOD: Default to 0 if None\namount = item[\"json\"].get(\"amount\") or 0\n\n# ✅ GOOD: Check for None explicitly\ntext = item[\"json\"].get(\"text\")\nif text is None:\n    text = \"\"\n```\n\n### 3. Use List Comprehensions for Filtering\n\n```python\n# ✅ PYTHONIC: List comprehension\nvalid = [item for item in items if item[\"json\"].get(\"active\")]\n\n# ❌ VERBOSE: Manual loop\nvalid = []\nfor item in items:\n    if item[\"json\"].get(\"active\"):\n        valid.append(item)\n```\n\n### 4. Return Consistent Structure\n\n```python\n# ✅ CONSISTENT: Always list with \"json\" key\nreturn [{\"json\": result}]  # Single result\nreturn results  # Multiple results (already formatted)\nreturn []  # No results\n```\n\n### 5. Debug with print() Statements\n\n```python\n# Debug statements appear in browser console (F12)\nitems = _input.all()\nprint(f\"Processing {len(items)} items\")\nprint(f\"First item: {items[0] if items else 'None'}\")\n```\n\n---\n\n## Production Gotchas\n\n### SplitInBatches Loop Semantics\n\nThe SplitInBatches node has two outputs:\n- `main[0]` = **done** — fires ONCE after all batches complete\n- `main[1]` = **each batch** — fires for every batch (the loop body)\n\nAlways add a **Limit 1** node after the done output.\n\n### Correct Node Reference Syntax\n\n```python\n# ❌ WRONG\ndata = _node['HTTP Request']['json']\n\n# ✅ CORRECT - call .first() then access json\ndata = _node['HTTP Request'].first()['json']\n```\n\n### Cross-Iteration Data Not Available in Python\n\n`$getWorkflowStaticData('global')` may not be available in Python Beta mode. If you need to accumulate data across SplitInBatches iterations, use a JavaScript Code node for the accumulation logic instead.\n\n---\n\n## When to Use Python vs JavaScript\n\n### Use Python When:\n- ✅ You need `statistics` module for statistical operations\n- ✅ You're significantly more comfortable with Python syntax\n- ✅ Your logic maps well to list comprehensions\n- ✅ You need specific standard library functions\n\n### Use JavaScript When:\n- ✅ You need HTTP requests (`this.helpers.httpRequest()`)\n- ✅ You need advanced date\u002Ftime (DateTime\u002FLuxon)\n- ✅ You want better n8n integration\n- ✅ **For 95% of use cases** (recommended)\n\n### Consider Other Nodes When:\n- ❌ Simple field mapping → Use **Set** node\n- ❌ Basic filtering → Use **Filter** node\n- ❌ Simple conditionals → Use **IF** or **Switch** node\n- ❌ HTTP requests only → Use **HTTP Request** node\n\n---\n\n## Integration with Other Skills\n\n### Works With:\n\n**n8n Expression Syntax**:\n- Expressions use `{{ }}` syntax in other nodes\n- Code nodes use Python directly (no `{{ }}`)\n- When to use expressions vs code\n\n**n8n MCP Tools Expert**:\n- How to find Code node: `search_nodes({query: \"code\"})`\n- Get configuration help: `get_node({nodeType: \"nodes-base.code\"})`\n- Validate code: `validate_node({nodeType: \"nodes-base.code\", config: {...}})`\n\n**n8n Node Configuration**:\n- Mode selection (All Items vs Each Item)\n- Language selection (Python vs JavaScript)\n- Understanding property dependencies\n\n**n8n Workflow Patterns**:\n- Code nodes in transformation step\n- When to use Python vs JavaScript in patterns\n\n**n8n Validation Expert**:\n- Validate Code node configuration\n- Handle validation errors\n- Auto-fix common issues\n\n**n8n Code JavaScript**:\n- When to use JavaScript instead\n- Comparison of JavaScript vs Python features\n- Migration from Python to JavaScript\n\n---\n\n## Quick Reference Checklist\n\nBefore deploying Python Code nodes, verify:\n\n- [ ] **Considered JavaScript first** - Using Python only when necessary\n- [ ] **Code is not empty** - Must have meaningful logic\n- [ ] **Return statement exists** - Must return list of dictionaries\n- [ ] **Proper return format** - Each item: `{\"json\": {...}}`\n- [ ] **Data access correct** - Using `_input.all()`, `_input.first()`, or `_input.item`\n- [ ] **No external imports** - Only standard library (json, datetime, re, etc.)\n- [ ] **Safe dictionary access** - Using `.get()` to avoid KeyError\n- [ ] **Webhook data** - Access via `[\"body\"]` if from webhook\n- [ ] **Mode selection** - \"All Items\" for most cases\n- [ ] **Output consistent** - All code paths return same structure\n\n---\n\n## Additional Resources\n\n### Related Files\n- [DATA_ACCESS.md](DATA_ACCESS.md) - Comprehensive Python data access patterns\n- [COMMON_PATTERNS.md](COMMON_PATTERNS.md) - 10 Python patterns for n8n\n- [ERROR_PATTERNS.md](ERROR_PATTERNS.md) - Top 5 errors and solutions\n- [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md) - Complete standard library reference\n\n### n8n Documentation\n- Code Node Guide: https:\u002F\u002Fdocs.n8n.io\u002Fcode\u002Fcode-node\u002F\n- Python in n8n: https:\u002F\u002Fdocs.n8n.io\u002Fcode\u002Fbuiltin\u002Fpython-modules\u002F\n\n---\n\n**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.\n","# Python Code Node (Beta)\n\nExpert guidance for writing Python code in n8n Code nodes.\n\n---\n\n## ⚠️ Important: JavaScript First\n\n**Recommendation**: Use **JavaScript for 95% of use cases**. Only use Python when:\n- You need specific Python standard library functions\n- You're significantly more comfortable with Python syntax\n- You're doing data transformations better suited to Python\n\n**Why JavaScript is preferred:**\n- Full n8n helper functions (`this.helpers.httpRequest`, etc.)\n- Luxon DateTime library for advanced date\u002Ftime operations\n- No external library limitations\n- Better n8n documentation and community support\n\n---\n\n## Quick Start\n\n```python\n# Basic template for Python Code nodes\nitems = _input.all()\n\n# Process data\nprocessed = []\nfor item in items:\n    processed.append({\n        \"json\": {\n            **item[\"json\"],\n            \"processed\": True,\n            \"timestamp\": datetime.now().isoformat()\n        }\n    })\n\nreturn processed\n```\n\n### Essential Rules\n\n1. **Consider JavaScript first** - Use Python only when necessary\n2. **Access data**: `_input.all()`, `_input.first()`, or `_input.item`\n3. **CRITICAL**: Must return `[{\"json\": {...}}]` format\n4. **CRITICAL**: Webhook data is under `_json[\"body\"]` (not `_json` directly)\n5. **CRITICAL LIMITATION**: **No external libraries** (no requests, pandas, numpy)\n6. **Standard library only**: json, datetime, re, base64, hashlib, urllib.parse, math, random, statistics\n\n---\n\n## Mode Selection Guide\n\nSame as JavaScript - choose based on your use case:\n\n### Run Once for All Items (Recommended - Default)\n\n**Use this mode for:** 95% of use cases\n\n- **How it works**: Code executes **once** regardless of input count\n- **Data access**: `_input.all()` or `_items` array (Native mode)\n- **Best for**: Aggregation, filtering, batch processing, transformations\n- **Performance**: Faster for multiple items (single execution)\n\n```python\n# Example: Calculate total from all items\nall_items = _input.all()\ntotal = sum(item[\"json\"].get(\"amount\", 0) for item in all_items)\n\nreturn [{\n    \"json\": {\n        \"total\": total,\n        \"count\": len(all_items),\n        \"average\": total \u002F len(all_items) if all_items else 0\n    }\n}]\n```\n\n### Run Once for Each Item\n\n**Use this mode for:** Specialized cases only\n\n- **How it works**: Code executes **separately** for each input item\n- **Data access**: `_input.item` or `_item` (Native mode)\n- **Best for**: Item-specific logic, independent operations, per-item validation\n- **Performance**: Slower for large datasets (multiple executions)\n\n```python\n# Example: Add processing timestamp to each item\nitem = _input.item\n\nreturn [{\n    \"json\": {\n        **item[\"json\"],\n        \"processed\": True,\n        \"processed_at\": datetime.now().isoformat()\n    }\n}]\n```\n\n---\n\n## Python Modes: Beta vs Native\n\nn8n offers two Python execution modes:\n\n### Python (Beta) - Recommended\n- **Use**: `_input`, `_json`, `_node` helper syntax\n- **Best for**: Most Python use cases\n- **Helpers available**: `_now`, `_today`, `_jmespath()`\n- **Import**: `from datetime import datetime`\n\n```python\n# Python (Beta) example\nitems = _input.all()\nnow = _now  # Built-in datetime object\n\nreturn [{\n    \"json\": {\n        \"count\": len(items),\n        \"timestamp\": now.isoformat()\n    }\n}]\n```\n\n### Python (Native) (Beta)\n- **Use**: `_items`, `_item` variables only\n- **No helpers**: No `_input`, `_now`, etc.\n- **More limited**: Standard Python only\n- **Use when**: Need pure Python without n8n helpers\n\n```python\n# Python (Native) example\nprocessed = []\n\nfor item in _items:\n    processed.append({\n        \"json\": {\n            \"id\": item[\"json\"].get(\"id\"),\n            \"processed\": True\n        }\n    })\n\nreturn processed\n```\n\n**Recommendation**: Use **Python (Beta)** for better n8n integration.\n\n---\n\n## Data Access Patterns\n\nAccess input data through underscore-prefixed variables. Each item is a dict shaped `{\"json\": {...}}`, so the actual fields live under `[\"json\"]`.\n\n```python\n# Pattern 1: _input.all() - Most common. Arrays, batch ops, aggregations\nall_items = _input.all()            # list of {\"json\": {...}} dicts\n\n# Pattern 2: _input.first() - Very common. Single objects, API responses\ndata = _input.first()[\"json\"]       # built-in safety vs all_items[0]\n\n# Pattern 3: _input.item - \"Run Once for Each Item\" mode ONLY\ncurrent = _input.item[\"json\"]       # None\u002Ferror in All Items mode\n\n# Pattern 4: _node - Reference a specific named node\nwebhook_data = _node[\"Webhook\"][\"json\"]\nhttp_data = _node[\"HTTP Request\"][\"json\"]\n```\n\n**See**: [DATA_ACCESS.md](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.\n\n---\n\n## Critical: Webhook Data Structure\n\n**MOST COMMON MISTAKE**: Webhook data is nested under `[\"body\"]`\n\n```python\n# ❌ WRONG - Will raise KeyError\nname = _json[\"name\"]\nemail = _json[\"email\"]\n\n# ✅ CORRECT - Webhook data is under [\"body\"]\nname = _json[\"body\"][\"name\"]\nemail = _json[\"body\"][\"email\"]\n\n# ✅ SAFER - Use .get() for safe access\nwebhook_data = _json.get(\"body\", {})\nname = webhook_data.get(\"name\")\n```\n\n**Why**: Webhook node wraps all request data under `body` property. This includes POST data, query parameters, and JSON payloads.\n\n**See**: [DATA_ACCESS.md](DATA_ACCESS.md) for full webhook structure details\n\n---\n\n## Return Format Requirements\n\n**CRITICAL RULE**: Always return list of dictionaries with `\"json\"` key\n\n### Correct Return Formats\n\n```python\n# ✅ Single result\nreturn [{\n    \"json\": {\n        \"field1\": value1,\n        \"field2\": value2\n    }\n}]\n\n# ✅ Multiple results\nreturn [\n    {\"json\": {\"id\": 1, \"data\": \"first\"}},\n    {\"json\": {\"id\": 2, \"data\": \"second\"}}\n]\n\n# ✅ List comprehension\ntransformed = [\n    {\"json\": {\"id\": item[\"json\"][\"id\"], \"processed\": True}}\n    for item in _input.all()\n    if item[\"json\"].get(\"valid\")\n]\nreturn transformed\n\n# ✅ Empty result (when no data to return)\nreturn []\n\n# ✅ Conditional return\nif should_process:\n    return [{\"json\": processed_data}]\nelse:\n    return []\n```\n\n### Incorrect Return Formats\n\n```python\n# ❌ WRONG: Dictionary without list wrapper\nreturn {\n    \"json\": {\"field\": value}\n}\n\n# ❌ WRONG: List without json wrapper\nreturn [{\"field\": value}]\n\n# ❌ WRONG: Plain string\nreturn \"processed\"\n\n# ❌ WRONG: Incomplete structure\nreturn [{\"data\": value}]  # Should be {\"json\": value}\n```\n\n**Why it matters**: Next nodes expect list format. Incorrect format causes workflow execution to fail.\n\n**See**: [ERROR_PATTERNS.md](ERROR_PATTERNS.md) #2 for detailed error solutions\n\n---\n\n## Critical Limitation: No External Libraries\n\n**MOST IMPORTANT PYTHON LIMITATION**: Cannot import external packages on default installs.\n\n> **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.\n\n**❌ NOT available** (raise `ModuleNotFoundError`): `requests`, `pandas`, `numpy`, `scipy`, `bs4`\u002FBeautifulSoup, `lxml`.\n\n**✅ Available** (standard library only): `json`, `datetime`, `re`, `base64`, `hashlib`, `urllib.parse`, `math`, `random`, `statistics`.\n\n### Workarounds\n\n**Need HTTP requests?**\n- ✅ Use **HTTP Request node** before Code node\n- ✅ Or switch to **JavaScript** and use `this.helpers.httpRequest()` (the bare `$helpers` global is undefined in the task-runner sandbox)\n\n**Need data analysis (pandas\u002Fnumpy)?**\n- ✅ Use Python **statistics** module for basic stats\n- ✅ Or switch to **JavaScript** for most operations\n- ✅ Manual calculations with lists and dictionaries\n\n**Need web scraping (BeautifulSoup)?**\n- ✅ Use **HTTP Request node** + **HTML Extract node**\n- ✅ Or switch to **JavaScript** with regex\u002Fstring methods\n\n**See**: [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md) for complete reference\n\n---\n\n## Common Patterns Overview\n\nBased on production workflows, the most useful Python patterns are:\n\n1. **Data Transformation** - Transform all items with list comprehensions\n2. **Filtering & Aggregation** - Sum, filter, count with built-in functions\n3. **String Processing with Regex** - Extract patterns from text with `re`\n4. **Data Validation** - Validate and clean data, attach error lists\n5. **Statistical Analysis** - Calculate mean\u002Fmedian\u002Fstdev with the `statistics` module\n\nCopy-ready snippets for all five live in [COMMON_PATTERNS.md](COMMON_PATTERNS.md#quick-pattern-snippets), alongside 10 fully detailed production patterns (multi-source aggregation, markdown parsing, JSON comparison, CRM normalization, dictionary lookup, top-N filtering, and more).\n\n---\n\n## Error Prevention - Top 5 Mistakes\n\n1. **Importing external libraries** (Python-specific) → `import requests` raises `ModuleNotFoundError`. Use the HTTP Request node or JavaScript instead.\n2. **Empty code or missing return** → every path must end with `return [{\"json\": ...}]`.\n3. **Incorrect return format** → wrap in a list: `{\"json\": {...}}` becomes `[{\"json\": {...}}]`.\n4. **KeyError on dictionary access** → use `.get()`: `_json.get(\"user\", {}).get(\"name\", \"Unknown\")`.\n5. **Webhook body nesting** → read via `[\"body\"]`: `_json.get(\"body\", {}).get(\"email\", \"no-email\")`.\n\n**See**: [ERROR_PATTERNS.md](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.\n\n---\n\n## Standard Library Reference\n\nMost useful modules: `json` (parse\u002Fgenerate), `datetime` (dates + `timedelta`), `re` (regex), `base64` (encode\u002Fdecode), `hashlib` (hashing), `urllib.parse` (URL ops), and `statistics` (mean\u002Fmedian\u002Fstdev). Also available: `math`, `random`, `collections`, `itertools`, `functools`.\n\nFor a condensed cheat sheet plus full per-module examples, see [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md#quick-reference-most-useful-modules).\n\n---\n\n## Best Practices\n\n### 1. Always Use .get() for Dictionary Access\n\n```python\n# ✅ SAFE: Won't crash if field missing\nvalue = item[\"json\"].get(\"field\", \"default\")\n\n# ❌ RISKY: Crashes if field doesn't exist\nvalue = item[\"json\"][\"field\"]\n```\n\n### 2. Handle None\u002FNull Values Explicitly\n\n```python\n# ✅ GOOD: Default to 0 if None\namount = item[\"json\"].get(\"amount\") or 0\n\n# ✅ GOOD: Check for None explicitly\ntext = item[\"json\"].get(\"text\")\nif text is None:\n    text = \"\"\n```\n\n### 3. Use List Comprehensions for Filtering\n\n```python\n# ✅ PYTHONIC: List comprehension\nvalid = [item for item in items if item[\"json\"].get(\"active\")]\n\n# ❌ VERBOSE: Manual loop\nvalid = []\nfor item in items:\n    if item[\"json\"].get(\"active\"):\n        valid.append(item)\n```\n\n### 4. Return Consistent Structure\n\n```python\n# ✅ CONSISTENT: Always list with \"json\" key\nreturn [{\"json\": result}]  # Single result\nreturn results  # Multiple results (already formatted)\nreturn []  # No results\n```\n\n### 5. Debug with print() Statements\n\n```python\n# Debug statements appear in browser console (F12)\nitems = _input.all()\nprint(f\"Processing {len(items)} items\")\nprint(f\"First item: {items[0] if items else 'None'}\")\n```\n\n---\n\n## Production Gotchas\n\n### SplitInBatches Loop Semantics\n\nThe SplitInBatches node has two outputs:\n- `main[0]` = **done** — fires ONCE after all batches complete\n- `main[1]` = **each batch** — fires for every batch (the loop body)\n\nAlways add a **Limit 1** node after the done output.\n\n### Correct Node Reference Syntax\n\n```python\n# ❌ WRONG\ndata = _node['HTTP Request']['json']\n\n# ✅ CORRECT - call .first() then access json\ndata = _node['HTTP Request'].first()['json']\n```\n\n### Cross-Iteration Data Not Available in Python\n\n`$getWorkflowStaticData('global')` may not be available in Python Beta mode. If you need to accumulate data across SplitInBatches iterations, use a JavaScript Code node for the accumulation logic instead.\n\n---\n\n## When to Use Python vs JavaScript\n\n### Use Python When:\n- ✅ You need `statistics` module for statistical operations\n- ✅ You're significantly more comfortable with Python syntax\n- ✅ Your logic maps well to list comprehensions\n- ✅ You need specific standard library functions\n\n### Use JavaScript When:\n- ✅ You need HTTP requests (`this.helpers.httpRequest()`)\n- ✅ You need advanced date\u002Ftime (DateTime\u002FLuxon)\n- ✅ You want better n8n integration\n- ✅ **For 95% of use cases** (recommended)\n\n### Consider Other Nodes When:\n- ❌ Simple field mapping → Use **Set** node\n- ❌ Basic filtering → Use **Filter** node\n- ❌ Simple conditionals → Use **IF** or **Switch** node\n- ❌ HTTP requests only → Use **HTTP Request** node\n\n---\n\n## Integration with Other Skills\n\n### Works With:\n\n**n8n Expression Syntax**:\n- Expressions use `{{ }}` syntax in other nodes\n- Code nodes use Python directly (no `{{ }}`)\n- When to use expressions vs code\n\n**n8n MCP Tools Expert**:\n- How to find Code node: `search_nodes({query: \"code\"})`\n- Get configuration help: `get_node({nodeType: \"nodes-base.code\"})`\n- Validate code: `validate_node({nodeType: \"nodes-base.code\", config: {...}})`\n\n**n8n Node Configuration**:\n- Mode selection (All Items vs Each Item)\n- Language selection (Python vs JavaScript)\n- Understanding property dependencies\n\n**n8n Workflow Patterns**:\n- Code nodes in transformation step\n- When to use Python vs JavaScript in patterns\n\n**n8n Validation Expert**:\n- Validate Code node configuration\n- Handle validation errors\n- Auto-fix common issues\n\n**n8n Code JavaScript**:\n- When to use JavaScript instead\n- Comparison of JavaScript vs Python features\n- Migration from Python to JavaScript\n\n---\n\n## Quick Reference Checklist\n\nBefore deploying Python Code nodes, verify:\n\n- [ ] **Considered JavaScript first** - Using Python only when necessary\n- [ ] **Code is not empty** - Must have meaningful logic\n- [ ] **Return statement exists** - Must return list of dictionaries\n- [ ] **Proper return format** - Each item: `{\"json\": {...}}`\n- [ ] **Data access correct** - Using `_input.all()`, `_input.first()`, or `_input.item`\n- [ ] **No external imports** - Only standard library (json, datetime, re, etc.)\n- [ ] **Safe dictionary access** - Using `.get()` to avoid KeyError\n- [ ] **Webhook data** - Access via `[\"body\"]` if from webhook\n- [ ] **Mode selection** - \"All Items\" for most cases\n- [ ] **Output consistent** - All code paths return same structure\n\n---\n\n## Additional Resources\n\n### Related Files\n- [DATA_ACCESS.md](DATA_ACCESS.md) - Comprehensive Python data access patterns\n- [COMMON_PATTERNS.md](COMMON_PATTERNS.md) - 10 Python patterns for n8n\n- [ERROR_PATTERNS.md](ERROR_PATTERNS.md) - Top 5 errors and solutions\n- [STANDARD_LIBRARY.md](STANDARD_LIBRARY.md) - Complete standard library reference\n\n### n8n Documentation\n- Code Node Guide: https:\u002F\u002Fdocs.n8n.io\u002Fcode\u002Fcode-node\u002F\n- Python in n8n: https:\u002F\u002Fdocs.n8n.io\u002Fcode\u002Fbuiltin\u002Fpython-modules\u002F\n\n---\n\n**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.\n",{"name":5,"description":7},"main","98985c16dc8df1bbd7dcd1bc698cd997a093e751","N8N agent\u002Fplaybooks\u002Fn8n-code-python","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os","https:\u002F\u002Fgithub.com\u002F26BB","🚀 Aspiring Product Manager | CS @ GS Moze\r\n\r\n🛠️ Building 0→1 products across SaaS & clean-tech\r\n\r\n📊 Turning user feedback & data into shipped features","2026-11-05 13:34:38",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add 26BB\u002Fagent-fleet-os --skill n8n-code-python",{"tool":37,"command":38},"bunx","bunx skills add 26BB\u002Fagent-fleet-os --skill n8n-code-python",{"tool":40,"command":41},"pnpm","pnpm dlx skills add 26BB\u002Fagent-fleet-os --skill n8n-code-python","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002FN8N agent\u002Fplaybooks\u002Fn8n-code-python\u002FSKILL.md",true,[45,51,55,59,63],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"COMMON_PATTERNS.md","REFERENCE","参考文档",21767,"https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002FN8N agent\u002Fplaybooks\u002Fn8n-code-python\u002FCOMMON_PATTERNS.md",{"path":52,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":53,"sourceHtmlUrl":54},"DATA_ACCESS.md",15026,"https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002FN8N agent\u002Fplaybooks\u002Fn8n-code-python\u002FDATA_ACCESS.md",{"path":56,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":57,"sourceHtmlUrl":58},"ERROR_PATTERNS.md",13921,"https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002FN8N agent\u002Fplaybooks\u002Fn8n-code-python\u002FERROR_PATTERNS.md",{"path":60,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":61,"sourceHtmlUrl":62},"README.md",9449,"https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002FN8N agent\u002Fplaybooks\u002Fn8n-code-python\u002FREADME.md",{"path":64,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":65,"sourceHtmlUrl":66},"STANDARD_LIBRARY.md",19004,"https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002FN8N agent\u002Fplaybooks\u002Fn8n-code-python\u002FSTANDARD_LIBRARY.md",[68,75,82,89,96,103],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7F51NQSCRM2PWFMATCV9MEG","taste-design","Semantic Design System Skill for Google Stitch. Generates agent-friendly DESIGN.md files that enforce premium, anti-generic UI standards — strict typography, calibrated color, asymmetric layouts, perpetual micro-motion, and hardware-accelerated performance.","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002Fstitch agent\u002Fplugins\u002Fstitch-utilities\u002Fplaybooks\u002Ftaste-design\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":19},"01M7F51JGTS9VJ3S9T6VMQWZ08","stitch-loop","Teaches agents to iteratively build websites using Stitch with an autonomous baton-passing loop pattern","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002Fstitch agent\u002Fplugins\u002Fstitch-utilities\u002Fplaybooks\u002Fstitch-loop\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":19},"01M7F51EZR2XYDWMA3XKWH1HX2","site-md","Analyze a project description or site requirements and synthesize a project constitution into SITE.md for the Stitch Build Loop","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002Fstitch agent\u002Fplugins\u002Fstitch-utilities\u002Fplaybooks\u002Fsite-md\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":19},"01M7F51BNCMP0GQ7SGP39SZYDP","enhance-prompt","Transforms vague UI ideas into polished, Stitch-optimized prompts. Enhances specificity, adds UI\u002FUX keywords, injects design system context, and structures output for better generation results.","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002Fstitch agent\u002Fplugins\u002Fstitch-utilities\u002Fplaybooks\u002Fenhance-prompt\u002FSKILL.md",[],[],{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":19},"01M7F518SX707EB3X42B2V7HRA","design-md","Analyze Stitch projects and synthesize a semantic design system into DESIGN.md files","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002Fstitch agent\u002Fplugins\u002Fstitch-utilities\u002Fplaybooks\u002Fdesign-md\u002FSKILL.md",[],[],{"skillNo":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":19},"01M7F5148PVYTA76NR3X0YK8SK","stitch::upload-to-stitch","Upload local assets (images, mockups, extracted HTML, design markdown) to a Stitch project. ALWAYS use this skill when you need to upload visual assets, HTML pages, or design docs to Stitch, particularly when direct MCP tool calls fail or truncate due to base64 token limits.","https:\u002F\u002Fgithub.com\u002F26BB\u002Fagent-fleet-os\u002Fblob\u002Fmain\u002Fstitch agent\u002Fplugins\u002Fstitch-design\u002Fplaybooks\u002Fupload-to-stitch\u002FSKILL.md",[],[]]