JavaScript examples: call an external API
Call an outside API from a Run Custom Code step with fetch, keep keys in app secrets, handle errors, and when to use Trigger Webhook or a pipe instead.
- Verified Nov 17, 2026
- Classic builder
On this page
- Options without code
- How requests from code run
- Keep keys in app secrets
- GET JSON and pick out a nested value
- POST JSON
- Build a URL with query parameters
- POST a form-encoded body
- Post a message to a chat tool's incoming webhook
- Call the Tadabase REST API
- Try one API, then a backup
- Notice a rate limit (HTTP 429)
- Skip the call when a stored value is recent
A Run Custom Code workflow action can call another service's API with fetch, read the answer, and pass values to later steps with returnData. New to the action? Start with Running Custom Javascript.
Options without code #
- Trigger Webhook sends record data to an outside address. See Send record data to another system with Trigger Webhook.
- Trigger Pipe runs a method of a pipe, a saved and reusable API connection, and passes its response on. See Run a pipe from a workflow.
Use code when you need to shape the request or the answer in ways those actions do not offer. Both actions depend on your plan.
How requests from code run #
- The code runs on Tadabase's servers, not in the user's browser. The API sees a request from Tadabase.
- Use
await fetch(url, options). The response hasok,status,headers,json()andtext(). - The whole step, including every request it makes, must finish within 30 seconds.
- If the code fails, the next steps still run, unless Abort workflow if this step fails is on in the step's settings. Call
fail("message")to stop the step with your own error. - Clicking Run in the code window runs the code for real: a POST sent from a test run creates or changes data in the other system. Test against a sandbox account when the API has one.
Keep keys in app secrets #
Never type an API key, token or password into the code. The code is saved with the workflow, and anyone who can edit workflows can read it. Store the key as an app secret and read it when the code runs:
const apiKey = getAppSecret("WEATHER_API_KEY");
if (!apiKey) fail("The WEATHER_API_KEY app secret is missing or inactive."); - Write the secret's name in quotes, exactly as saved. Only secrets named this way are sent to the code; a name built while the code runs gives
undefined. - If the code returns, logs or throws a secret's value, it is masked in the step's output.
- Values that are fine to show, such as a base URL or an account number, can go in an app variable and be read with
getAppVariable("slug").
GET JSON and pick out a nested value #
// Input: city (Record Value (Source))
// App secret: WEATHER_API_KEY
const url = "https://api.weather.example/v1/current?q=" + encodeURIComponent($city || "");
const res = await fetch(url, {
headers: { "Authorization": "Bearer " + getAppSecret("WEATHER_API_KEY") }
});
if (!res.ok) {
console.error("Weather API failed", res.status);
returnData("ok", false);
returnData("error", "status " + res.status);
return;
}
const data = await res.json();
returnData("ok", true);
returnData("temperature", data && data.current ? data.current.temp : null);
returnData("condition", data && data.current && data.current.condition ? data.current.condition.text : null); POST JSON #
// Inputs: name, email (Record Value (Source))
// App secret: CRM_TOKEN
const res = await fetch("https://api.crm.example/v2/contacts", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + getAppSecret("CRM_TOKEN")
},
body: JSON.stringify({ name: $name, email: $email, source: "tadabase" })
});
const text = await res.text();
let body = null;
try { body = JSON.parse(text); } catch (e) { body = null; }
returnData("ok", res.ok);
returnData("status", res.status);
returnData("contact_id", body && body.id ? body.id : null);
if (!res.ok) returnData("error", text.slice(0, 500)); Build a URL with query parameters #
// Inputs: query, page (Custom Value or Record Value)
const params = {
q: $query || "",
limit: 25,
page: Number($page) || 1
};
const qs = Object.keys(params)
.map(function (k) { return encodeURIComponent(k) + "=" + encodeURIComponent(params[k]); })
.join("&");
const res = await fetch("https://api.example.com/search?" + qs);
const data = res.ok ? await res.json() : {};
const items = Array.isArray(data.items) ? data.items : [];
returnData("results", items);
returnData("count", items.length); POST a form-encoded body #
// Some older APIs want application/x-www-form-urlencoded instead of JSON.
// Input: email (Record Value (Source))
// App secret: NEWSLETTER_KEY; app variable: newsletter_list_id
const fields = {
email: $email || "",
list_id: getAppVariable("newsletter_list_id") || ""
};
const body = Object.keys(fields)
.map(function (k) { return encodeURIComponent(k) + "=" + encodeURIComponent(fields[k]); })
.join("&");
const res = await fetch("https://api.newsletter.example/subscribe", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + getAppSecret("NEWSLETTER_KEY")
},
body: body
});
returnData("ok", res.ok);
returnData("status", res.status); Post a message to a chat tool's incoming webhook #
Many chat tools give you an incoming-webhook address that posts whatever you send to a channel. That address works like a password, so keep the whole URL in an app secret:
// Input: message (Custom Value, can include record values)
// App secret: CHAT_WEBHOOK_URL
const url = getAppSecret("CHAT_WEBHOOK_URL");
if (!url) fail("The CHAT_WEBHOOK_URL app secret is missing.");
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text: $message || "(empty message)" })
});
returnData("ok", res.ok);
returnData("status", res.status); The body each tool expects differs; check its documentation.
Call the Tadabase REST API #
Inside the same app, the workflow's own record actions are simpler. The REST API is useful to change records in another Tadabase app. Create an API key in that app (see Create and manage API keys), then save its key and secret as app secrets and its app ID as an app variable in the app that runs the workflow. Your plan must include API access.
// Inputs: tableId, recordId, newStatus (Custom Value or Record Value)
// App secrets: OTHER_APP_API_KEY, OTHER_APP_API_SECRET; app variable: other_app_id
// Replace field_38 with the slug of the field to change.
const res = await fetch(
"https://api.tadabase.io/api/v1/data-tables/" + $tableId + "/records/" + $recordId,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Tadabase-App-id": getAppVariable("other_app_id"),
"X-Tadabase-App-Key": getAppSecret("OTHER_APP_API_KEY"),
"X-Tadabase-App-Secret": getAppSecret("OTHER_APP_API_SECRET")
},
body: JSON.stringify({ field_38: $newStatus })
}
);
const data = await res.json();
returnData("ok", data.type === "success");
if (data.type !== "success") returnData("error", data.msg || ("status " + res.status)); Endpoints, headers and responses are described in Create, read, update and delete records.
Try one API, then a backup #
async function tryJson(url) {
try {
const res = await fetch(url);
return res.ok ? await res.json() : null;
} catch (e) {
return null;
}
}
const primary = await tryJson("https://primary.example.com/lookup");
const data = primary || await tryJson("https://backup.example.com/lookup");
returnData("ok", !!data);
returnData("source", primary ? "primary" : data ? "backup" : "none");
returnData("data", data); Notice a rate limit (HTTP 429) #
const res = await fetch("https://api.example.com/data");
if (res.status === 429) {
const retryAfter = Number(res.headers.get("Retry-After")) || null;
console.warn("Rate limited. Retry-After:", retryAfter);
returnData("ok", false);
returnData("rate_limited", true);
returnData("retry_after_seconds", retryAfter);
return;
}
returnData("ok", res.ok);
returnData("data", res.ok ? await res.json() : null); Do not wait inside the code for a long Retry-After: the step has 30 seconds in total. Save the result, and let a later run, for example a scheduled workflow, try again.
Skip the call when a stored value is recent #
// Inputs: lastFetchedAt and cachedValue (Record Value (Source))
const ONE_HOUR = 60 * 60 * 1000;
const last = Date.parse($lastFetchedAt || "");
if (!isNaN(last) && Date.now() - last < ONE_HOUR) {
returnData("from_cache", true);
returnData("value", $cachedValue);
return;
}
const res = await fetch("https://api.example.com/rate?base=USD");
const data = res.ok ? await res.json() : null;
returnData("from_cache", false);
returnData("value", data ? data.rate : null);
returnData("fetched_at", new Date().toISOString()); A later Update Record step can save value and fetched_at back to the record for the next run.
Was this page helpful?
Something wrong or missing on this page? Tell us.