---
title: "code snippets for automation platforms - codefmt"
description: "ready-to-use javascript, python, and hubl code snippets for Zapier, n8n, Pipedream, Make, and HubSpot. editable examples to format, copy, and paste."
url: https://codefmt.dev/snippets
updated: 2026-11-22
sources:
  - https://codefmt.dev/snippets
licence: "© codefmt. Cite with attribution to https://codefmt.dev."
---

# code snippets for automation platforms

## snippet library

### HTTP GET with Error Handling

zapier

Fetch JSON from a public API endpoint using inputData, with error handling. For an API that needs a key, use API by Zapier instead of passing the key through Input Data.

const url = inputData.apiUrl;

const response = await fetch(url, {
  method: "GET",
  headers: { Accept: "application/json" },
});

if (!response.ok) {
  throw new Error(`Request failed: ${response.status} ${response.statusText}`);
}
 …

[open in formatter](/?snippet=zapier-http-request)

### Date Formatting & Parsing

zapier

Parse a date string from inputData and reformat it for downstream steps.

const raw = inputData.dateString;
const date = new Date(raw);

if (isNaN(date.getTime())) {
  throw new Error(`Invalid date: "${raw}"`);
}

const iso = date.toISOString();
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, "0");
 …

[open in formatter](/?snippet=zapier-date-format)

### Map & Filter Array Data

zapier

Parse a JSON array from inputData, filter and transform each item, and return the results.

const items = JSON.parse(inputData.jsonArray);

const transformed = items
  .filter((item) => item.status === "active" && item.email)
  .map((item) => ({
    fullName: `${item.firstName} ${item.lastName}`.trim(),
    email: item.email.toLowerCase(),
    role: item.role || "member",
  }));

 …

[open in formatter](/?snippet=zapier-data-transform)

### Input Validation & Sanitization

zapier

Validate required inputData fields and sanitize values before processing.

const email = (inputData.email || "").trim().toLowerCase();
const name = (inputData.name || "").trim();
const amount = parseFloat(inputData.amount);

if (!email || !email.includes("@")) {
  throw new Error(`Invalid email: "${inputData.email}"`);
}

if (!name || name.length < 2) {
  throw new Error("Name is required and must be at least 2 characters");
 …

[open in formatter](/?snippet=zapier-input-validation)

### Return Multiple Output Objects

zapier

Split a comma-separated inputData field into multiple output objects for downstream steps.

const raw = inputData.emails || "";
const tag = inputData.tag || "imported";

const emails = raw
  .split(",")
  .map((e) => e.trim().toLowerCase())
  .filter((e) => e.includes("@"));

if (emails.length === 0) {
  throw new Error("No valid emails found in input");
 …

[open in formatter](/?snippet=zapier-multi-output)

### Python: Contact Lookup via requests

zapier

Look up a contact on a public endpoint using Zapier Python with the preinstalled requests library. For an API that needs a key, use API by Zapier instead of passing the key through Input Data.

import requests

email = input_data.get("email", "").strip().lower()

if not email or "@" not in email:
    raise Exception(f'Invalid email: "{input_data.get("email", "")}"')

response = requests.get(
    "https://api.example.com/v1/users",
    headers={"Accept": "application/json"},
 …

[open in formatter](/?snippet=zapier-python-contact-lookup)

### Process All Items

n8n

Loop through all input items with $input.all(), transform each, and return results.

const items = $input.all();
const results = [];

for (const item of items) {
  const { name, email, score } = item.json;

  results.push({
    json: {
      name: (name || "").trim(),
      email: (email || "").toLowerCase(),
 …

[open in formatter](/?snippet=n8n-process-items)

### HTTP Request with Retry

n8n

Call an API from a Code node with this.helpers.httpRequest and retry with exponential backoff. The Code node has no fetch; for a plain call, the HTTP Request node is simpler.

const maxRetries = 3;
const results = [];

for (const item of $input.all()) {
  let succeeded = false;
  let lastError = "";

  for (let attempt = 0; attempt < maxRetries && !succeeded; attempt++) {
    try {
      const data = await this.helpers.httpRequest({
 …

[open in formatter](/?snippet=n8n-http-retry)

### Remove Duplicate Items

n8n

Keep the first item for each email address and drop later duplicates, in Run Once for All Items mode. Items without an email pass through untouched.

const seen = new Set();
const results = [];

for (const item of $input.all()) {
  const key = String(item.json.email || "").trim().toLowerCase();

  if (key !== "" && seen.has(key)) {
    continue;
  }

 …

[open in formatter](/?snippet=n8n-dedupe-items)

### Date Parsing & Timezone Handling

n8n

Parse each item's dates with Luxon's DateTime, compute differences, and format them in a timezone (Run Once for All Items mode).

const results = [];

for (const item of $input.all()) {
  const zone = item.json.timezone || "UTC";
  const start = DateTime.fromISO(item.json.startDate, { zone });
  const end = DateTime.fromISO(item.json.endDate, { zone });

  if (!start.isValid || !end.isValid) {
    // Luxon names the cause, e.g. an unknown timezone or an unparsable date.
    results.push({ json: { error: start.invalidExplanation || end.invalidExplanation } });
 …

[open in formatter](/?snippet=n8n-date-manipulation)

### Try/Catch with Structured Errors

n8n

Wrap processing in try/catch and return a structured error item instead of failing the node.

const items = $input.all();
const results = [];

for (const item of items) {
  try {
    const payload = JSON.parse(item.json.rawData);

    if (!payload.id) {
      throw new Error("Missing required field: id");
    }
 …

[open in formatter](/?snippet=n8n-error-handling)

### Access Data from Previous Nodes

n8n

Reference output data from specific previous nodes using $() notation.

// The Webhook node puts the request payload under json.body.
const webhookData = $("Webhook").first().json.body;
const dbRecords = $("Postgres").all();
const configValue = $("Set Config").first().json.apiEndpoint;

const enriched = dbRecords.map((record) => ({
  json: {
    ...record.json,
    source: webhookData.source || "unknown",
    triggeredBy: webhookData.userId,
 …

[open in formatter](/?snippet=n8n-node-reference)

### Transform the Current Item

n8n

Transform one item in Run Once for Each Item mode, where n8n calls the code once per item and expects a single item back.

const { name, email, score } = $input.item.json;

return {
  json: {
    name: (name || "").trim(),
    email: (email || "").toLowerCase(),
    score: Number(score) || 0,
    grade: Number(score) >= 80 ? "pass" : "fail",
    itemIndex: $itemIndex,
  },
 …

[open in formatter](/?snippet=n8n-each-item-transform)

### Python: Process All Items

n8n

Iterate \_items in n8n's Python Code node (Run Once for All Items mode), transforming each item.

results = []

for item in _items:
    data = item["json"]
    name = (data.get("name") or "").strip()
    email = (data.get("email") or "").lower()
    try:
        score = float(data.get("score") or 0)
    except (TypeError, ValueError):
        score = 0.0
 …

[open in formatter](/?snippet=n8n-python-process-items)

### Python: Transform the Current Item

n8n

Read \_item in n8n's Python Code node (Run Once for Each Item mode) and return a single transformed item.

data = _item["json"]

try:
    score = float(data.get("score") or 0)
except (TypeError, ValueError):
    score = 0.0

return {
    "json": {
        "name": (data.get("name") or "").strip(),
 …

[open in formatter](/?snippet=n8n-python-each-item)

### Webhook Body Validation

pipedream

Validate an incoming webhook payload from steps.trigger.event and return a structured record.

const body = steps.trigger.event.body;

if (!body || !body.action) {
  return $.flow.exit("Missing required field: action");
}

const allowedActions = ["create", "update", "delete"];
if (!allowedActions.includes(body.action)) {
  return $.flow.exit(`Invalid action: ${body.action}`);
}
 …

[open in formatter](/?snippet=pipedream-webhook-handler)

### HTTP Request with axios

pipedream

Make an authenticated POST using axios from npm. Pipedream installs a package you import or require, but one step can't mix the two.

const axios = require("axios");

const { data } = await axios.post(
  "https://api.example.com/v1/records",
  {
    name: steps.trigger.event.body.name,
    email: steps.trigger.event.body.email,
  },
  {
    headers: {
 …

[open in formatter](/?snippet=pipedream-http-axios)

### Data Store Read/Write (full component)

pipedream

Persist state across runs with a Pipedream Data Store. Data stores must be declared as a component prop; codefmt formats this as module-style code because of the top-level export.

// In the Pipedream UI, attach a Data Store to this step. The configured
// store is exposed as this.db inside run().
export default defineComponent({
  props: {
    db: { type: "data_store" },
  },
  async run({ steps, $ }) {
    const userId = steps.trigger.event.body.userId;
    const key = `user:${userId}`;

 …

[open in formatter](/?snippet=pipedream-data-store)

### Environment Variable Access

pipedream

Check that required environment variables are set and export only the non-secret settings, with fallback defaults.

const requiredVars = ["API_KEY", "WEBHOOK_SECRET"];
const missing = requiredVars.filter((v) => !process.env[v]);

if (missing.length > 0) {
  throw new Error(`Missing env vars: ${missing.join(", ")}`);
}

// Pipedream stores exports and return values with the run (inspector and
// Event History), so keep secrets out of them. Read process.env.API_KEY in
// the step that needs it.
 …

[open in formatter](/?snippet=pipedream-env-vars)

### Python: Webhook Handler

pipedream

Process an incoming webhook in a Pipedream Python step. Return pd.flow.exit() to stop, since a bare call runs the rest of the step first.

import requests


def handler(pd: "pipedream"):
    body = pd.steps["trigger"]["event"]["body"]

    if not body or not body.get("action"):
        return pd.flow.exit("Missing required field: action")

    allowed = {"create", "update", "delete"}
 …

[open in formatter](/?snippet=pipedream-python-webhook)

### Source: Emit Deduped Events

pipedream

The run(event) body of a source component: skip events without an id and emit the rest with this.$emit. Set dedupe: "unique" on the component so a repeated id is dropped.

const body = event.body;

if (!body || !body.id) {
  console.log("Skipping event without an id");
  return;
}

this.$emit(body, {
  id: body.id,
  summary: `New record ${body.id}`,
 …

[open in formatter](/?snippet=pipedream-source-emit)

### Transform Input Fields

make

Transform and restructure scenario input fields for an API request.

const { firstName, lastName, email, phone, tags } = input;

const fullName = `${(firstName || "").trim()} ${(lastName || "").trim()}`.trim();

const tagList = (tags || "")
  .split(",")
  .map((t) => t.trim().toLowerCase())
  .filter(Boolean);

const contact = {
 …

[open in formatter](/?snippet=make-bundle-transform)

### Parse Nested JSON from Strings

make

Safely parse JSON strings from scenario input, handling nested structures.

const rawPayload = input.jsonPayload;
const rawMeta = input.metadata;

let payload;
let metadata;

try {
  payload = typeof rawPayload === "string" ? JSON.parse(rawPayload) : rawPayload;
} catch (e) {
  throw new Error(`Failed to parse jsonPayload: ${e.message}`, { cause: e });
 …

[open in formatter](/?snippet=make-json-parse)

### Error Handling with Structured Output

make

Try/catch pattern returning structured success or error output for Make scenarios. For an API that needs a key, use Make's HTTP module instead of passing the key through module input.

const url = input.url;

try {
  const response = await fetch(url, {
    headers: { Accept: "application/json" },
  });

  if (!response.ok) {
    const body = await response.text();
    return {
 …

[open in formatter](/?snippet=make-error-pattern)

### Python: Transform Input List

make

Transform a list of items from scenario input and return a structured result.

items = input.get("items", [])

results = []
for item in items:
    name = (item.get("name") or "").strip()
    email = (item.get("email") or "").lower()

    if not name or "@" not in email:
        continue

 …

[open in formatter](/?snippet=make-python-transform)

### Search Contacts by Email

hubspot

Look up a HubSpot contact by email address using the CRM search API via @hubspot/api-client.

const hubspot = require("@hubspot/api-client");
const hubspotClient = new hubspot.Client({
  accessToken: process.env.HUBSPOT_PRIVATE_APP_TOKEN,
});

const email = event.inputFields["email"];

try {
  const searchResponse = await hubspotClient.crm.contacts.searchApi.doSearch({
    filterGroups: [
 …

[open in formatter](/?snippet=hubspot-contact-lookup)

### Custom Workflow Action with API Call

hubspot

A custom coded workflow action that calls an external API via axios and updates the contact in HubSpot.

const axios = require("axios");
const hubspot = require("@hubspot/api-client");
const hubspotClient = new hubspot.Client({
  accessToken: process.env.HUBSPOT_PRIVATE_APP_TOKEN,
});

const objectId = event.object.objectId;
const email = event.inputFields["email"];

try {
 …

[open in formatter](/?snippet=hubspot-custom-action)

### Route by a Mapped Property

hubspot

Branch on a contact property mapped into the custom code action (here lifecyclestage) and return an action label for the workflow to route on.

// inputFields holds only the properties added under "Property to include in code".
const stage = event.inputFields["lifecyclestage"];
const objectId = event.object.objectId;

let action;
let outputData = {};

switch (stage) {
  case "lead":
  case "marketingqualifiedlead":
 …

[open in formatter](/?snippet=hubspot-webhook-process)

### Error Handling with Structured Output

hubspot

Robust error handling pattern using @hubspot/api-client that returns structured error data and rethrows what HubSpot should retry.

const hubspot = require("@hubspot/api-client");
const hubspotClient = new hubspot.Client({
  accessToken: process.env.HUBSPOT_PRIVATE_APP_TOKEN,
});

const contactId = event.object.objectId;
const requiredFields = ["email", "firstname"];
const missing = requiredFields.filter((f) => !event.inputFields[f]);

// Bad input will not fix itself on a retry, so report it as output.
 …

[open in formatter](/?snippet=hubspot-error-response)

### Python: Contact Lookup via REST

hubspot

Look up a HubSpot contact by object ID using the CRM REST API and a private app token.

import os

import requests

object_id = event.get("object", {}).get("objectId")
token = os.getenv("HUBSPOT_PRIVATE_APP_TOKEN")

if not object_id or not token:
    return {"outputFields": {"found": False, "error": "Missing objectId or token"}}

 …

[open in formatter](/?snippet=hubspot-python-contact)

### For Loop with Conditionals

hubl

Iterate over a list with if/else conditional rendering and loop index access.

{% set items = module.items %}
{% if items %}
  <ul class="card-list">
    {% for item in items %}
      <li class="card{% if loop.first %} card--first{% endif %}">
        <h3>{{ item.title|escape }}</h3>
        {% if item.description %}
          <p>{{ item.description|truncatewords(30) }}</p>
        {% else %}
          <p class="text-muted">No description available</p>
 …

[open in formatter](/hubl?snippet=hubl-for-loop)

### Custom Module with Parameters

hubl

A reusable custom module template that reads module parameters with defaults and renders content.

{# Custom CTA Banner Module #}
{# button_url is a text field. A Link field is an object: read module.button_link.url.href. #}
{% set heading = module.heading or "Get Started Today" %}
{% set subtext = module.subtext or "" %}
{% set button_text = module.button_text or "Learn More" %}
{% set button_url = module.button_url or "#" %}
{% set style = module.style or "primary" %}

<section class="cta-banner cta-banner--{{ style }}">
  <div class="cta-banner__content">
 …

[open in formatter](/hubl?snippet=hubl-custom-module)

### Blog Post Listing

hubl

Display recent blog posts using content variables and blog\_recent\_posts.

{% set blog_posts = blog_recent_posts("default", 6) %}

<div class="blog-listing">
  <h2>{{ module.heading or "Latest Posts" }}</h2>
  <div class="blog-grid">
    {% for post in blog_posts %}
      <article class="blog-card">
        {% if post.featured_image %}
          <img src="{{ post.featured_image }}"
               alt="{{ post.featured_image_alt_text|default(post.name, true) }}"
 …

[open in formatter](/hubl?snippet=hubl-blog-listing)

### Form Embed with Custom Styling

hubl

Embed a HubSpot form via the @hubspot/form module with custom wrapper markup and a fallback for the editor.

{% set form_id = module.form.form_id %}
{% set show_title = module.show_title|default(true) %}
{% set bg_color = module.background_color.color|default("#ffffff") %}

{% if form_id %}
  <div class="form-section" style="background-color: {{ bg_color }};">
    <div class="form-section__inner">
      {% if show_title and module.title %}
        <h2 class="form-section__title">{{ module.title }}</h2>
      {% endif %}
 …

[open in formatter](/hubl?snippet=hubl-form-handler)

## for agents (added to every page twin, not part of the page)

- format API: POST https://codefmt.dev/api/format (OpenAPI: https://codefmt.dev/api/openapi.json, code up to 51,200 characters, 50KB of ASCII (400 above it), request body up to 100KB, counted in bytes (413 above it), no authentication)
- MCP server: POST https://codefmt.dev/api/mcp (tools: format_code, format_json, ask_codefmt; manifest: https://codefmt.dev/.well-known/mcp.json)
- rate limit: 60 requests per minute per ip across format api calls, mcp and a2a tool calls, and /ask (mcp handshakes and listings are not counted). the count is kept per server instance, so treat it as a ceiling to stay under rather than an exact budget. the format api and /ask report the limit in RateLimit headers, every 429 carries Retry-After, /ask puts the message in answer, and an mcp tool call over the limit returns a tool result saying to try again in a minute
- auth statement: https://codefmt.dev/auth.md (no accounts, api keys or oauth; send no authorization header)
- site index for agents: https://codefmt.dev/llms.txt
- full reference (request bodies for every language, a copy-paste curl command, platform globals, troubleshooting): https://codefmt.dev/llms-full.txt
