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

# Cancel Job

> Attempts to cancel an asynchronous job that is currently pending
or processing. Jobs that have already completed will remain unchanged.


## Overview

Cancel an asynchronous job that is currently pending or processing.

Jobs that have already completed, failed, or been canceled will remain unchanged.

## Response

A successful cancellation returns a confirmation message:

```json theme={null}
{
  "job_id": "abc123-def456-ghi789",
  "message": "Job cancelled successfully"
}
```

### Response Fields

| Field     | Type   | Description                               |
| --------- | ------ | ----------------------------------------- |
| `job_id`  | string | Identifier of the job that was cancelled. |
| `message` | string | Human-readable confirmation message.      |

## When to Cancel Jobs

Cancel jobs when:

* The extraction is no longer needed
* You submitted a job with incorrect parameters
* You want to stop processing to conserve page usage

<Note>
  Cancellation is best-effort. If a job is already mid-processing, it may complete before the cancellation takes effect. Pages used before cancellation are still counted toward your usage.
</Note>

## Example Usage

### Cancel a Job

<CodeGroup>
  ```python Python SDK theme={null}
  from pulse import Pulse

  client = Pulse(api_key="YOUR_API_KEY")

  job_id = "abc123-def456-ghi789"

  try:
      response = client.jobs.cancel_job(job_id=job_id)
      print(f"Job {response.job_id} cancelled successfully")
      print(f"Message: {response.message}")
  except Exception as e:
      print(f"Failed to cancel job: {e}")
  ```

  ```typescript TypeScript SDK theme={null}
  import { PulseClient } from 'pulse-ts-sdk';

  const client = new PulseClient({
      apiKey: 'YOUR_API_KEY'
  });

  const jobId = "abc123-def456-ghi789";

  try {
      const response = await client.jobs.cancelJob({ jobId });
      console.log(`Job ${response.job_id} cancelled successfully`);
      console.log(`Message: ${response.message}`);
  } catch (error) {
      console.log(`Failed to cancel job: ${error}`);
  }
  ```

  ```bash curl theme={null}
  # Cancel a pending or processing job
  curl -X DELETE https://api.runpulse.com/job/abc123-def456-ghi789 \
    -H "x-api-key: YOUR_API_KEY"
  ```
</CodeGroup>

### Cancel with Error Handling

<CodeGroup>
  ```python Python SDK theme={null}
  from pulse import Pulse
  from pulse.core.api_error import ApiError

  client = Pulse(api_key="YOUR_API_KEY")

  def cancel_job_safely(job_id: str):
      """Cancel a job with comprehensive error handling."""
      try:
          response = client.jobs.cancel_job(job_id=job_id)
          print(f"✓ Job {job_id} cancelled successfully")
          return True
      except ApiError as e:
          if e.status_code == 404:
              print(f"✗ Job {job_id} not found")
          elif e.status_code == 403:
              print(f"✗ You don't have access to job {job_id}")
          elif e.status_code == 401:
              print(f"✗ Invalid or missing API key")
          else:
              print(f"✗ Failed to cancel job: {e}")
          return False
      except Exception as e:
          print(f"✗ Unexpected error: {e}")
          return False

  # Example usage
  cancel_job_safely("abc123-def456-ghi789")
  ```

  ```typescript TypeScript SDK theme={null}
  import { PulseClient } from 'pulse-ts-sdk';

  const client = new PulseClient({
      apiKey: 'YOUR_API_KEY'
  });

  async function cancelJobSafely(jobId: string): Promise<boolean> {
      /**
       * Cancel a job with comprehensive error handling.
       */
      try {
          const response = await client.jobs.cancelJob({ jobId });
          console.log(`✓ Job ${jobId} cancelled successfully`);
          return true;
      } catch (error: any) {
          if (error.statusCode === 404) {
              console.log(`✗ Job ${jobId} not found`);
          } else if (error.statusCode === 403) {
              console.log(`✗ You don't have access to job ${jobId}`);
          } else if (error.statusCode === 401) {
              console.log(`✗ Invalid or missing API key`);
          } else {
              console.log(`✗ Failed to cancel job: ${error.message}`);
          }
          return false;
      }
  }

  // Example usage
  cancelJobSafely("abc123-def456-ghi789");
  ```

  ```bash curl theme={null}
  #!/bin/bash

  JOB_ID="abc123-def456-ghi789"
  API_KEY="YOUR_API_KEY"

  response=$(curl -s -w "\n%{http_code}" -X DELETE \
      "https://api.runpulse.com/job/${JOB_ID}" \
      -H "x-api-key: ${API_KEY}")

  # Split response body and status code
  body=$(echo "$response" | head -n -1)
  status_code=$(echo "$response" | tail -n 1)

  case "$status_code" in
      200)
          echo "✓ Job ${JOB_ID} cancelled successfully"
          echo "$body" | jq .
          ;;
      401)
          echo "✗ Invalid or missing API key"
          ;;
      403)
          echo "✗ You don't have access to job ${JOB_ID}"
          ;;
      404)
          echo "✗ Job ${JOB_ID} not found"
          ;;
      *)
          echo "✗ Failed to cancel job (status $status_code)"
          echo "$body"
          ;;
  esac
  ```
</CodeGroup>

### Cancel Multiple Jobs

<CodeGroup>
  ```python Python SDK theme={null}
  from pulse import Pulse

  client = Pulse(api_key="YOUR_API_KEY")

  job_ids = [
      "job-111-aaa",
      "job-222-bbb", 
      "job-333-ccc"
  ]

  for job_id in job_ids:
      try:
          client.jobs.cancel_job(job_id=job_id)
          print(f"✓ Cancelled: {job_id}")
      except Exception as e:
          print(f"✗ Failed to cancel {job_id}: {e}")
  ```

  ```typescript TypeScript SDK theme={null}
  import { PulseClient } from 'pulse-ts-sdk';

  const client = new PulseClient({
      apiKey: 'YOUR_API_KEY'
  });

  const jobIds = [
      "job-111-aaa",
      "job-222-bbb",
      "job-333-ccc"
  ];

  for (const jobId of jobIds) {
      try {
          await client.jobs.cancelJob({ jobId });
          console.log(`✓ Cancelled: ${jobId}`);
      } catch (error: any) {
          console.log(`✗ Failed to cancel ${jobId}: ${error.message}`);
      }
  }
  ```

  ```bash curl theme={null}
  #!/bin/bash

  API_KEY="YOUR_API_KEY"
  JOB_IDS=("job-111-aaa" "job-222-bbb" "job-333-ccc")

  for job_id in "${JOB_IDS[@]}"; do
      status=$(curl -s -o /dev/null -w "%{http_code}" -X DELETE \
          "https://api.runpulse.com/job/${job_id}" \
          -H "x-api-key: ${API_KEY}")
      
      if [ "$status" = "200" ]; then
          echo "✓ Cancelled: $job_id"
      else
          echo "✗ Failed to cancel $job_id (status $status)"
      fi
  done
  ```
</CodeGroup>

## Error Responses

| Status | Description                                          |
| ------ | ---------------------------------------------------- |
| `401`  | Invalid or missing API key.                          |
| `403`  | You don't have access to this job.                   |
| `404`  | Job not found.                                       |
| `500`  | Job could not be cancelled or internal server error. |


## OpenAPI

````yaml DELETE /job/{jobId}
openapi: 3.1.0
info:
  title: Pulse API
  description: >-
    Production-grade document extraction service that transforms complex
    documents  into structured, AI-ready data. This specification is the single
    source of truth  for the Pulse extraction APIs.
  version: 1.0.0
  contact:
    name: Pulse Support
    email: support@trypulse.ai
    url: https://docs.runpulse.com
servers:
  - url: https://api.runpulse.com
    description: Production server
security:
  - ApiKeyAuth: []
paths:
  /job/{jobId}:
    delete:
      tags:
        - Jobs
      summary: Cancel Job
      description: |
        Attempts to cancel an asynchronous job that is currently pending
        or processing. Jobs that have already completed will remain unchanged.
      operationId: cancelJob
      parameters:
        - name: jobId
          in: path
          required: true
          description: Identifier returned from an async job submission.
          schema:
            type: string
      responses:
        '200':
          description: Job cancellation accepted
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/JobCancellationResponse'
        '401':
          $ref: '#/components/responses/Unauthorized'
        '403':
          $ref: '#/components/responses/Forbidden'
        '404':
          $ref: '#/components/responses/NotFound'
        '429':
          $ref: '#/components/responses/TooManyRequests'
        '500':
          $ref: '#/components/responses/InternalServerError'
      x-codeSamples:
        - lang: python
          label: Python SDK
          source: |
            from pulse import Pulse

            client = Pulse(api_key="YOUR_API_KEY")
            result = client.jobs.cancel_job(job_id="your-job-id")
            print(result)
        - lang: typescript
          label: TypeScript SDK
          source: >
            import { PulseClient } from "pulse-ts-sdk";


            const client = new PulseClient({
                apiKey: "YOUR_API_KEY"
            });

            const result = await client.jobs.cancelJob({ jobId: "your-job-id"
            });

            console.log(result);
        - lang: bash
          label: curl
          source: |
            curl -X DELETE https://api.runpulse.com/job/your-job-id \
              -H "x-api-key: YOUR_API_KEY"
components:
  schemas:
    JobCancellationResponse:
      type: object
      description: Confirmation payload returned after successfully canceling a job.
      required:
        - job_id
        - message
      properties:
        job_id:
          type: string
          description: Identifier of the job that was cancelled.
        message:
          type: string
          description: Human-readable confirmation message.
    ErrorResponse:
      type: object
      properties:
        error:
          type: object
          properties:
            code:
              type: string
              description: Error code (e.g., FILE_001, AUTH_002)
            message:
              type: string
              description: Human-readable error message
            details:
              type: object
              description: Additional error context
  responses:
    Unauthorized:
      description: Unauthorized - Invalid or missing API key
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    Forbidden:
      description: >-
        Forbidden - Authenticated principal does not have access to this
        resource
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFound:
      description: Resource not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    TooManyRequests:
      description: Rate limit exceeded
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    InternalServerError:
      description: Internal server error
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: x-api-key
      description: API key for authentication

````