Skip to main content

Call APIs from agent functions

This page covers calling your APIs from the code of an agent function with apis.execute from "@yellow/bot". The APIs themselves are set up under Build → API. Credentials such as API keys stay in the API's settings and never appear in your code.

apis.execute​

Sends the request and returns the response.

apis.execute(api, parameters?) // → { status, headers, body }
ParameterDescription
apiThe API to call, picked from the editor's suggestions. Required.
parametersValues for the variables defined in the API's settings, such as {{orderId}} in its URL
Response fieldDescription
statusHTTP status code, for example 200
headersResponse headers, with lowercase names
bodyThe response. JSON is converted to an object; anything else arrives as text.
import { apis } from "@yellow/bot";

export default async function ({ orderId }) {
const response = await apis.execute("getOrderStatus", { orderId });

response.status; // 200
response.headers["content-type"]; // "application/json; charset=utf-8"
return { status: response.body.status };
}

To pick the API, type " right after apis.execute( and choose it from the list. The editor shows it as a label such as getOrderStatus. A name typed out by hand isn't recognised and stops the function with "api must be a Studio reference". See Get suggestions.

Handle errors​

apis.execute raises an error when the API answers with an error status (4xx or 5xx) or doesn't exist. The error message includes the status and the start of the response body. Wrap the call in try / catch so the user gets a helpful reply instead of a failed tool call.

try {
const response = await apis.execute("getOrderStatus", { orderId });
return { ok: true, status: response.body.status };
} catch (error) {
console.error("Order lookup failed", error);
return { ok: false, message: "We couldn't find that order. Please check the order number." };
}

Logging the error records its message, for example Error: unknown API: getOrderStatus. See Testing and logs.

Call two APIs at the same time​

Independent calls can run together with Promise.all. At most two calls can be running at the same time, and this counts database calls too: two API calls, two table calls, or one of each. A third call started while two are still running is refused, so run larger sets two at a time.

const [order, invoice] = await Promise.all([
apis.execute("getOrder", { orderId }),
apis.execute("getInvoice", { orderId }),
]);

A function can make up to 5 API calls per run.

  • Crypto, to sign a payload before you send it
  • Examples: creating a support ticket, cancelling an order