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

# Crear automatización

> Crea una automatización en borrador con trigger webhook, cron o evento de registro y uno o más pasos.

Crea una automatización en borrador. Para que acepte disparos debes [publicarla](/automatizaciones/publicar-automatizacion) y [activarla](/automatizaciones/activar-automatizacion).

## Endpoint

```text theme={null}
POST /workflows
```

## Body

| Campo     | Tipo     | Requerido | Descripción                                                               |
| --------- | -------- | --------- | ------------------------------------------------------------------------- |
| `name`    | `string` | Sí        | Nombre visible.                                                           |
| `status`  | `string` | No        | `enabled` o `disabled`. Recomendado: crear en `disabled`.                 |
| `trigger` | `object` | Sí        | `webhook`, `cron`, `database_record_created` o `database_record_updated`. |
| `steps`   | `array`  | Sí        | Uno o más pasos ordenados.                                                |

### Trigger webhook

```json theme={null}
{ "type": "webhook" }
```

No envíes `secret`: la API lo genera y lo devuelve en la respuesta.

### Trigger cron

```json theme={null}
{
  "type": "cron",
  "cron": "0 9 * * *",
  "timezone": "America/Mexico_City"
}
```

### Trigger al crear un registro

```json theme={null}
{
  "type": "database_record_created",
  "databaseId": "<database-id>"
}
```

Se dispara automáticamente cuando se crea un registro en el tablero seleccionado.

### Trigger al actualizar un registro

```json theme={null}
{
  "type": "database_record_updated",
  "databaseId": "<database-id>"
}
```

Se dispara automáticamente cuando cambian los campos o el alcance de un registro en el tablero seleccionado. Cambios que solo afectan otros metadatos no generan una ejecución.

Obtén el `databaseId` con [Listar tableros](/tableros/listar-tableros). Para ambos triggers puedes acceder al registro con `{{trigger.body.record}}`; sus campos están en `{{trigger.body.record.values.<fieldId>}}`.

### Paso `browser.use`

```json theme={null}
{
  "actionKey": "browser.use",
  "task": "Investiga al prospecto {{trigger.body.record.values.<fieldId>}} y devuelve su sitio oficial, industria y fuentes.",
  "resultSchema": {
    "type": "object",
    "additionalProperties": false,
    "required": ["website", "industry", "sources"],
    "properties": {
      "website": { "type": "string" },
      "industry": { "type": "string" },
      "sources": {
        "type": "array",
        "items": { "type": "string" }
      }
    }
  },
  "wait": {
    "initialDelaySeconds": 30,
    "pollIntervalSeconds": 15,
    "timeoutSeconds": 3600
  }
}
```

Guía completa: [Usar navegador](/automatizaciones/paso-navegador).

### Paso `system.delay`

```json theme={null}
{
  "name": "Esperar",
  "actionKey": "system.delay",
  "input": {
    "mode": "duration",
    "amount": 1,
    "unit": "seconds"
  }
}
```

Guía completa: [Esperar](/automatizaciones/paso-esperar).

### Paso `http.request`

```json theme={null}
{
  "name": "Avisar sistema externo",
  "actionKey": "http.request",
  "input": {
    "method": "POST",
    "url": "https://ejemplo.com/hooks/pago",
    "headers": { "Content-Type": "application/json" },
    "body": {
      "referencia": "{{trigger.body.referencia}}"
    }
  }
}
```

Guía completa: [Solicitud HTTP](/automatizaciones/paso-http).

### Paso `code.javascript`

```json theme={null}
{
  "name": "Normalizar referencia",
  "actionKey": "code.javascript",
  "input": {
    "referencia": "{{trigger.body.referencia}}"
  },
  "code": "output = { referencia: String(input.referencia || '').trim() };"
}
```

Guía completa (objetos disponibles, buenos/malos ejemplos): [Paso JavaScript](/automatizaciones/paso-javascript).

Para **pasar variables entre pasos** (`steps.N.output`, `capture`, `context`) con ejemplos de 2 y 3 pasos, ver [Variables y contexto](/automatizaciones/variables-y-contexto).

## Ejemplo de solicitud

```bash theme={null}
curl -X POST "https://api.insuranceboosters.com/api/v1/workflows" \
  -H "Content-Type: application/json" \
  -H "x-ib-api-key: TU_API_KEY" \
  -d '{
    "name": "Notificar pago recibido",
    "status": "disabled",
    "trigger": { "type": "webhook" },
    "steps": [
      {
        "name": "Esperar",
        "actionKey": "system.delay",
        "input": { "mode": "duration", "amount": 1, "unit": "seconds" }
      },
      {
        "name": "Avisar sistema externo",
        "actionKey": "http.request",
        "input": {
          "method": "POST",
          "url": "https://ejemplo.com/hooks/pago",
          "headers": { "Content-Type": "application/json" },
          "body": {
            "evento": "pago_recibido",
            "referencia": "{{trigger.body.referencia}}"
          }
        }
      }
    ]
  }'
```

## Respuesta exitosa (`201`)

```json theme={null}
{
  "id": "<workflow-id>",
  "name": "Notificar pago recibido",
  "status": "disabled",
  "trigger": {
    "type": "webhook",
    "secret": "<webhook-secret>"
  },
  "steps": [
    {
      "id": "<step-id>",
      "name": "Esperar",
      "actionKey": "system.delay",
      "input": {
        "mode": "duration",
        "amount": 1,
        "unit": "seconds"
      }
    }
  ],
  "latestVersionNumber": 0,
  "createdAt": 1720000000000,
  "lastUpdatedAt": 1720000000000
}
```

Guarda `id` y, si el trigger es webhook, `trigger.secret` para armar la URL pública.

## Ejemplo con un registro actualizado

Este ejemplo envía el ID y el campo `estado` del registro actualizado a un sistema externo:

```bash theme={null}
curl -X POST "https://api.insuranceboosters.com/api/v1/workflows" \
  -H "Content-Type: application/json" \
  -H "x-ib-api-key: TU_API_KEY" \
  -d '{
    "name": "Notificar cambio de estado",
    "status": "disabled",
    "trigger": {
      "type": "database_record_updated",
      "databaseId": "<database-id>"
    },
    "steps": [
      {
        "name": "Avisar sistema externo",
        "actionKey": "http.request",
        "input": {
          "method": "POST",
          "url": "https://ejemplo.com/hooks/estado",
          "headers": { "Content-Type": "application/json" },
          "body": {
            "recordId": "{{trigger.body.record.id}}",
            "estado": "{{trigger.body.record.values.estado}}"
          }
        }
      }
    ]
  }'
```

Publica y activa la automatización antes de actualizar el registro que debe dispararla.

## Errores frecuentes

| HTTP  | Qué significa                                                 | Qué hacer                                                                                  |
| ----- | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `400` | El body no cumple el esquema o el tablero no está disponible. | Revisa `trigger`, `databaseId`, `actionKey` y los campos requeridos por cada tipo de paso. |
| `401` | API key inválida o faltante.                                  | Verifica `x-ib-api-key`.                                                                   |
| `500` | No fue posible crear.                                         | Reintenta; si continúa, contacta soporte.                                                  |


## OpenAPI

````yaml openapi/automatizaciones-v1.yaml POST /workflows
openapi: 3.1.0
info:
  title: Insurance Boosters API — Automatizaciones
  version: 1.0.0
  description: >
    API pública para crear, publicar y ejecutar automatizaciones por webhook,
    cron o eventos de registros, y consultar sus versiones y ejecuciones.
  license:
    name: Propietaria
    url: https://insuranceboosters.com
servers:
  - url: https://api.insuranceboosters.com/api/v1
    description: Producción
security:
  - IbApiKey: []
tags:
  - name: Automatizaciones
    description: Definición, publicación y control de automatizaciones.
  - name: Versiones
    description: Instantáneas publicadas de una automatización.
  - name: Ejecuciones
    description: Historial y detalle de corridas.
  - name: Webhooks
    description: Disparo público de automatizaciones con trigger webhook.
paths:
  /workflows:
    post:
      tags:
        - Automatizaciones
      summary: Crear automatización
      operationId: createWorkflow
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateWorkflowRequest'
            examples:
              webhook:
                summary: Trigger webhook
                value:
                  name: Notificar pago recibido
                  status: disabled
                  trigger:
                    type: webhook
                  steps:
                    - name: Esperar
                      actionKey: system.delay
                      input:
                        mode: duration
                        amount: 1
                        unit: seconds
                    - name: Avisar sistema externo
                      actionKey: http.request
                      input:
                        method: POST
                        url: https://ejemplo.com/hooks/pago
                        headers:
                          Content-Type: application/json
                        body:
                          evento: pago_recibido
                          referencia: '{{trigger.body.referencia}}'
              cron:
                summary: Trigger programado
                value:
                  name: Resumen diario
                  status: disabled
                  trigger:
                    type: cron
                    cron: 0 9 * * *
                    timezone: America/Mexico_City
                  steps:
                    - name: Esperar
                      actionKey: system.delay
                      input:
                        mode: duration
                        amount: 1
                        unit: seconds
              recordCreated:
                summary: Trigger al crear un registro
                value:
                  name: Notificar registro nuevo
                  status: disabled
                  trigger:
                    type: database_record_created
                    databaseId: <database-id>
                  steps:
                    - name: Avisar sistema externo
                      actionKey: http.request
                      input:
                        method: POST
                        url: https://ejemplo.com/hooks/registros
                        body:
                          recordId: '{{trigger.body.record.id}}'
              recordUpdated:
                summary: Trigger al actualizar un registro
                value:
                  name: Notificar cambio de estado
                  status: disabled
                  trigger:
                    type: database_record_updated
                    databaseId: <database-id>
                  steps:
                    - name: Avisar sistema externo
                      actionKey: http.request
                      input:
                        method: POST
                        url: https://ejemplo.com/hooks/estado
                        body:
                          recordId: '{{trigger.body.record.id}}'
                          estado: '{{trigger.body.record.values.estado}}'
      responses:
        '201':
          description: Automatización creada en borrador.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Workflow'
        '400':
          $ref: '#/components/responses/BadRequest'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '500':
          $ref: '#/components/responses/InternalError'
components:
  schemas:
    CreateWorkflowRequest:
      type: object
      required:
        - name
        - trigger
        - steps
      properties:
        name:
          type: string
        status:
          $ref: '#/components/schemas/WorkflowStatus'
        trigger:
          $ref: '#/components/schemas/WorkflowTrigger'
        steps:
          type: array
          items:
            $ref: '#/components/schemas/WorkflowStep'
          minItems: 1
    Workflow:
      type: object
      required:
        - id
        - name
        - status
        - trigger
        - steps
        - createdAt
        - lastUpdatedAt
      properties:
        id:
          type: string
        name:
          type: string
        status:
          $ref: '#/components/schemas/WorkflowStatus'
        trigger:
          $ref: '#/components/schemas/WorkflowTrigger'
        steps:
          type: array
          items:
            $ref: '#/components/schemas/WorkflowStep'
        publishedVersionId:
          type: string
        latestVersionNumber:
          type: integer
        cronState:
          type: object
          properties:
            lastFiredAt:
              type: integer
            nextDueAt:
              type: integer
        createdAt:
          type: integer
        lastUpdatedAt:
          type: integer
    WorkflowStatus:
      type: string
      enum:
        - enabled
        - disabled
    WorkflowTrigger:
      oneOf:
        - $ref: '#/components/schemas/WebhookTrigger'
        - $ref: '#/components/schemas/CronTrigger'
        - $ref: '#/components/schemas/DatabaseRecordCreatedTrigger'
        - $ref: '#/components/schemas/DatabaseRecordUpdatedTrigger'
    WorkflowStep:
      oneOf:
        - $ref: '#/components/schemas/BrowserUseStep'
        - $ref: '#/components/schemas/BrowserScriptStep'
        - $ref: '#/components/schemas/DelayStep'
        - $ref: '#/components/schemas/HttpStep'
        - $ref: '#/components/schemas/CodeStep'
    Error:
      type: object
      properties:
        error:
          type: string
      required:
        - error
    AuthError:
      type: object
      properties:
        message:
          type: string
      required:
        - message
    WebhookTrigger:
      type: object
      required:
        - type
      properties:
        type:
          type: string
          const: webhook
        secret:
          type: string
          description: Generado por la API. Úsalo solo en la URL del webhook.
    CronTrigger:
      type: object
      required:
        - type
        - cron
        - timezone
      properties:
        type:
          type: string
          const: cron
        cron:
          type: string
          description: Expresión cron de 5 campos.
          example: 0 9 * * *
        timezone:
          type: string
          example: America/Mexico_City
    DatabaseRecordCreatedTrigger:
      type: object
      required:
        - type
        - databaseId
      properties:
        type:
          type: string
          const: database_record_created
        databaseId:
          type: string
          description: >-
            Identificador del tablero cuyos registros activarán la
            automatización.
          example: <database-id>
    DatabaseRecordUpdatedTrigger:
      type: object
      required:
        - type
        - databaseId
      properties:
        type:
          type: string
          const: database_record_updated
        databaseId:
          type: string
          description: >-
            Identificador del tablero cuyos registros activarán la
            automatización.
          example: <database-id>
    BrowserUseStep:
      type: object
      additionalProperties: false
      required:
        - actionKey
        - task
        - resultSchema
        - wait
      properties:
        id:
          type: string
        name:
          type: string
        actionKey:
          type: string
          const: browser.use
        task:
          type: string
          minLength: 1
          maxLength: 20000
          description: Tarea para el navegador. Acepta plantillas {{...}}.
        resultSchema:
          type: object
          required:
            - type
          properties:
            type:
              type: string
              const: object
          additionalProperties: true
          description: JSON Schema del output esperado. No debe declarar _files.
        wait:
          type: object
          additionalProperties: false
          properties:
            initialDelaySeconds:
              type: integer
              minimum: 0
              maximum: 604800
              default: 30
            pollIntervalSeconds:
              type: integer
              minimum: 1
              maximum: 3600
              default: 15
            timeoutSeconds:
              type: integer
              minimum: 2
              maximum: 604800
              default: 3600
    BrowserScriptStep:
      type: object
      required:
        - actionKey
        - code
      properties:
        id:
          type: string
        name:
          type: string
        actionKey:
          type: string
          const: browser.script
        code:
          type: string
          minLength: 1
          maxLength: 100000
          description: JavaScript que dirige al agente de IA con el objeto `browser`.
        input:
          type: object
          additionalProperties: true
          description: Variables disponibles como `input.*`. Acepta plantillas {{...}}.
        timeoutMs:
          type: number
    DelayStep:
      type: object
      required:
        - actionKey
        - input
      properties:
        id:
          type: string
        name:
          type: string
        actionKey:
          type: string
          const: system.delay
        input:
          type: object
          required:
            - mode
            - amount
            - unit
          properties:
            mode:
              type: string
              enum:
                - duration
            amount:
              type: integer
              minimum: 1
            unit:
              type: string
              enum:
                - seconds
                - minutes
                - hours
                - days
    HttpStep:
      type: object
      required:
        - actionKey
        - input
      properties:
        id:
          type: string
        name:
          type: string
        actionKey:
          type: string
          const: http.request
        input:
          type: object
          required:
            - method
            - url
          properties:
            method:
              type: string
              enum:
                - GET
                - POST
                - PUT
                - PATCH
                - DELETE
            url:
              type: string
            headers:
              type: object
              additionalProperties:
                type: string
            query:
              type: object
              additionalProperties: true
            body: {}
    CodeStep:
      type: object
      required:
        - actionKey
        - code
      properties:
        id:
          type: string
        name:
          type: string
        actionKey:
          type: string
          const: code.javascript
        code:
          type: string
        input:
          type: object
          additionalProperties: true
        timeoutMs:
          type: number
  responses:
    BadRequest:
      description: Solicitud inválida.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
    Unauthorized:
      description: API key inválida o faltante.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/AuthError'
          example:
            message: Invalid API key.
    InternalError:
      description: Error inesperado.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
  securitySchemes:
    IbApiKey:
      type: apiKey
      in: header
      name: x-ib-api-key
      description: API key emitida por Insurance Boosters.

````