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

# Cancel a Batch

> Stop a batch from starting new pages. In-progress pages finish, and unused credits are refunded.

<Badge color="green">0 Credits</Badge>


## OpenAPI

````yaml POST /batch/{batch_id}/cancel
openapi: 3.1.0
info:
  title: Context API
  description: API for retrieving context data from any website
  version: 1.0.0
servers:
  - url: https://api.context.dev/v1
security: []
tags:
  - name: Batch
    description: Scrape many pages or crawl a site asynchronously.
  - name: Monitors
    description: >-
      Monitor pages, sitemaps, and extracted website data for exact or semantic
      changes. Webhook payloads are documented by the
      MonitorsChangeDetectedWebhookPayload and
      MonitorsRunCompletedWebhookPayload schemas.
  - name: WebDBs
    description: Create structured tables from web pages and keep them up to date.
paths:
  /batch/{batch_id}/cancel:
    post:
      tags:
        - Batch
      summary: Cancel a batch
      description: >-
        Stop a batch from starting new pages. In-progress pages finish, and
        unused credits are refunded.
      operationId: cancelBatch
      parameters:
        - schema:
            type: string
            example: batch_9f2c8a
            description: ID of the batch to retrieve or cancel.
          required: true
          description: ID of the batch to retrieve or cancel.
          name: batch_id
          in: path
      responses:
        '202':
          description: >-
            Cancellation started. Poll `GET /batch/{batch_id}` until the batch
            settles.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/RateLimitReset'
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/BatchCancelling'
                  - type: object
                    properties:
                      key_metadata:
                        $ref: '#/components/schemas/KeyMetadata'
                        description: API key usage for this request.
        '401':
          $ref: '#/components/responses/Unauthorized'
        '404':
          $ref: '#/components/responses/NotFound'
        '409':
          description: >-
            Batch already reached a terminal state, so there is nothing to
            cancel.
          headers:
            X-RateLimit-Limit:
              $ref: '#/components/headers/RateLimitLimit'
            X-RateLimit-Remaining:
              $ref: '#/components/headers/RateLimitRemaining'
            X-RateLimit-Reset:
              $ref: '#/components/headers/RateLimitReset'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - bearerAuth: []
      x-codeSamples:
        - lang: JavaScript
          source: |-
            import ContextDev from 'context.dev';

            const client = new ContextDev({
              apiKey: process.env['CONTEXT_DEV_API_KEY'], // This is the default and can be omitted
            });

            const response = await client.batch.cancel('batch_9f2c8a');

            console.log(response.id);
        - lang: Python
          source: |-
            import os
            from context.dev import ContextDev

            client = ContextDev(
                api_key=os.environ.get("CONTEXT_DEV_API_KEY"),  # This is the default and can be omitted
            )
            response = client.batch.cancel(
                "batch_9f2c8a",
            )
            print(response.id)
        - lang: Go
          source: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/context-dot-dev/context-go-sdk\"\n\t\"github.com/context-dot-dev/context-go-sdk/option\"\n)\n\nfunc main() {\n\tclient := contextdev.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Batch.Cancel(context.TODO(), \"batch_9f2c8a\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n"
        - lang: Ruby
          source: |-
            require "context_dev"

            context_dev = ContextDev::Client.new(api_key: "My API Key")

            response = context_dev.batch.cancel("batch_9f2c8a")

            puts(response)
        - lang: PHP
          source: >-
            <?php


            require_once dirname(__DIR__) . '/vendor/autoload.php';


            use ContextDev\Client;

            use ContextDev\Core\Exceptions\APIException;


            $client = new Client(apiKey: getenv('CONTEXT_DEV_API_KEY') ?: 'My
            API Key');


            try {
              $response = $client->batch->cancel('batch_9f2c8a');

              var_dump($response);
            } catch (APIException $e) {
              echo $e->getMessage();
            }
        - lang: CLI
          source: |-
            context-dev batch cancel \
              --api-key 'My API Key' \
              --batch-id batch_9f2c8a
components:
  headers:
    RateLimitLimit:
      description: >-
        Maximum requests allowed in the current fixed one-minute window.
        Returned when the authenticated API key has a per-minute rate limit.
      schema:
        type: integer
        minimum: 1
    RateLimitRemaining:
      description: >-
        Requests remaining in the current fixed one-minute window. Returned when
        the authenticated API key has a per-minute rate limit.
      schema:
        type: integer
        minimum: 0
    RateLimitReset:
      description: >-
        Unix timestamp in seconds when the current rate-limit window resets.
        Returned when the authenticated API key has a per-minute rate limit.
      schema:
        type: integer
  schemas:
    BatchCancelling:
      type: object
      properties:
        id:
          type: string
          example: batch_9f2c8a
          description: Batch ID.
        status:
          type: string
          enum:
            - cancelling
          description: >-
            Always `cancelling`. Work already in flight finishes; the batch
            reaches `cancelled` shortly after.
        mode:
          type: string
          enum:
            - scrape
            - crawl
          description: How pages were selected.
        format:
          type: string
          enum:
            - markdown
            - html
          description: What each page is returned as.
        tags:
          type: array
          items:
            type: string
          description: Tags stored on the batch at submission.
          example:
            - docs
        crawl:
          $ref: '#/components/schemas/BatchNullableCrawlControls'
        input:
          $ref: '#/components/schemas/BatchIntake'
        progress:
          type: object
          properties:
            succeeded:
              type: integer
              example: 4120
              description: Pages scraped successfully before the request landed.
            failed:
              type: integer
              example: 37
              description: Pages that could not be scraped before the request landed.
            pending:
              type: integer
              example: 20660
              description: >-
                Reserved pages that will now be skipped, and refunded when the
                batch settles.
          required:
            - succeeded
            - failed
            - pending
          description: How far the batch got before cancellation.
        credits:
          type: object
          properties:
            reserved:
              type: integer
              example: 24817
              description: >-
                Credits debited at submission. The unspent remainder is refunded
                once the batch settles — read `credits.refunded` from GET
                /batch/{batch_id} then.
          required:
            - reserved
          description: What this batch cost so far.
        timing:
          type: object
          properties:
            created_at:
              type: string
              description: When the batch was created.
            started_at:
              type:
                - string
                - 'null'
              description: >-
                When processing started. Null if it was cancelled while still
                queued.
          required:
            - created_at
            - started_at
          description: There is no finish time yet — the batch is still winding down.
        page_errors:
          type: array
          items:
            $ref: '#/components/schemas/BatchPageErrorCount'
          description: Page failures so far, grouped by error code and sorted by count.
      required:
        - id
        - status
        - mode
        - format
        - tags
        - crawl
        - input
        - progress
        - credits
        - timing
        - page_errors
      title: Cancelling batch
      description: >-
        Acknowledgement that cancellation was requested. The batch has not
        settled, so it carries no results, no failure, no refund and no finish
        time; poll GET /batch/{batch_id} for those.
    KeyMetadata:
      type: object
      properties:
        credits_consumed:
          type: integer
          description: The number of credits consumed by this request.
        credits_remaining:
          type: integer
          description: >-
            The number of credits remaining for your organization after this
            request.
      required:
        - credits_consumed
        - credits_remaining
      description: >-
        Metadata about the API key used for the request. Included in every
        response whenever a valid API key is provided, even when the response
        status is not 200.
    ErrorResponse:
      type: object
      properties:
        message:
          type: string
          description: Error message
        error_code:
          type: string
          enum:
            - INTERNAL_ERROR
            - VALID
            - NOT_FOUND
            - FORBIDDEN
            - USAGE_EXCEEDED
            - RATE_LIMITED
            - UNAUTHORIZED
            - DISABLED
            - PAID_PLAN_REQUIRED
            - INSUFFICIENT_PERMISSIONS
            - TIMEOUT_EXCEEDS_MAXIMUM
            - WEBSITE_ACCESS_ERROR
            - EXTERNAL_PROVIDER_ERROR
            - INPUT_VALIDATION_ERROR
            - ZDR_NOT_SUPPORTED
            - ZDR_NOT_ENABLED
            - FREE_EMAIL_DETECTED
            - DISPOSABLE_EMAIL_DETECTED
            - REQUEST_TIMEOUT
            - UNSUPPORTED_CONTENT
            - MONITOR_PAUSED
            - MONITOR_NO_WEBHOOK
            - COLLECTION_PAUSED
            - MONITOR_LIMIT_EXCEEDED
            - SEARCH_UNAVAILABLE
            - BATCH_LIMIT_EXCEEDED
            - BATCH_NOT_CANCELLABLE
            - BATCH_NOT_COMPLETED
            - IDEMPOTENCY_KEY_CONFLICT
          description: Error code indicating the type of error
        key_metadata:
          $ref: '#/components/schemas/KeyMetadata'
    BatchNullableCrawlControls:
      anyOf:
        - allOf:
            - $ref: '#/components/schemas/BatchCrawlControls'
        - type: 'null'
      description: How the crawl was configured. Null for scrape batches.
    BatchIntake:
      type: object
      properties:
        reserved:
          type: integer
          example: 24817
          description: >-
            Pages credits were reserved for. Everything else — progress, the
            refund, the completion percentage — is measured against this.
        reserved_is_ceiling:
          type: boolean
          example: false
          description: >-
            Whether `reserved` is an upper bound the batch may finish under.
            True only for a crawl that follows links, whose reachable page count
            is unknowable until it runs. False for a scrape and for a sitemap
            crawl, where `reserved` is an exact page count.
        submitted:
          type:
            - integer
            - 'null'
          example: 25000
          description: >-
            URLs in the list you sent, before validation and de-duplication.
            Null for a crawl, which is given a source rather than a list.
        duplicates:
          type: integer
          example: 183
          description: >-
            URLs dropped before reserving because another entry resolved to the
            same page. Non-zero for sitemap crawls too, whose sitemaps routinely
            list a page more than once.
        invalid:
          type:
            - integer
            - 'null'
          example: 0
          description: >-
            URLs from your list rejected as unusable; the same ones are itemised
            in `invalid_urls` at submission. Null for a crawl — a crawl that
            resolves no usable page is rejected outright with a 400 rather than
            accepted with an empty list.
      required:
        - reserved
        - reserved_is_ceiling
        - submitted
        - duplicates
        - invalid
      x-stainless-model: batch.intake
      description: What submission took in, and what it charged for.
    BatchPageErrorCount:
      type: object
      properties:
        code:
          type: string
          example: WEBSITE_ACCESS_ERROR
          description: Error code for these failures.
        count:
          type: integer
          example: 204
          description: Pages that failed with this code.
      required:
        - code
        - count
      x-stainless-model: batch.page_error_count
      description: Page failures sharing one error code.
    BatchCrawlControls:
      type: object
      properties:
        source:
          anyOf:
            - type: object
              properties:
                type:
                  type: string
                  enum:
                    - start_url
                url:
                  type: string
                  example: https://example.com/docs
                  description: Page the crawl started from.
              required:
                - type
                - url
            - type: object
              properties:
                type:
                  type: string
                  enum:
                    - sitemap
                domain:
                  type: string
                  example: example.com
                  description: Domain whose sitemap supplied the pages.
              required:
                - type
                - domain
          description: Where the crawl started.
        max_pages:
          type: integer
          example: 500
          description: >-
            The `maxUrls` submitted with the crawl. A sitemap crawl scrapes only
            the URLs its sitemap actually lists, up to this many, so
            `input.reserved` is often lower.
        max_depth:
          type:
            - integer
            - 'null'
          example: 0
          description: >-
            Link depth limit. Always 0 for a sitemap crawl, which never follows
            links off its URLs; null when a `start_url` crawl set no limit.
        follow_subdomains:
          type: boolean
          description: >-
            Whether links to subdomains were followed. Always false for a
            sitemap crawl.
        url_pattern:
          type:
            - string
            - 'null'
          example: ^https://example\.com/docs/
          description: >-
            RE2 pattern URLs had to match to be crawled. Null when the crawl set
            none.
      required:
        - source
        - max_pages
        - max_depth
        - follow_subdomains
        - url_pattern
      x-stainless-model: batch.crawl_controls
      title: Crawl controls
      description: >-
        The crawl controls as submitted, so the limits requested can be compared
        against what the crawl reached.
  responses:
    Unauthorized:
      description: Unauthorized
      headers:
        X-RateLimit-Limit:
          $ref: '#/components/headers/RateLimitLimit'
        X-RateLimit-Remaining:
          $ref: '#/components/headers/RateLimitRemaining'
        X-RateLimit-Reset:
          $ref: '#/components/headers/RateLimitReset'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
    NotFound:
      description: Not found
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
      headers:
        X-RateLimit-Limit:
          $ref: '#/components/headers/RateLimitLimit'
        X-RateLimit-Remaining:
          $ref: '#/components/headers/RateLimitRemaining'
        X-RateLimit-Reset:
          $ref: '#/components/headers/RateLimitReset'
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: >-
        Bearer authentication header of the form `Bearer <API_KEY>`, where
        `<API_KEY>` is your api key.

````