# API Task With n8n Orchestration

### Description

You can implement a custom N8N workflow to act as an off-chain processing layer that:

* Receives an execution request from your deployed smart contract.
* Executes Truebit API or Function tasks.
* Then triggers a second function task that extracts and encodes only the desired fields using `abi.encode`.
* And finally responds with the encoded output and transcript IDs for the on-chain callbackTask.<br>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcR_XHOYWpIOZWA_xuvlqKCyT3_kGHwrmrqLU5LgNLKj59OgxbZzWYlOGVbxQ8NU8QCY2UdqJ7vdW8UKeK3zIOk8ycNXWkX-tr4jyq4meTYJaCf6r1VVPHtUQJ_vCCAbu1bIoKUeQ?key=yM4bTL3u4RXxd1TQyVE1EA" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
By using an **n8n workflow**, you can encode and return only the specific field you want as the response.\
In contrast, executing directly against the **Truebit API** returns the entire JSON object.
{% endhint %}

#### Flow Architecture

Your N8N workflow consists of the following nodes:

1. **Webhook**:  This is the Workflow entry point. The path should be defined in the manifest of your Truebit API task and also, must match the one specified in your Solidity contract’s payload.
2. **APINODE or TASKNODE**: Triggers a Truebit Function or API task using the Truebit Endpoints.

<details>

<summary>Example of calling a Truebit API TASK:</summary>

```json
{
  "namespace": "a67fa7c8",
  "taskName": "direct",
  "input": {
    "url": "https://api.restful-api.dev/objects?id=3",
    "method": "GET",
    "headers": {
      "Content-Type": "application/json"
    }
  },
  "executionTimeout": 10000,
  "async": false
}
```

</details>

3\. **TASKNODE** (Truebit Function Task for ABI-Encoding):  Executes a Truebit function task that takes the response of the API task, selects only the required fields, and encodes them using Solidity's `abi.encode(...)` format. This allows the WatchTower to send those encoded values directly back to your smart contract in resultData.

<details>

<summary>Example of calling a Truebit task to encode the output values</summary>

```json
{
  "namespace": "a67fa7c8",
  "taskName": "n8n",
  "input": "<double-stringified APINODE response>",
  "requiredSolutions": 2,
  "totalSolutions": 3,
  "executionTimeout": 60000,
  "async": false
}
```

</details>

How it works:

* The input for this task is built from the output of APINODE.
* The task runs a custom JS function in a sandboxed environment.
* The JS function selects and ABI-encodes only the fields the user needs (e.g., \[uint256, string]).

4\. Respond to Webhook: Sends a structured response back to WatchTower.

<details>

<summary>JSON response example</summary>

```json
{
  "encodedOutput": "{{ $node['TASKNODE'].json.clearTextSolution.output }}",
  "metaTranscriptIds": [
    "{{ $node['APINODE'].json.executionId }}",
    "{{ $node['TASKNODE'].json.executionId }}"
  ]
}
```

</details>

#### Execution Flow Summary

1. The smart contract sends a request to WatchTower (e.g. \[using requestGet...]).
2. WatchTower triggers the N8N webhook via HTTP.
3. N8N:
   1. Executes the API task using APINODE.
   2. Runs a JS task (TASKNODE) to process the API response and encode the final result.
   3. Returns the ABI-encoded result and transcript IDs to WatchTower.
4. WatchTower uses the returned data to invoke callbackTask(...) on your contract.

{% hint style="info" %}

#### Important!

* The value returned as encodedOutput must be ABI-encoded using Solidity types, matching what your contract expects in the callback.
* Ensure your N8N workflow returns a response within the configured timeout on WatchTower.
  {% endhint %}

#### Encoding

The encodedOutput in the webhook response must be a string encoded using Solidity's ABI rules, e.g., via abi.encode(...) in your N8N logic. If your smart contract expects a string, uint, or a tuple of both, the data returned must match the expected structure and be properly encoded ahead of time.

For example, if your contract expects:

```solidity
(string value, uint256 number)
```

Then, in N8N you must do ABI encoding of that pair and return it as a hex string.

Here the N8N workflow full example json.

#### Best Practices

* If supporting multiple simultaneous tasks, use a mapping of id => data instead of a single id variable.
* Customize the callbackTask logic as needed (e.g. conditional branching, retries, etc).
* Use abi.encode / abi.decode correctly when dealing with complex types.

### How To Implement It?

{% hint style="danger" %}
Make sure you have developed and deployed the API manifest first.
{% endhint %}

1. You must create a Dynamic Oracle API Task filling the payload with the n8n Webhook URL.
2. You must [grant](/developing-truebit-tasks/truebit-cli-reference.md#auth-grant) permission to the Truebit Verify Hub. Please execute:

```bash
truebit auth grant [options] <namespace> <grantee>
```

* `namespace`: The namespace where the Truebit API task was deployed
* grantee:&#x20;
  * Truebit Verify Hub Address: `0xd70C3454aaD1B7ec660a064d8b1FE5708d898d84` .

3. Handle the callback with the output you have defined in your n8n workflow.&#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://devs.truebit.io/developing-truebit-tasks/dynamic-oracles/api-task-with-n8n-orchestration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
