# Execute a batch request

> Source: https://truto.one/docs/api-reference/admin/batch-requests/create/

`POST /batch-request`

Resource: **Batch requests**

This endpoint processes a batch of resource calls in one go.  
  1. **Requires** an `integrated_account_id`, which must be accessible to the user based on environment permissions.  
  2. **Requires** a list of `resources` describing how each resource call should be made, including optional dependencies.  
  3. **Processes** these calls in an order that respects dependencies and loops (`loop_on`).
  4. **Refuses** a stale integrated account (one paused because it needs reauthorization) with `401` and `truto_error_code: integrated_account_needs_reauth`.
  5. **Returns** a combined result including successful records and any errors encountered. If a resource returns a file, the response is that file instead (see `result` in the response).

  An example of a batch request would look like this - 

  ```bash
  curl --location 'https://api.truto.one/batch-request' \
    --header 'Content-Type: application/json' \
    --header 'Authorization: ••••••' \
    --data '{
      "integrated_account_id": "<replace with your integrated account id>",
      "args": {
        "page_id": "<replace with your notion page id>"
      },
      "resources": [
        {
          "name": "page-content",
          "resource": "block-children",
          "method": "list",
          "query": {
            "block_id": "{{args.page_id}}",
            "truto_ignore_remote_data": true
          },
          "recurse": {
            "if": "{{resources.block-children.has_children:bool}}",
            "config": {
              "query": {
                "block_id": "{{resources.block-children.id}}"
              }
            }
          },
          "persist": false
        },
        {
          "name": "all-page-content",
          "type": "spool",
          "depends_on": "page-content"
        },
        {
          "name": "combine-page-content",
          "type": "transform",
          "config": {
            "expression": "$convertNotionToMarkdown($sortNodes($map(resources.`block-children`, function($v) {$merge([$v, {'parent_id': $firstNonEmpty($v.parent.page_id, $v.parent.block_id)}])}), 'id', 'parent_id'))"
          },
          "depends_on": "all-page-content",
          "persist": true
        }
      ]
    }'
 ``` 
In the above example, we have the page content in [Notion blocks](https://www.notion.com/help/what-is-a-block) which is converted into Markdown format (.md), joined together one by one using spool and returned as part of the batch request response. The depends_on options help in executing it step by step wherein one results depends on another. The batch requests are similar to [sync jobs](https://truto.one/docs/guides/sync-jobs/overview) - just that they are much simpler in terms of setting up - the data can be returned as part of the same Request/Response cycle.
Send `Idempotency-Key` to make a retry return the first response (kept for 24 hours).

## Header parameters

- **`Idempotency-Key`** _(string)_
  A retry with the same key, path and integrated account within 24 hours returns the first response instead of calling the integration again.

## Request body

- **`integrated_account_id`** _(string)_
  The ID of the integrated account in whose context these resource calls are made.
- **`args`** _(object)_
  Optional arguments available for placeholder replacement in resource definitions.
- **`resources`** _(array<object>)_
  A list of resource definitions that can be either a request or a transform.
  - **`name`** _(string)_
    The name of the node. Required on runtime version 4, where `depends_on` and destinations refer to nodes by name. Keep names unique within a sync job.
  - **`type`** _(string)_
    The node type. Required on runtime version 4. Each type reads its own fields; `resource`, `method`, `id`, `query` and `loop_on` apply to `request` nodes.
    Allowed: `request`, `transform`, `spool`, `add_context`, `destination`, `event`, `get_state`, `update_state`, `delete_state`
  - **`run_if`** _(string)_
    A JSONata expression. On runtime version 4 the node runs only when it evaluates to a truthy value.
  - **`resource`** _(string)_
    The name of the resource to sync. Required for `request` nodes and on runtime versions 1 to 3. For Unified APIs, it should be in the format `unified_api_name/resource_name`. For Proxy API, it can just be `resource_name`.
  - **`method`** _(string)_
    The method to call on the resource.
  - **`id`** _(string)_
    The ID of the resource to sync. This is optional and can be used to sync a single resource. It also supports placeholders.
  - **`query`** _(object | string)_
    The query parameters to pass to the resource method. An object whose values may use placeholders, or a JSONata string that returns the object.
  - **`body`** _(object | string)_
    `request` nodes: the request body. An object whose values may use placeholders, or a JSONata string that returns the object.
  - **`integrated_account_id`** _(string)_
    `request` nodes, runtime version 4: the integrated account to call. Required there, usually `{{args.integrated_account_id}}`. Versions 1 to 3 refuse it and call the run's own `integrated_account_id`. On version 4, `add_context` and `get_state` nodes also take it.
  - **`recurse`** _(object)_
    `request` nodes: call the same resource again for each returned record for which `if` is truthy, with `config.id` and `config.query` for the next call. Use it for nested data such as child pages.
    - **`if`** _(string | object)_
      A placeholder or JSONata condition, or `{ expression }` with a JSONata expression.
      _One of:_
      - **object**
        - **`expression`** _(string)_
    - **`config`** _(object)_
      - **`id`** _(string)_
      - **`query`** _(object | string)_
  - **`paginate_if`** _(string)_
    `request` nodes, runtime version 4: a JSONata expression. Truto fetches the next page only while it is truthy.
  - **`delay_after_ms`** _(number)_
    `request` nodes, runtime version 4: a pause in milliseconds after each call.
  - **`delete_tracking`** _(string)_
    `request` nodes, for runs that store Unified API records in Super Query: what happens to the stored records of this job and account that the run did not write. `hard` deletes them; `soft` marks them `truto_deleted`. Not used by runs that send to a webhook.
    Allowed: `hard`, `soft`
  - **`delete_tracking_query`** _(object)_
    With `delete_tracking`, a filter (placeholders allowed) that narrows which stored records are checked.
  - **`config`** _(object)_
    The settings of a non-`request` node. Its shape depends on `type`: for example `expression` on `transform` and `add_context` nodes, `key` on the state nodes, `name` on `event` nodes and `id` on `destination` nodes.
  - **`destination_type`** _(string)_
    `destination` nodes, runtime version 4: where the records go. `config.id` names the webhook or datastore.
    Allowed: `webhook`, `datastore`
  - **`resources_to_persist`** _(array<string>)_
    `destination` nodes, runtime version 4: the names of the nodes whose records this destination sends.
  - **`use_args`** _(boolean)_
    `transform` nodes, runtime version 4: set `true` when the parent is not a `request` node, such as a transform that builds records from `args`.
  - **`debug`** _(boolean)_
    Runtime version 4, any node: `true` logs a `transform` node's input and output.
  - **`loop_on`** _(string)_
    When a particular placeholder argument is an array and you want to repeat the request for each element in that array, you can set this parameter. For example, if you accept an argument called `user_ids` which is an array of strings, and you want to fetch each user's details, you can set this parameter to `args.user_ids` and the request will be repeated for each element in the `user_ids` array.
  - **`depends_on`** _(string)_
    The `name` of the parent node (on runtime versions 1 to 3, its `name` or `resource`). The node runs only after its parent, and each object synced for the parent is available as the resources object in placeholders, e.g. `{{resources.crm.contacts.id}}` when the parent is the `crm/contacts` resource.
  - **`persist`** _(boolean)_
    Runtime versions 1 to 3 only; refused on version 4. Whether to persist the resource in the database or not in case of a Daemon sync job run or send as a payload in case of RapidBridge sync job run. The Proxy API resources are by default NOT persisted and this parameter can be set to `true` to persist them. Unified API resources are always persisted.

## Response body

- **`result`** _(object)_
  Map of resource names to the records fetched for that resource. The key is the resource's `name` from the request body. If a resource returns a file instead of JSON (a non-JSON response that has a `Content-Type`), the response is that file itself, with the provider's `Content-Type`, not this JSON object, and the other results and `errors` are not returned. Fetch files in their own batch request.
- **`errors`** _(object)_
  Map of resource names to errors encountered while processing that resource. Present only for resources that failed.

## Errors

| Status | Description |
| :----- | :---------- |
| `400` | Bad request if `integrated_account_id` or `resources` is missing |
| `401` | Unauthorized if the user session is invalid or missing |
| `404` | Not found if the `integrated_account_id` does not exist or is not accessible by the user |

## Code examples

### Truto CLI

```bash
truto batch \
  -b '{"requests": [{"method": "GET", "path": "/integrated-account"}]}' \
  -o json
```

### Truto TS SDK

```typescript
import Truto from '@truto/truto-ts-sdk';

const truto = new Truto({
  token: '<your_api_token>',
});

const body = {
  "integrated_account_id": "your_integrated_account_id",
  "args": {
    "my_placeholder": 123
  },
  "resources": []
};

const result = await truto.batchRequest.create(body);

console.log(result);
```

### Truto Python SDK

```python
import asyncio
from truto_python_sdk import TrutoApi

truto_api = TrutoApi(token="<your_api_token>")

async def main():
    body = {
        "integrated_account_id": "your_integrated_account_id",
        "args": {
            "my_placeholder": 123
        },
        "resources": []
    }

    result = await truto_api.batch_requests.create(body)
    print(result)

asyncio.run(main())
```

### curl

```bash
curl -X POST 'https://api.truto.one/batch-request' \
  -H 'Authorization: Bearer <your_api_token>' \
  -H 'Content-Type: application/json' \
  -d '{
  "integrated_account_id": "your_integrated_account_id",
  "args": {
    "my_placeholder": 123
  },
  "resources": []
}'
```

### JavaScript

```javascript
const body = {
  "integrated_account_id": "your_integrated_account_id",
  "args": {
    "my_placeholder": 123
  },
  "resources": []
};

const response = await fetch('https://api.truto.one/batch-request', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer <your_api_token>',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(body),
});

const data = await response.json();
console.log(data);
```

### Python

```python
import requests

url = "https://api.truto.one/batch-request"
headers = {
    "Authorization": "Bearer <your_api_token>",
    "Content-Type": "application/json",
}
params = {
}
payload = {
    "integrated_account_id": "your_integrated_account_id",
    "args": {
        "my_placeholder": 123
    },
    "resources": []
}

response = requests.post(url, headers=headers, params=params, json=payload)
print(response.json())
```
