Check Background Jobs

Monitor the status of asynchronous operations such as role assignments, cascade knowledge deletion, taxonomy publishing, and other workflow-backed operations. When an endpoint runs asynchronously, it returns a workflowId — pass it here to track progress.

Endpoint

POST /v1/workspaces/{workspaceId}/background-jobs

Authentication

Requires API key authentication with a valid access token.

Request

curl -X POST \
  'https://api.sharely.ai/v1/workspaces/{workspaceId}/background-jobs' \
  -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  -H 'Content-Type: application/json' \
  -H 'organizationid: your-organization-id' \
  -d '{
    "jobIds": ["workflow-id-1", "workflow-id-2"]
  }'

Path Parameters

ParameterTypeRequiredDescription
workspaceIdstring (UUID)YesThe unique identifier of the workspace

Headers

HeaderTypeRequiredDescription
AuthorizationstringYesBearer token with access token
organizationidstring (UUID)YesYour organization ID
Content-TypestringYesMust be application/json

Body Parameters

ParameterTypeRequiredDescription
jobIdsarray of stringsNoWorkflow IDs to check (as returned by async endpoints). Omit to check all background jobs recorded for the workspace

Response

Success Response (200 OK)

Returns an array — one entry per matched job. Returns [] if no jobs match.

[
  {
    "workflowId": "workflow-id-1",
    "status": { "code": 2, "name": "COMPLETED" },
    "runId": "0190a1b2-c3d4-..."
  },
  {
    "workflowId": "workflow-id-2",
    "status": { "code": 1, "name": "RUNNING" },
    "runId": "0190a1b2-e5f6-..."
  }
]

Response Fields

FieldTypeDescription
workflowIdstringThe workflow ID you passed in (or that the async endpoint returned)
statusobjectWorkflow execution status
status.namestringOne of RUNNING, COMPLETED, FAILED, CANCELLED, TERMINATED, TIMED_OUT, CONTINUED_AS_NEW
status.codenumberNumeric status code corresponding to status.name
runIdstringThe underlying workflow run identifier (useful when contacting support)

Job Statuses

  • RUNNING — the job is currently being processed
  • COMPLETED — the job finished successfully; verify the resulting resource via its own GET endpoint
  • FAILED / TERMINATED / TIMED_OUT — the job did not complete; retry the originating operation or contact support with the workflowId and runId
  • CANCELLED — the job was cancelled before completion

Example Usage

Node.js - Polling Pattern

async function waitForJobs(workspaceId, jobIds, accessToken, organizationId) {
  const maxAttempts = 30;
  const pollInterval = 2000; // 2 seconds
 
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const response = await fetch(
      `https://api.sharely.ai/v1/workspaces/${workspaceId}/background-jobs`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${accessToken}`,
          'Content-Type': 'application/json',
          'organizationid': organizationId
        },
        body: JSON.stringify({ jobIds })
      }
    );
 
    const jobs = await response.json();
 
    // Check if all jobs reached a terminal state
    const allDone = jobs.every(job =>
      ['COMPLETED', 'FAILED', 'CANCELLED', 'TERMINATED', 'TIMED_OUT'].includes(job.status.name)
    );
 
    if (allDone) {
      return jobs;
    }
 
    // Wait before next poll
    await new Promise(resolve => setTimeout(resolve, pollInterval));
  }
 
  throw new Error('Jobs did not complete within timeout');
}

Python - With Exponential Backoff

import requests
import time
 
TERMINAL = {'COMPLETED', 'FAILED', 'CANCELLED', 'TERMINATED', 'TIMED_OUT'}
 
def check_background_jobs(workspace_id, job_ids, access_token, organization_id):
    max_attempts = 30
    base_interval = 1  # Start with 1 second
 
    for attempt in range(max_attempts):
        response = requests.post(
            f'https://api.sharely.ai/v1/workspaces/{workspace_id}/background-jobs',
            headers={
                'Authorization': f'Bearer {access_token}',
                'Content-Type': 'application/json',
                'organizationid': organization_id
            },
            json={'jobIds': job_ids}
        )
 
        response.raise_for_status()
        jobs = response.json()
 
        if all(job['status']['name'] in TERMINAL for job in jobs):
            return jobs
 
        # Exponential backoff
        wait_time = min(base_interval * (2 ** attempt), 30)
        time.sleep(wait_time)
 
    raise TimeoutError('Jobs did not complete within timeout')

Best Practices

  1. Poll Interval: Start with 1-2 second intervals, increase with exponential backoff
  2. Timeout: Set a reasonable timeout (30-60 seconds for most operations)
  3. Batch Checking: Check multiple workflow IDs in a single request
  4. Verify outcomes: The status tells you the workflow finished, not what it produced — confirm via the resource's own GET endpoint
  5. Keep IDs for support: Log workflowId and runId for failed jobs

Related Endpoints