# HTTP Client

> Hace solicitudes HTTP.

Source: https://docs.sommatic.ai/es/nodes/io.http/

- Slug: `io.http`
- Familia: Entrada y salida
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Hace solicitudes HTTP.

## Configuración

- `connection_id` (string, opcional): Credencial opcional para la solicitud HTTP. Acepta credenciales de tipo `api-key`, `basic-auth`, `oauth2` u `object` (encabezados o autenticación personalizados).
- `url` (string, obligatorio, acepta expresiones): URL completa, o ruta si se usa una conexión.
- `method` (string, opcional): Por defecto: `GET`. Valores permitidos: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`.
- `headers` (object, opcional, acepta expresiones): Encabezados HTTP como pares clave-valor.
- `body` (object, opcional, acepta expresiones): Cuerpo JSON. Admite {{expressions}}.

Admite los ajustes de ejecución compartidos: reintentos (`retryOnFail`, `maxTries`, `waitBetweenTries`) y timeout.

## Puertos de salida

- `out` (por defecto): Respuesta HTTP correcta (2xx)
- `error`: Error de cliente HTTP (4xx) o error de servidor (5xx)

## Contrato de entrada

- `connection_id` (string, opcional)
- `url` (string, obligatorio)
- `method` (string, opcional)
- `headers` (object, opcional)
- `body` (object, opcional)

## Contrato de salida

- `status` (number, opcional)
- `headers` (object, opcional)
- `data` (object, opcional): Cuerpo de la respuesta

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("HTTP Client").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `HTTP Client`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `out`, según la salida que muestra Puertos.

- `$("HTTP Client").item.json.status` (number) = `200`
- `$("HTTP Client").item.json.headers` (object) = `{…}`
- `$("HTTP Client").item.json.data` (object) = `{…}`: Cuerpo de la respuesta
- `$("HTTP Client").item.json.data.id` (string) = `"ord_123"` (El editor no la sugiere)
- `$("HTTP Client").item.json.data.status` (string) = `"paid"` (El editor no la sugiere)
- `$("HTTP Client").item.json.headers.content-type` (string) = `"application/json; charset=utf-8"` (El editor no la sugiere)


## Cómo funciona

Envía una petición HTTP, opcionalmente autenticada con una credencial resuelta en el servidor, y reintenta con espera exponencial los límites de tasa, los 5xx y los fallos de red transitorios.

1. Resuelve la configuración: las expresiones de `url`, `headers` y `body` se evalúan contra la ejecución.
2. Con `connection_id`, resuelve la credencial: antepone `config.baseUrl` cuando `url` no empieza por `http` y añade una cabecera de autenticación desde el secreto, gana la primera coincidencia: `token` → `Authorization: Bearer`, `username` + `password` → `Authorization: Basic`, `apiKey` → cabecera `config.headerName` (por defecto `x-api-key`).
3. Calcula la política de reintentos (consulta `http_retry_*` y `execution`).
4. Envía `method` a `url` con `headers` y con `body` como datos de la petición, por IPv4. El cliente acepta todos los estados y el worker los clasifica.
5. Un 2xx sale por `out` con `{ status, data, headers }`. Los 429 y 5xx se reintentan mientras queden intentos, igual que los errores de red transitorios; cualquier otro caso sale por `error` de inmediato.

## En un workflow

### Nodo

```json
{
  "node_id": "node-call-erp",
  "label": "Call ERP",
  "operator_slug": "io.http",
  "operator_version": "1.0.0",
  "config": {
    "url": "https://api.example.com/orders/{{ $json.order_id }}",
    "method": "GET",
    "headers": {
      "accept": "application/json"
    },
    "connection_id": "pi-credential-xxxx",
    "http_retry_max_attempts": 3,
    "http_retry_backoff_ms": 1000
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "status": 200,
    "data": {
      "id": "ord_123",
      "status": "paid"
    },
    "headers": {
      "content-type": "application/json; charset=utf-8"
    }
  },
  "port": "out"
}
```

## Puertos de salida (comportamiento en el código)

### `out`

El servidor respondió con un estado 2xx. `data` es el cuerpo de la respuesta interpretado (JSON si el servidor envía JSON; texto en otro caso).

```json
{
  "status": 200,
  "data": {
    "id": "ord_123",
    "status": "paid"
  },
  "headers": {
    "content-type": "application/json; charset=utf-8"
  }
}
```

### `error`

Un estado no 2xx tras el último intento (los datos son `{ status, data, message }`) o un fallo de red o de preparación (los datos son `{ error, response }`).

```json
{
  "status": 404,
  "data": {
    "message": "Order not found"
  },
  "message": "HTTP Request Failed with status 404"
}
```

## Comportamiento en el código

- `http_retry_max_attempts`: No está declarado en el esquema. Número total de intentos, incluido el primero. Tiene prioridad sobre `execution`. Los valores menores que 1 o no numéricos pasan a 1; el máximo es 5.
- `http_retry_backoff_ms`: No declarado. Espera base en ms (si falta, `execution.waitBetweenTries` y luego 1000). La espera antes del reintento n es `base × 2^(n−1)` más 0–249 ms aleatorios, con el tope de `http_retry_max_wait_ms`.
- `http_retry_max_wait_ms`: No declarado. Tope de una sola espera; por defecto 20000 y nunca más de 30000.
- `execution`: Solo se usa si falta `http_retry_max_attempts`: `retryOnFail: false` da 1 intento; en otro caso, `maxTries` intentos (por defecto 3). Sin bloque `execution`, el nodo hace hasta 3 intentos. Este worker no aplica `timeout_ms`, `continueOnFail` ni `alwaysOutputData`.
- `method`: Si está vacío, la petición se envía como GET.
- `connection_id`: El secreto debe ser un objeto con `token`, `username` + `password` o `apiKey`, como en las credenciales `basic-auth`, `oauth2` u `object`. Una credencial `api-key` guardada como cadena simple no añade cabecera. `config.baseUrl` y `config.headerName` salen de la configuración de la credencial.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `HTTP Request Failed with status <status>` | `error` | El servidor respondió con un estado no 2xx. Los 4xx distintos de 429 nunca se reintentan; los 429 y 5xx llegan a este puerto solo tras el último intento. `data` contiene el cuerpo de la respuesta. |
| `<network error message>` | `error` | La conexión falló en todos los intentos (por ejemplo `connect ETIMEDOUT` o `getaddrinfo ENOTFOUND`) o falló con un error no transitorio. Revisa la URL y que el host sea accesible desde el orquestador. |
| `Failed to resolve connection <connection_id>: <detail>` | `error` | La credencial no existe o este flujo no puede usarla. No se reintenta. |

## Notas y límites

- Estados que se reintentan: 429 y 500–599. Errores de red que se reintentan: `ETIMEDOUT`, `ECONNRESET`, `ECONNREFUSED`, `ECONNABORTED`, `ENOTFOUND`, `EAI_AGAIN`, `EPIPE`, `ENETUNREACH`, `EHOSTUNREACH` y cualquier error cuyo mensaje contenga "timeout".
- Los reintentos reenvían la misma petición: asegúrate de que las llamadas no idempotentes (POST, PATCH) se puedan repetir, o define `http_retry_max_attempts: 1`.
- La petición en sí no tiene tiempo límite; un servidor que nunca responde mantiene el nodo en espera.
- Las conexiones se fuerzan a IPv4 y no se mantienen abiertas entre ejecuciones.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "io.http",
  "name": "HTTP Client",
  "category": "io",
  "version": "1.0.0",
  "description": "Make HTTP Requests.",
  "capabilities": [
    "http",
    "api",
    "rest"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "HTTP Credential (optional)",
        "description": "Optional credential for the HTTP request. Accepts credentials of type `api-key`, `basic-auth`, `oauth2`, or `object` (custom headers / auth).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "api-key",
            "basic-auth",
            "oauth2",
            "object"
          ],
          "types": [
            "http"
          ]
        }
      },
      "url": {
        "type": "string",
        "title": "URL",
        "description": "Full URL or Path if connection used.",
        "format": "expression"
      },
      "method": {
        "type": "string",
        "title": "Method",
        "enum": [
          "GET",
          "POST",
          "PUT",
          "PATCH",
          "DELETE"
        ],
        "default": "GET"
      },
      "headers": {
        "type": "object",
        "title": "Headers",
        "description": "HTTP headers as key-value pairs.",
        "format": "expression"
      },
      "body": {
        "type": "object",
        "title": "Body",
        "description": "JSON body. Supports {{expressions}}.",
        "format": "expression"
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "url"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "url": {
        "type": "string"
      },
      "method": {
        "type": "string"
      },
      "headers": {
        "type": "object"
      },
      "body": {
        "type": "object"
      }
    },
    "required": [
      "url"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "status": {
        "type": "number"
      },
      "headers": {
        "type": "object"
      },
      "data": {
        "type": "object",
        "description": "Response Body"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Response",
      "description": "Successful HTTP response (2xx)",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "HTTP client_error (4xx) or server_error (5xx)",
      "is_default": false,
      "supports_condition": true
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "high-throughput-io"
  ],
  "tags": [
    "api",
    "rest"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "HTTP Credential (optional)",
      "description": "Optional credential for the HTTP request. Accepts credentials of type `api-key`, `basic-auth`, `oauth2`, or `object` (custom headers / auth).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "api-key",
          "basic-auth",
          "oauth2",
          "object"
        ],
        "types": [
          "http"
        ]
      }
    },
    "url": {
      "type": "string",
      "title": "URL",
      "description": "Full URL or Path if connection used.",
      "format": "expression"
    },
    "method": {
      "type": "string",
      "title": "Method",
      "enum": [
        "GET",
        "POST",
        "PUT",
        "PATCH",
        "DELETE"
      ],
      "default": "GET"
    },
    "headers": {
      "type": "object",
      "title": "Headers",
      "description": "HTTP headers as key-value pairs.",
      "format": "expression"
    },
    "body": {
      "type": "object",
      "title": "Body",
      "description": "JSON body. Supports {{expressions}}.",
      "format": "expression"
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "url"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "url": {
      "type": "string"
    },
    "method": {
      "type": "string"
    },
    "headers": {
      "type": "object"
    },
    "body": {
      "type": "object"
    }
  },
  "required": [
    "url"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "status": {
      "type": "number"
    },
    "headers": {
      "type": "object"
    },
    "data": {
      "type": "object",
      "description": "Response Body"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Response",
    "description": "Successful HTTP response (2xx)",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "HTTP client_error (4xx) or server_error (5xx)",
    "is_default": false,
    "supports_condition": true
  }
]
```
