n8n Masterclass IModule 3

3.2Custom Tooling for Agents

30 min 4 code blocks Practice Lab Homework Quiz (5Q)

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

Technical Snippet: The character-to-token estimator

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

javascript
// 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();
Key Insight

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

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.

🇵🇰 Pakistan Activity: Build a PKR Invoice Generator

Create a Code node that generates a simple invoice for Pakistani clients:

Input JSON:

json
{"client": "Kolachi Restaurant", "service": "SEO Audit", "amount": 45000, "city": "Karachi"}

Code Node Logic:

javascript
for (const item of $input.all()) {
  const gst = item.json.amount * 0.17; // 17% GST
  item.json.invoice = {
    client: item.json.client,
    subtotal: `PKR ${item.json.amount.toLocaleString()}`,
    gst: `PKR ${gst.toLocaleString()}`,
    total: `PKR ${(item.json.amount + gst).toLocaleString()}`,
    note: `Invoice for ${item.json.service} — ${item.json.city}`
  };
}
return $input.all();

This is the kind of micro-automation that Pakistani freelancers need daily — and you can sell it as part of a bigger workflow package.

Homework

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.

📺 Recommended Videos & Resources

🎯 Mini-Challenge

Write your URL normalizer: Create a Code node that takes 10 messy URLs (different formats, protocols, subdomains) and cleans them all to just the root domain. Test it, then use it to find and remove duplicate companies from a lead list!

🖼️ Visual Reference

code
📊 Custom Code Node Data Pipeline

Raw Input (Chaos):
┌────────────────────────────────────┐
│ "  http://WWW.EXAMPLE.COM/path?x=1"│
│ "EXAMPLE.com"                      │
│ "192.168.1.1"                      │
│ "ftp://cdn.example.com/file.pdf"   │
│ "example.com:8080"                 │
└──────────────┬─────────────────────┘
               │
               ↓ Code Node
        ┌──────────────────┐
        │ JavaScript Logic │
        │ - Extract domain │
        │ - Normalize case │
        │ - Remove path    │
        │ - Remove port    │
        │ - Return root    │
        └─────────┬────────┘
                  │
Clean Output (Deduplicated):
┌────────────────────────────────────┐
│ "example.com"                      │
│ "example.com" (Duplicate removed)  │
│ "192.168.1.1"                      │
│ "example.com" (Matched above)      │
│ "example.com" (Matched above)      │
└────────────────────────────────────┘

Result: 5 URLs → 2 unique domains

Lesson Summary

Includes hands-on practice labHomework assignment included4 runnable code examples5-question knowledge check below

Quiz: Custom Tooling for Agents

5 questions to test your understanding. Score 60% or higher to pass.