> ## Documentation Index
> Fetch the complete documentation index at: https://docs.firstresonance.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Call the ION API from a Code step

> Add a Code step that reads your ION connection's API key, gets an access token, and runs a GraphQL query.

A Code step runs your own JavaScript in a flow. Use one for logic the [ion-api actions](https://docs.firstresonance.io/automate-with-ion/workflow-builder/ion-api-actions.md) don't cover. The sample on this page reads the purchase order that fired the flow. It needs a flow that triggers on **Purchase Orders - Create** and a saved test payload. See [Create a flow](https://docs.firstresonance.io/automate-with-ion/workflow-builder/create-a-flow.md) and [Test a flow](https://docs.firstresonance.io/automate-with-ion/workflow-builder/test-a-flow.md).

> [!TIP]
>
> Before you ask an AI coding agent to write or change Code step code, point it at [llms.txt](https://docs.firstresonance.io/llms.txt), an index of this manual for AI agents, or [llms-full.txt](https://docs.firstresonance.io/llms-full.txt) for the full text, and at the [API reference](https://docs.firstresonance.io/api-reference/overview.md). The agent then uses real queries, mutations, and field names.

## Add a Code step

1. In **Workflow Builder**, click **+** under the trigger, search for **Code**, and select **Code Block**.
2. In the step's **Configure** tab, open the code editor, replace its contents with the [sample code](#sample-code), and click the check mark to close the editor.
3. Click **Save > Save draft**.
4. Run the flow with your saved payload, as described in [Run the flow with a saved payload](https://docs.firstresonance.io/automate-with-ion/workflow-builder/test-a-flow.md#run-the-flow-with-a-saved-payload).
5. In **Run history**, click **Code Block**. Check the purchase order on its **Output** tab, and the lines the code logged on its **Logs** tab.

## How the code reads your ION connection

When a Code step runs, it receives the flow's config variables as `configVars`. Your ION connection is one of them. Its `fields` hold the **Client ID** as `clientId` and the **Client Secret** as `clientSecret`. The sample finds the connection that has a `clientId`, and exchanges the two for an access token, so you never paste credentials into the code.

The code reads the trigger's output from `stepResults`. The purchase order's ID is at `results.body.data.data.id`.

## Sample code

This sample gets an access token, then queries the purchase order the trigger fired for:

```javascript theme={null}
module.exports = async ({ logger, configVars }, stepResults) => {
  // The trigger is the first step; the PO id is at results.body.data.data.id
  const trigger = Object.values(stepResults)[0];
  const poId = trigger.results.body.data.data.id;

  // The ION connection (Client ID / Secret / Environment)
  const conn = Object.values(configVars || {}).find((v) => v?.fields?.clientId);
  if (!conn) {
    logger.error("No ION connection found. configVars keys:", Object.keys(configVars || {}));
    throw new Error("No ION connection available");
  }
  const { clientId, clientSecret } = conn.fields;

  // US sandbox URLs; for another environment, replace with that environment's auth server and API endpoint
  const tokenUrl = "https://staging-auth.buildwithion.com/realms/api-keys/protocol/openid-connect/token";
  const apiUrl = "https://staging-api.buildwithion.com/graphql";

  // 1. Get a token
  const tokenRes = await fetch(tokenUrl, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({ grant_type: "client_credentials", client_id: clientId, client_secret: clientSecret }),
  });
  const { access_token } = await tokenRes.json();

  // 2. Read the purchase order
  const res = await fetch(apiUrl, {
    method: "POST",
    headers: { "Content-Type": "application/json", Authorization: `Bearer ${access_token}` },
    body: JSON.stringify({
      query: "query ($id: ID!) { purchaseOrder(id: $id) { id status assignedToId supplier { name } } }",
      variables: { id: poId },
    }),
  });
  const body = await res.json();
  if (body.errors) throw new Error(JSON.stringify(body.errors));

  logger.info("Purchase order:", body.data.purchaseOrder);
  return { data: body.data.purchaseOrder };
};
```

> [!NOTE]
>
> The sample's URLs point to the US sandbox, so the ION connection must use sandbox [API keys](https://docs.firstresonance.io/api/authentication/api-keys.md). For another region or environment, replace `tokenUrl` and `apiUrl` with that environment's auth server and API endpoint from [ION environments](https://docs.firstresonance.io/getting-started/ion-basics.md#ion-environments).


## Related topics

- [ion-api actions reference](https://docs.firstresonance.io/automate-with-ion/workflow-builder/ion-api-actions.md)
- [Error codes](https://docs.firstresonance.io/api/error-codes.md)
- [Build a production integration](https://docs.firstresonance.io/api/guides/build-a-production-integration.md)
- [Authenticate with OAuth 2.0](https://docs.firstresonance.io/api/authentication/oauth.md)
- [Export data as PDF](https://docs.firstresonance.io/automate-with-ion/integrations/export-data-as-pdf.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.