# Execute API Tasks

## API Doc

Interactive API docs can be found at: <https://run.truebit.network/dispatcher/api-docs/>

## Overview

You can configure the endpoint for either a synchronous or asynchronous response. In sync mode, if the result is ready within 60 seconds, it will be returned immediately. If not, you'll receive an executionId, which you can use to check the result later by calling the status endpoint.

When executing an [API Task](https://devs.truebit.io/developing-truebit-tasks/how-to-create-api-tasks), your task `input` will need to specify the API endpoint path, HTTP method type, and API input parameters.  These parameters must match the schema defined in the API Task manifest.

## Execute an API Task by task name

> Execute an API Task using the provided task name. Supports both synchronous and asynchronous execution.

```json
{"openapi":"3.1.0","info":{"title":"Task Execution API","version":"1.120.0-beta.275"},"tags":[{"name":"API task execution","description":"Api task execution by id and namespace"}],"servers":[{"description":"Public beta","url":"https://run.truebit.network"},{"description":"Current environment relative paths","url":"/"}],"paths":{"/task/api/execute-by-name":{"post":{"summary":"Execute an API Task by task name","description":"Execute an API Task using the provided task name. Supports both synchronous and asynchronous execution.","operationId":"executeApiTaskByName","tags":["API task execution"],"parameters":[{"in":"header","name":"x-api-key","required":true,"schema":{"type":"string"},"description":"API key for authentication."}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"namespace":{"type":"string","description":"The namespace of the task."},"taskName":{"type":"string","description":"The name of the task to be executed."},"label":{"type":"string","description":"Label of the task."},"version":{"type":"integer","format":"uint32","description":"Version number of the task."},"async":{"type":"boolean","description":"If true, the endpoint will retrieve the executionId; otherwise, it will try to return the execution result only if it completes within 60 seconds."},"input":{"type":"object","description":"Input data required for task execution."},"executionTimeout":{"type":"integer","format":"uint32","description":"Timeout for task execution in seconds."}},"required":["namespace","taskName","async","input","executionTimeout"]}}}},"responses":{"200":{"description":"Successful execution","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/ExecuteApiSyncResponse"},{"$ref":"#/components/schemas/ExecuteTaskAsyncResponse"}]}}}},"400":{"description":"Bad request, invalid input.","content":{"application/json":{"schema":{"oneOf":[{"$ref":"#/components/schemas/BadRequestResponse"},{"$ref":"#/components/schemas/BlockchainSignedError"}]}}}},"401":{"description":"Not authorized.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"402":{"description":"Payment required.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}},"500":{"description":"Internal server error.","content":{"application/json":{"schema":{"$ref":"#/components/schemas/Error"}}}}}}}},"components":{"schemas":{"ExecuteApiSyncResponse":{"type":"object","description":"Successful execution of the API task.","properties":{"executionId":{"type":"string","description":"The ID of the executed task."},"clearTextSolution":{"type":"object","description":"The result of the API task execution.","properties":{"output":{"type":"object","description":"The output of the task execution, containing task-specific details."},"status":{"type":"string","description":"Status of the execution within the solution.","enum":["succeed","failed"]},"senderAddress":{"type":"string","description":"The address of the sender who executed the task."}}},"status":{"type":"string","description":"Status of the execution.","enum":["Success","Running","Error"]},"totalTransferredBytes":{"type":"object","description":"Total bytes transferred during the request and response.","properties":{"request":{"type":"integer","description":"Bytes transferred in the request."},"response":{"type":"integer","description":"Bytes transferred in the response."}}},"errorMsg":{"type":"string","description":"Error message if execution encountered issues but still returned a result."}}},"ExecuteTaskAsyncResponse":{"type":"object","description":"Asynchronous response of task execution.","properties":{"executionId":{"type":"string","description":"The ID of the task execution."}}},"BadRequestResponse":{"type":"object","description":"Bad request","properties":{"message":{"type":"string","description":"Error message."}}},"BlockchainSignedError":{"type":"object","description":"Blockchain Signed Error","properties":{"status":{"type":"number","description":"Error code."},"message":{"type":"string","description":"Error message."},"taskRegistryContract":{"type":"string","description":"Task Registry Contract address."},"nodeRegistryContract":{"type":"string","description":"Node Registry Contract address."},"authorizationContract":{"type":"string","description":"Authorization Contract address."},"chainId":{"type":"string","description":"Chain identification."},"blockHash":{"type":"string","description":"Block hash."},"blockNumber":{"type":"number","description":"Block number."},"signedError":{"type":"string","description":"Error signed by hub."}}},"Error":{"type":"object","description":"Internal server error","properties":{"message":{"type":"string","description":"Internal server error"}}}}}}
```

### Custom Headers

When executing API tasks, you may need to include custom HTTP headers in the request to the target API. This is common for authentication tokens, custom identifiers, or specifying content preferences.

#### Adding Headers to Your Request

You will need to include a `headers` object within the `input` field of your request body. Truebit will inject these headers into the final API call to the target endpoint.

> **Note:** This feature is separate from the Truebit API authentication header (`X-API-KEY`), which is used to authenticate your request to Truebit. Custom headers you define in the `input.headers` object will be forwarded to the target API you are calling.

#### Supported Header Types

You can include any standard HTTP header, such as:

* **Authorization** – Bearer tokens, Basic auth, API keys for the target service.
* **Accept** – Specify expected response format (e.g., `application/json`, `application/xml`).
* **Content-Type** – Define the request body format when using POST/PUT methods.
* **Custom Headers** – Any application-specific headers required by the target API (e.g., `X-Custom-Header`, `X-Request-ID`).

<details>

<summary>Example: Executing an API Task with Custom Headers</summary>

```bash
curl -s -X POST "https://run.truebit.network/task/api/execute-by-name" \
  -H "Content-Type: application/json" \
  -H "X-API-KEY: YOUR_TRUEBIT_API_KEY" \
  -d '{
    "namespace": "3a2b5129",
    "taskName": "custom",
    "input": {
      "path": "/anything/{Id}",
      "method": "GET",
      "params": {
        "Id": 12345
      },
      "headers": {
        "Authorization": "Bearer YOUR_TARGET_API_TOKEN",
        "X-Custom-Header": "CustomValue123",
        "Accept": "application/json"
      }
    },
    "executionTimeout": 30000,
    "async": false
  }'
```

</details>

#### Request Structure

| Field           | Location       | Description                                            |
| --------------- | -------------- | ------------------------------------------------------ |
| `X-API-KEY`     | Request Header | Your Truebit API key for authentication with Truebit   |
| `input.headers` | Request Body   | Custom headers to be injected into the target API call |

#### Important Notes

1. **Header Injection**: Headers defined in `input.headers` are injected by Truebit into the outgoing request to the target API endpoint.
2. **Authentication Separation**: Keep in mind the distinction between:
   * `X-API-KEY` in the request header → Authenticates your request to Truebit.
   * `Authorization` (or other auth headers) in `input.headers` → Authenticates the request to your target API.
3. **CLI Authentication**: If you previously configured authentication headers using the Truebit CLI tool, you can now alternatively include them directly in the request body using `input.headers`. Both methods are supported.
4. **Header Overrides**: Headers specified in `input.headers` will be included in the final request to the target API. Ensure there are no conflicts with headers that may be automatically set by Truebit.

### Authorization

#### API KEY

To get authorization to execute a task, include your registered `API key` in the request header. This allows Truebit to validate your access and identify the account responsible for covering the task execution cost (linked to the API key’s associated address).

**Example**

```
X-API-KEY: be0dc6ba-9a60-4777-b5b7-60ed2397e3ed
```
