Documents

Los endpoints de Documents te permiten crear, consultar, actualizar y gestionar documentos en AllSign. Un documento representa un archivo PDF (o DOCX que se convierte automáticamente) listo para firma electrónica.


POST/v2/documents

Create document

Crea un documento nuevo en AllSign. Este endpoint ejecuta el flujo completo de créditos empresariales: reserva del crédito document_signature, proceso del archivo y liquidación/seguimiento del uso.

Soporta dos modos de ejecución mediante el query parameter mode:

  • sync (default): Espera a que se procese completamente y retorna 201 Created con el documento listo.
  • async: Retorna inmediatamente 202 Accepted con un workflowId para rastrear el progreso via SSE.
API Key

Request Builder

Código generado

{
"document": {
"name": "contrato.pdf",
"base64Content": "<BASE64_CONTENT>"
},
"signatureValidation": {
"autografa": true,
"id_reuse_policy": "always_new"
}
}
← Configura tu API key primero

Respuesta

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

⚠️ Edge Cases y Validaciones422

Edge Cases y Validaciones

Combinaciones que producen errores de validación (422 Unprocessable Entity)

⚠️ skip
sendInvitations: true + participante sin email ni WhatsApp

La API detecta automáticamente el canal por participante. Si un participante no tiene email ni WhatsApp, se omite con advertencia.

422
startAtStep: 3 + sin participantes

Step 3 = esperando firmas, necesita al menos un firmante definido.

422
sendInvitations: true + startAtStep: 1

Las invitaciones solo se envían en step 3. Cambia startAtStep a 3.

422
folderId + folderName enviados juntos

Son mutuamente excluyentes. Usa uno u otro para organizar en carpeta.

422
fields referenciando email que no existe en participants

Cada campo de firma debe referenciar un participantEmail que exista en el array de participants.

422
Participante duplicado (mismo email)

Los emails e identificadores WhatsApp deben ser únicos entre todos los participantes.

422
anchorString + position en el mismo field

Los modos de placement son mutuamente excluyentes: usa coordenadas (position) o anchor (texto), no ambos.

422
pageNumbers + includeInAllPages

Elige una estrategia: páginas específicas (pageNumbers) o todas las páginas (includeInAllPages).

422
Base64 inválido o archivo >50MB

El contenido debe ser Base64 válido y el archivo decodificado debe pesar menos de 50MB.

Query parameters

  • Name
    mode
    Type
    string
    Description

    Modo de ejecución: sync (default) o async. En modo async, el endpoint retorna inmediatamente con un workflowId en lugar de esperar a que se procese el documento. Usa el endpoint de progreso SSE para rastrear el estado.

Request body

Existen dos modos de creación — envía uno de los dos:

  • Subida directa: proporciona document con base64Content y name.
  • Desde template: proporciona templateId (y opcionalmente templateValues).
  • Name
    document
    Type
    object
    Description

    Objeto con el archivo a subir. Requerido a menos que se use templateId. Ver objeto Document.

  • Name
    document.base64Content
    Type
    string
    Description

    Contenido del archivo codificado en Base64 (máx. 50 MB decodificados). Requerido cuando se usa document.

  • Name
    document.name
    Type
    string
    Description

    Nombre original del archivo con extensión (ej. contrato.pdf). Requerido cuando se usa document.

  • Name
    templateId
    Type
    string
    Description

    UUID de un template DOCX previamente creado. Cuando se proporciona, el backend descarga el DOCX desde S3 y lo usa como fuente del documento. Mutuamente exclusivo con document.

  • Name
    templateValues
    Type
    object
    Description

    Pares clave-valor para inyectar en las variables &#123;&#123;variable&#125;&#125; del template. Solo se usa cuando templateId está presente. Ejemplo: {"nombre_cliente": "Pedro Páramo", "monto": "$150,000.00 MXN"}.

  • Name
    participants
    Type
    array
    Description

    Lista de firmantes. Cada participante debe tener email o whatsapp (no ambos), y name. Ver objeto Participant.

  • Name
    fields
    Type
    array
    Description

    Campos de firma a crear junto con el documento. Ver Campos de firma.

  • Name
    signatureValidation
    Type
    object
    Description

    Configuración de validaciones de firma. Ver objeto Document.

  • Name
    config
    Type
    object
    Description

    Controla el flujo de invitaciones. Ver objeto Document.

  • Name
    permissions
    Type
    object
    Description

    Define el propietario y colaboradores. Ver objeto Document.

  • Name
    folderId
    Type
    string
    Description

    ID de carpeta donde organizar el documento. No se puede usar junto con folderName.

  • Name
    folderName
    Type
    string
    Description

    Nombre de carpeta — busca una existente o crea una nueva. Se ignora si folderId también está presente. Máx. 255 caracteres.

  • Name
    placeholders
    Type
    object
    Description

    Pares clave-valor para reemplazar en documentos DOCX (ej. {"nombre_cliente": "Juan"} reemplaza &#123;&#123; nombre_cliente &#125;&#125; en el template). Solo aplica para archivos .docx, se ignora para PDFs.

Response

Errores posibles

StatusCuándo ocurre
402 Payment RequiredCréditos insuficientes para el documento
422 Unprocessable EntityUno o más correos de participantes no son entregables
500 Internal Server ErrorError inesperado en el pipeline

Ejemplo 422 — email no entregable:

Response (422) — Participant email invalid

{
  "success": false,
  "error_code": "EMAIL_VALIDATION_FAILED",
  "message": "One or more participant emails cannot receive messages. Check the 'participants' field and correct the following: firmante@invaliddomain.xyz: domain cannot receive email (no MX records)",
  "details": [
    {
      "email": "firmante@invaliddomain.xyz",
      "reason": "domain cannot receive email (no MX records)",
      "suggestion": null
    }
  ]
}

Modo síncrono (mode=sync, default)

Devuelve el documento creado con su ID único. 201 Created en éxito, 402 Payment Required si no hay créditos suficientes.

Response (201) — Sync mode

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "contrato.pdf",
  "pdfHash": "a1b2c3d4e5f6...",
  "description": null,
  "createdAt": "2024-11-23T20:00:00Z",
  "creditsConsumed": 1
}

Modo asíncrono (mode=async)

Retorna inmediatamente 202 Accepted con un workflowId para rastrear el progreso. El documentId aún no está disponible — se obtiene del endpoint SSE de progreso cuando se completa.

Response (202) — Async mode

{
  "status": "processing",
  "workflowId": "doc-create-550e8400-e29b-41d4-a716-446655440000",
  "progressUrl": "/v2/documents/workflows/doc-create-550e8400-e29b-41d4-a716-446655440000/progress"
}

GET/v2/documents/workflows/{workflowId}/progress

Stream document progress (SSE)

Endpoint de Server-Sent Events (SSE) para recibir progreso en tiempo real de un workflow de creación de documentos iniciado con mode=async.

GET/v2/documents/workflows/{workflowId}/progress
ProdTest
API Key

Path parameters

curl -X GET "https://api.allsign.io/v2/documents/workflows/{workflowId}/progress" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Path parameters

  • Name
    workflowId
    Type
    string
    Description

    ID del workflow retornado por POST /v2/documents?mode=async.

Response

Retorna un stream text/event-stream con los siguientes tipos de eventos:

Evento: connected

Se envía inmediatamente al conectar.

Event: connected

{
  "workflowId": "doc-create-550e8400-e29b-41d4-a716-446655440000"
}

Evento: progress

Se envía en cada paso del procesamiento.

Event: progress

{
  "step": "processing",
  "progress": 25,
  "message": "Procesando documento..."
}

Pasos del workflow:

StepProgressDescripción
security5%Verificando permisos y seguridad
credits15%Reservando créditos
validating20%Validando correos de participantes
processing25%Procesando el archivo PDF
saving50%Persistiendo en la base de datos
relations65%Configurando acceso y relaciones
finalizing85%Finalizando configuración

Evento: complete

Se envía cuando el documento está listo. Este evento contiene el documentId final.

Event: complete

{
  "step": "complete",
  "progress": 100,
  "message": "¡Documento listo!",
  "documentId": "550e8400-e29b-41d4-a716-446655440000",
  "creditsConsumed": 1
}

Evento: error

Se envía si el procesamiento falla.

Event: error

{
  "code": "PROCESSING_FAILED",
  "message": "Error al procesar el documento"
}

Ejemplo: Flujo completo async

Python — Crear documento y escuchar progreso

import requests
import sseclient

API_KEY = "allsign_live_sk_TU_API_KEY"
BASE_URL = "https://api.allsign.io"
HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}

# 1. Crear documento en modo async
response = requests.post(
    f"{BASE_URL}/v2/documents/?mode=async",
    headers=HEADERS,
    json={
        "document": {
            "base64Content": "JVBERi0xLjQK...",
            "name": "contrato.pdf"
        },
        "participants": [
            {"email": "firmante@ejemplo.com", "name": "Juan"}
        ]
    }
)

data = response.json()
print(f"Workflow iniciado: {data['workflowId']}")
# → Workflow iniciado: doc-create-550e8400-e29b-41d4-a716-446655440000

# 2. Escuchar progreso via SSE
sse_url = f"{BASE_URL}{data['progressUrl']}"
sse_response = requests.get(sse_url, headers=HEADERS, stream=True)
client = sseclient.SSEClient(sse_response)

for event in client.events():
    if event.event == "progress":
        info = json.loads(event.data)
        print(f"  [{info['progress']}%] {info['message']}")
    elif event.event == "complete":
        result = json.loads(event.data)
        print(f"✅ Documento listo: {result['documentId']}")
        break
    elif event.event == "error":
        error = json.loads(event.data)
        print(f"❌ Error: {error['message']}")
        break

JavaScript — fetch + ReadableStream (navegador)

// 1. Crear documento en modo async
const response = await fetch('https://api.allsign.io/v2/documents/?mode=async', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer allsign_live_sk_TU_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    document: {
      base64Content: 'JVBERi0xLjQK...',
      name: 'contrato.pdf',
    },
    participants: [
      { email: 'firmante@ejemplo.com', name: 'Juan' },
    ],
  }),
});

const { workflowId, progressUrl } = await response.json();
console.log('Workflow iniciado:', workflowId);

// 2. Escuchar progreso via SSE con fetch (soporta Authorization header)
// ⚠️ EventSource nativo NO soporta custom headers — usamos fetch + ReadableStream
const sseResponse = await fetch(`https://api.allsign.io${progressUrl}`, {
  headers: { 'Authorization': 'Bearer allsign_live_sk_TU_API_KEY' },
});

const reader = sseResponse.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split('\n');
  buffer = lines.pop(); // conservar línea incompleta

  let eventType = '';
  for (const line of lines) {
    if (line.startsWith('event: ')) eventType = line.slice(7);
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.slice(6));

      if (eventType === 'progress') {
        console.log(`[${data.progress}%] ${data.message}`);
        // Actualizar UI con el progreso...
      } else if (eventType === 'complete') {
        console.log('✅ Documento listo:', data.documentId);
        reader.cancel();
        window.location.href = `/documentos/${data.documentId}`;
        return;
      } else if (eventType === 'error') {
        console.error('❌ Error:', data.message);
        reader.cancel();
        return;
      }
    }
  }
}

GET/v2/documents/workflows/{workflowId}/status

Poll document status (JSON)

Endpoint ligero de JSON para consultar el estado de un workflow de creación de documentos. Ideal para integraciones que prefieren polling simple sobre SSE.

Haz polling cada 2-5 segundos hasta que status sea completed o failed.

GET/v2/documents/workflows/{workflowId}/status
ProdTest
API Key

Path parameters

curl -X GET "https://api.allsign.io/v2/documents/workflows/{workflowId}/status" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Path parameters

  • Name
    workflowId
    Type
    string
    Description

    ID del workflow retornado por POST /v2/documents?mode=async.

Response

  • Name
    status
    Type
    string
    Description

    Estado actual: processing, completed, o failed.

  • Name
    step
    Type
    string
    Description

    Paso actual del pipeline (security, credits, processing, saving, relations, finalizing, complete).

  • Name
    progress
    Type
    integer
    Description

    Porcentaje de progreso (0-100).

  • Name
    message
    Type
    string
    Description

    Mensaje legible del estado actual.

  • Name
    documentId
    Type
    string
    Description

    ID del documento creado (solo cuando status=completed).

  • Name
    creditsConsumed
    Type
    integer
    Description

    Créditos consumidos (solo cuando status=completed).

  • Name
    error
    Type
    string
    Description

    Mensaje de error (solo cuando status=failed).

Response — Processing

{
  "status": "processing",
  "step": "saving",
  "progress": 50,
  "message": "Guardando documento..."
}

Response — Completed

{
  "status": "completed",
  "step": "complete",
  "progress": 100,
  "message": "¡Documento listo!",
  "documentId": "550e8400-e29b-41d4-a716-446655440000",
  "creditsConsumed": 1
}

Response — Failed

{
  "status": "failed",
  "step": "error",
  "error": "Créditos insuficientes"
}

Ejemplo: Polling con JavaScript

JavaScript — Polling cada 2 segundos

// 1. Crear documento en modo async
const createRes = await fetch('https://api.allsign.io/v2/documents/?mode=async', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer allsign_live_sk_TU_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    document: { base64Content: 'JVBERi0xLjQK...', name: 'contrato.pdf' },
    participants: [{ email: 'firmante@ejemplo.com', name: 'Juan' }],
  }),
});

const { workflowId } = await createRes.json();

// 2. Polling cada 2 segundos
let result;
while (true) {
  const res = await fetch(
    `https://api.allsign.io/v2/documents/workflows/${workflowId}/status`,
    { headers: { 'Authorization': 'Bearer allsign_live_sk_TU_API_KEY' } }
  );
  const status = await res.json();

  console.log(`[${status.progress}%] ${status.message}`);

  if (status.status === 'completed') {
    result = status;
    break;
  }
  if (status.status === 'failed') {
    throw new Error(status.error);
  }
  await new Promise(r => setTimeout(r, 2000));
}

console.log('✅ Document ready:', result.documentId);

GET/v2/documents/{id}

Retrieve document

Consulta los detalles de un documento existente.

GET/v2/documents/{id}
ProdTest
API Key

Path parameters

curl -X GET "https://api.allsign.io/v2/documents/{id}" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Path parameters

  • Name
    id
    Type
    string
    Description

    ID único del documento (UUID).

Response

Devuelve el objeto Document completo, incluyendo signersData con el estado de cada firma.

Response (200)

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Contract 2024.pdf",
  "documentType": "EDITABLE",
  "createdAt": "2024-11-23T10:00:00Z",
  "updatedAt": "2024-11-23T10:00:00Z",
  "ownerId": "550e8400-e29b-41d4-a716-446655440001",
  "orgId": "550e8400-e29b-41d4-a716-446655440002",
  "categoryId": 1,
  "activePublicUrl": false,
  "signersData": {
    "id": "cdc27f13-4d05-47d0-9690-fb69d005e7f8",
    "status": "TODOS_FIRMARON",
    "signatures": [
      {
        "id": "63db6fa9-2709-4f68-9ea7-bc640194bade",
        "status": "SIGNED",
        "signer": {
          "id": "99dc8f00-be5f-4331-ae66-db71bc2f6ccb",
          "email": "firmante@empresa.com"
        }
      }
    ]
  },
  "folders": [
    {
      "id": "111e8400-e29b-41d4-a716-446655440000",
      "name": "Contratos",
      "parentId": null
    }
  ]
}

GET/v2/documents

List documents

Lista documentos con paginación por cursor y filtros avanzados. Soporta filtrado por equipo, por miembro específico o solo tus documentos.

GET/v2/documents
ProdTest

Configuraciones pre-cargadas

API Key

Query parameters

curl -X GET "https://api.allsign.io/v2/documents" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Query parameters

  • Name
    limit
    Type
    integer
    Description

    Resultados por página (1-100, default: 10).

  • Name
    cursor
    Type
    string
    Description

    Token de paginación obtenido del meta.nextCursor de la respuesta anterior.

  • Name
    scope
    Type
    string
    Description

    Alcance de búsqueda: owner (default), org, tenant, accessible.

  • Name
    search
    Type
    string
    Description

    Búsqueda por texto libre en el nombre del documento.

  • Name
    signatureStatus
    Type
    string
    Description

    Filtra por estado de firma: TODOS_FIRMARON, ESPERANDO_FIRMAS, RECOLECTANDO_FIRMANTES, CONFIGURANDO, EXPIRADO.

  • Name
    folderId
    Type
    string
    Description

    Filtra documentos por carpeta.

  • Name
    createdAfter
    Type
    datetime
    Description

    Filtrar documentos creados después de esta fecha (ISO 8601).

  • Name
    createdBefore
    Type
    datetime
    Description

    Filtrar documentos creados antes de esta fecha (ISO 8601).

  • Name
    orgId
    Type
    string
    Description

    Filtra documentos por organización.

  • Name
    createdBy
    Type
    string
    Description

    Filtra documentos creados por un usuario específico (UUID). Requiere rol de admin/owner o el permiso documents:view_all. El usuario indicado debe pertenecer al mismo tenant. Si se omite, retorna todos los documentos visibles según el scope.

  • Name
    forUserId
    Type
    string
    Description

    UUID de un usuario del mismo tenant. Filtra documentos donde este usuario es creador, firmante o tiene acceso. Requiere rol de admin/owner.

  • Name
    sortBy
    Type
    string
    Description

    Campo de ordenamiento: created_at (default), updated_at, name, document_type.

  • Name
    sortOrder
    Type
    string
    Description

    Dirección: asc o desc (default).

  • Name
    includeSigners
    Type
    boolean
    Description

    Incluir datos de firmantes en la respuesta (default: true).

  • Name
    includeFolders
    Type
    boolean
    Description

    Incluir carpetas del documento (default: false).

  • Name
    includeDocumentStats
    Type
    boolean
    Description

    Incluir estadísticas agregadas (default: false).

  • Name
    includeAllHistory
    Type
    boolean
    Description

    Desactiva el rango por defecto de 365 días, retornando el historial completo (default: false). No se puede combinar con createdAfter/createdBefore.

Response

Devuelve un array de documentos con metadata de paginación por cursor.

Response (200)

{
  "success": true,
  "message": "Documents retrieved successfully",
  "data": [
    {
      "id": "550e8400-e29b-41d4-a716-446655440000",
      "name": "Contrato de Servicios 2025.pdf",
      "documentType": "EDITABLE",
      "createdAt": "2024-11-23T20:00:00Z",
      "updatedAt": "2024-11-23T20:00:00Z",
      "ownerId": "550e8400-e29b-41d4-a716-446655440001",
      "orgId": "550e8400-e29b-41d4-a716-446655440002",
      "categoryId": 1,
      "activePublicUrl": false,
      "signersData": {
        "id": "cdc27f13-4d05-47d0-9690-fb69d005e7f8",
        "status": "ESPERANDO_FIRMAS",
        "signatures": [
          {
            "id": "63db6fa9-2709-4f68-9ea7-bc640194bade",
            "status": "SENT",
            "signer": {
              "id": "99dc8f00-be5f-4331-ae66-db71bc2f6ccb",
              "email": "firmante@empresa.com"
            }
          }
        ]
      }
    }
  ],
  "meta": {
    "limit": 10,
    "total": null,
    "hasNext": true,
    "nextCursor": "eyJzb3J0X2ZpZWxkIjoi...",
    "prevCursor": null
  }
}

PATCH/v2/documents/{id}

Update document

Actualiza parcialmente un documento. Solo los campos enviados se modifican — el resto permanece igual.

PATCH/v2/documents/{id}
ProdTest
API Key

Path parameters

Request body

curl -X PATCH "https://api.allsign.io/v2/documents/{id}" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Path parameters

  • Name
    id
    Type
    string
    Description

    ID único del documento (UUID).

Request body

Todos los campos son opcionales. Solo envía los que quieres cambiar.

  • Name
    name
    Type
    string
    Description

    Nuevo nombre del documento (1-255 caracteres).

  • Name
    folderId
    Type
    string | null
    Description

    Mover a carpeta ("uuid"), o null para quitar de carpeta.

  • Name
    status
    Type
    string
    Description

    Avanzar el estado del documento. Solo se permiten transiciones específicas — ver status lifecycle. Actualmente la única transición permitida via PATCH es RECOLECTANDO_FIRMANTESSELLOS_PDF.

  • Name
    config
    Type
    object
    Description

    Actualizaciones de configuración (sendInvitations, startAtStep, expiresAt, expirationReminders).

  • Name
    signatureValidation
    Type
    object
    Description

    Actualizaciones de validaciones de firma (autografa, FEA, eIDAS, nom151, videofirma, etc.).

  • Name
    permissions
    Type
    object
    Description

    Actualizaciones de permisos (ownerEmail, collaborators, isPublicRead).

Response

Devuelve el documento actualizado con el formato DocumentV2Response.

Response (200)

{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "Contrato Final v2.pdf",
  "documentType": "EDITABLE",
  "createdAt": "2024-11-23T10:00:00Z",
  "updatedAt": "2024-11-24T15:30:00Z",
  "ownerId": "550e8400-e29b-41d4-a716-446655440001",
  "orgId": "550e8400-e29b-41d4-a716-446655440002",
  "categoryId": 1,
  "activePublicUrl": false,
  "signersData": null
}

Error: invalid status transition

Si intentas una transición no permitida, recibirás un error descriptivo indicando qué transiciones son válidas desde el estado actual.

Response (400) — Invalid transition

{
  "detail": "Status transition 'SELLOS_PDF' → 'RECOLECTANDO_FIRMANTES' is not allowed via PATCH. Allowed transitions from 'SELLOS_PDF': none."
}

POST/v2/documents/{id}/extend

Extend document deadline

Extiende o reactiva el deadline de firma de un documento. Solo el propietario del documento puede extender el deadline.

Si el documento está en estado EXPIRADO, será reactivado a ESPERANDO_FIRMAS con el nuevo deadline.

POST/v2/documents/{id}/extend
ProdTest
API Key

Path parameters

Request body

curl -X POST "https://api.allsign.io/v2/documents/{id}/extend" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Path parameters

  • Name
    id
    Type
    string
    Description

    ID único del documento (UUID).

Request body

  • Name
    newExpiresAt
    Type
    datetime
    Description

    Nueva fecha límite de firma (ISO 8601). Debe ser una fecha futura.

Response

Response (200)

{
  "success": true,
  "newExpiresAt": "2025-06-30T23:59:59+00:00",
  "extendedCount": 1,
  "previousStatus": "EXPIRADO",
  "newStatus": "ESPERANDO_FIRMAS"
}

GET/v2/documents/stats

Document statistics

Obtén estadísticas agregadas de tus documentos.

GET/v2/documents/stats
ProdTest
API Key

Query parameters

curl -X GET "https://api.allsign.io/v2/documents/stats" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Query parameters

  • Name
    scope
    Type
    string
    Description

    Alcance: owner, org, tenant, accessible (default: accessible).

  • Name
    createdAfter
    Type
    datetime
    Description

    Inicio del rango de fechas (ISO 8601).

  • Name
    createdBefore
    Type
    datetime
    Description

    Fin del rango de fechas (ISO 8601).

  • Name
    includeAllHistory
    Type
    boolean
    Description

    Desactiva el rango por defecto de 365 días (default: false). No se puede combinar con createdAfter/createdBefore.

Response (200)

{
  "totalDocuments": 150,
  "totalCompleted": 42,
  "totalPending": 93,
  "totalConfiguring": 15,
  "recentCount": 12
}

DELETE/v2/documents/{documentId}

Delete document

Elimina un documento individual junto con todos sus registros asociados (firmas, eventos, PDFs, evidencia, constancias NOM-151) mediante cascadas de base de datos. Los archivos en S3 se limpian en segundo plano.

Requiere el scope document:delete o document:*. Solo se pueden eliminar documentos que pertenezcan al mismo tenant del API key.

Reglas de eliminación por estado

Estado del documento¿Se puede eliminar?Detalle
Sin firma (draft)✅ SíNo existe flujo de firma
SELLOS_PDF✅ SíEtapa temprana de configuración
RECOLECTANDO_FIRMANTES✅ SíAún no se han enviado invitaciones
EXPIRADO✅ SíEl documento expiró
ESPERANDO_FIRMAS❌ NoFirmas en progreso — anula el documento primero
CORRIGIENDO❌ NoCorrección en progreso
GENERANDO_PDF❌ NoGeneración de PDF en progreso
TODOS_FIRMARON❌ NoDocumento legalmente vinculante
DELETE/v2/documents/{documentId}
ProdTest

Configuraciones pre-cargadas

API Key

Path parameters

curl -X DELETE "https://api.allsign.io/v2/documents/{documentId}" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Path parameters

  • Name
    documentId
    Type
    string
    Description

    UUID del documento a eliminar.

Request

DELETE
/v2/documents/{documentId}
curl -X DELETE "https://api.allsign.io/v2/documents/550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Response

Response (200)

{
  "success": true,
  "message": "Document deleted successfully",
  "documentId": "550e8400-e29b-41d4-a716-446655440000",
  "s3KeysCleaned": 3
}

Error — document not found (404)

{
  "error": {
    "code": "E1300",
    "type": "not_found",
    "message": "Document not found"
  }
}

Error — signed document (409)

{
  "error": {
    "code": "E1600",
    "type": "conflict",
    "message": "Document is fully signed and legally binding. Signed documents cannot be deleted."
  }
}

Error — signatures in progress (409)

{
  "error": {
    "code": "E1600",
    "type": "conflict",
    "message": "Document has signatures in progress. Void the document before deleting."
  }
}

DELETE/v2/documents/bulk

Delete documents (bulk)

Elimina múltiples documentos en una sola llamada. Los documentos se eliminan de forma atómica junto con todos sus registros asociados (firmas, eventos, PDFs, evidencia, constancias NOM-151) mediante cascadas de base de datos. Los archivos en S3 se limpian en segundo plano.

Requiere el scope document:delete o document:*. Solo se pueden eliminar documentos que pertenezcan al mismo tenant del API key.

DELETE/v2/documents/bulk
ProdTest

Configuraciones pre-cargadas

API Key

Request body

curl -X DELETE "https://api.allsign.io/v2/documents/bulk" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK"

Configura el request y haz click en Enviar Request para ver la respuesta aquí.

Request body

  • Name
    documentIds
    Type
    string[]
    Description

    Lista de IDs de documentos a eliminar (UUIDs). Mínimo 1, máximo 100.

Request

DELETE
/v2/documents/bulk
curl -X DELETE "https://api.allsign.io/v2/documents/bulk" \
  -H "Authorization: Bearer ALLSIGN_LIVE_SK" \
  -H "Content-Type: application/json" \
  -d '{
    "documentIds": [
      "550e8400-e29b-41d4-a716-446655440000",
      "660f9511-f3ac-52e5-b827-557766551111",
      "770a0622-a4bd-63f6-c938-668877662222"
    ]
  }'

Response

Devuelve un resumen con el conteo de documentos eliminados y fallidos, además de detalles individuales por documento.

Response — all deleted (200)

{
  "success": true,
  "message": "3 document(s) deleted successfully",
  "deletedCount": 3,
  "failedCount": 0,
  "details": [
    { "documentId": "550e8400-e29b-41d4-a716-446655440000", "success": true },
    { "documentId": "660f9511-f3ac-52e5-b827-557766551111", "success": true },
    { "documentId": "770a0622-a4bd-63f6-c938-668877662222", "success": true }
  ]
}

Response — partial success (200)

{
  "success": true,
  "message": "1 document(s) deleted successfully",
  "deletedCount": 1,
  "failedCount": 2,
  "details": [
    { "documentId": "550e8400-e29b-41d4-a716-446655440000", "success": true },
    { "documentId": "660f9511-f3ac-52e5-b827-557766551111", "success": false, "error": "Document is fully signed and legally binding. Signed documents cannot be deleted." },
    { "documentId": "invalid-or-unauthorized-id", "success": false, "error": "Document not found" }
  ]
}

Error — empty list (422)

{
  "error": {
    "code": "E1200",
    "type": "validation_error",
    "message": "List should have at least 1 item after validation, not 0",
    "field": "documentIds"
  }
}

Error — insufficient permissions (403)

{
  "error": {
    "code": "E1100",
    "type": "permission_error",
    "message": "Insufficient permissions. Required: document:delete or document:*."
  }
}

Was this page helpful?