Back to Curriculum

Custom Tooling for Agents: Building Your Own API Nodes

The real power of n8n is the ability to write custom JavaScript or Python code within a node to perform tasks that standard nodes cannot. In this lesson, we learn how to build Custom API Nodes to bridge the gap between AI reasoning and real-world execution.

🏗️ The Code Node Architecture

  1. Input: The JSON data from the previous node (e.g., an AI-generated strategy).
  2. Logic: Your custom script (e.g., calculating ROI or formatting a PDF).
  3. Output: A clean JSON object ready for the next node.

🛠️ Technical Snippet: The character-to-token estimator

In n8n, use a "Code" node to estimate token usage before sending to an LLM:

// Estimate tokens (approx 4 chars per token)
for (const item of $input.all()) {
  item.json.token_estimate = Math.ceil(item.json.text_input.length / 4);
}
return $input.all();

🔍 Nuance: Error Handling in Code Nodes

Always use try/catch blocks in your custom nodes. If a script fails inside n8n without error handling, the entire workflow stops. A professional workflow "catches" the error and sends it to a Slack notification while letting the other leads continue.


⚡ Practice Lab: The Character Counter

  1. Trigger: Manual Trigger with a string.
  2. Action: Add a "Code" node. Write a script that returns the character count and the word count of that string.
  3. Verify: Run the workflow and ensure the data appears in the JSON output.

📝 Homework: The Data Normalizer

Build a custom Code node that takes a "Messy" website URL (e.g., http://WWW.TEST.COM/path?query=1) and normalizes it to a clean root domain (test.com). Use this to deduplicate leads in your database.