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

# Create Webhook

> Subscribe to extraction events with a webhook URL

Create a new webhook subscription. The response includes a `secret` for verifying webhook signatures. This secret is only returned on creation and cannot be retrieved later.

## Request Body

| Field    | Type      | Required | Default    | Description                                                                       |
| -------- | --------- | -------- | ---------- | --------------------------------------------------------------------------------- |
| `url`    | string    | Yes      | —          | HTTPS URL to receive webhook events. HTTP URLs are rejected.                      |
| `events` | string\[] | No       | All events | Array of event types to subscribe to: `extraction.completed`, `extraction.failed` |

<Warning>
  The `secret` field is only included in the creation response. Store it immediately. If lost, delete the webhook and create a new one.
</Warning>

<RequestExample>
  ```bash curl theme={null}
  curl -X POST 'https://api.anyformat.ai/v2/webhooks/' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer YOUR_API_KEY' \
    -d '{
      "url": "https://your-server.com/webhooks/anyformat",
      "events": ["extraction.completed", "extraction.failed"]
    }'
  ```

  ```python Python (requests) theme={null}
  import requests

  url = "https://api.anyformat.ai/v2/webhooks/"
  headers = {
      "Content-Type": "application/json",
      "Authorization": "Bearer YOUR_API_KEY"
  }

  data = {
      "url": "https://your-server.com/webhooks/anyformat",
      "events": ["extraction.completed", "extraction.failed"]
  }

  response = requests.post(url, headers=headers, json=data)
  webhook = response.json()
  # Store the secret securely — it is only returned on creation
  print(f"Webhook created: {webhook['id']}, secret: {webhook['secret']}")
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.anyformat.ai/v2/webhooks/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify({
      url: 'https://your-server.com/webhooks/anyformat',
      events: ['extraction.completed', 'extraction.failed']
    })
  });

  const data = await response.json();
  // Store the secret securely — it is only returned on creation
  console.log(data);
  ```

  ```typescript TypeScript theme={null}
  interface WebhookCreateRequest {
    url: string;
    events?: string[];
  }

  interface WebhookResponse {
    id: string;
    url: string;
    events: string[];
    is_active: boolean;
    secret: string;
    created_at: string;
  }

  const body: WebhookCreateRequest = {
    url: 'https://your-server.com/webhooks/anyformat',
    events: ['extraction.completed', 'extraction.failed']
  };

  const response = await fetch('https://api.anyformat.ai/v2/webhooks/', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY'
    },
    body: JSON.stringify(body)
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  const data: WebhookResponse = await response.json();
  // Store data.secret securely — it is only returned on creation
  console.log(data.id);
  ```
</RequestExample>

<ResponseExample>
  ```json Response (201 Created) theme={null}
  {
    "id": "wh_1234567890",
    "url": "https://your-server.com/webhooks/anyformat",
    "events": ["extraction.completed", "extraction.failed"],
    "is_active": true,
    "secret": "whsec_abc123def456...",
    "created_at": "2024-03-24T12:00:00.000Z"
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v2/webhooks/
openapi: 3.1.0
info:
  title: AnyFormat API
  description: >
    Document extraction and workflow automation API.


    AnyFormat lets you define extraction workflows that pull structured data
    from any document — PDFs, images, scanned files, or plain text. Upload a
    file, run it through a workflow, and get back structured fields with
    confidence scores and source evidence.


    ## Quick start


    1. **Create a workflow** in the [AnyFormat
    dashboard](https://app.anyformat.ai) and define the fields you want to
    extract.

    2. **Run the workflow** via `POST /v2/workflows/{workflow_id}/run/` with a
    file attached.

    3. **Fetch results** via `GET
    /v2/workflows/{workflow_id}/files/{collection_id}/results/` once processing
    completes.


    ## Authentication


    All endpoints (except `/health/`) require a Bearer token in the
    `Authorization` header:


    ```

    Authorization: Bearer <your-api-key>

    ```


    Get your API key from
    [app.anyformat.ai/settings](https://app.anyformat.ai/settings).


    ## Versioning


    All endpoints use the `/v2/` path prefix. All responses include
    `X-API-Version`.
  version: 2.0.0
servers:
  - url: https://api.anyformat.ai
    description: API server
security: []
tags:
  - name: workflows
    description: >-
      Workflows define extraction templates — what fields to extract from
      documents. Create workflows, upload files, run extractions, and fetch
      results.
  - name: files
    description: >-
      File collections group uploaded documents and track their extraction
      progress. Upload files, check status, and retrieve extraction results.
  - name: webhooks
    description: >-
      Webhook subscriptions for asynchronous event notifications. Get notified
      when extractions complete or fail.
  - name: health
    description: Health check endpoints to verify API availability.
paths:
  /v2/webhooks/:
    post:
      tags:
        - webhooks
      summary: Create webhook
      description: >-
        Create a new webhook subscription for your organization.


        The webhook URL must use HTTPS. AnyFormat will send POST requests to
        this URL

        when the subscribed events occur. The response includes a `secret` that
        you

        should use to verify webhook signatures.


        Supported events:

        - `extraction.completed` — fired when a file extraction finishes
        successfully.

        - `extraction.failed` — fired when a file extraction fails.
      operationId: create_webhook_v2_webhooks__post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/WebhookCreateRequest'
        required: true
      responses:
        '201':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/WebhookResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    WebhookCreateRequest:
      properties:
        url:
          type: string
          maxLength: 2083
          minLength: 1
          format: uri
          title: Url
          description: >-
            The HTTPS URL to receive webhook events. Must be publicly
            accessible.
          examples:
            - https://example.com/webhooks/anyformat
        events:
          items:
            type: string
          type: array
          title: Events
          description: >-
            List of event types to subscribe to. Available events:
            `extraction.completed`, `extraction.failed`.
          examples:
            - - extraction.completed
              - extraction.failed
      type: object
      required:
        - url
      title: WebhookCreateRequest
      description: Request to create a new webhook subscription.
    WebhookResponse:
      properties:
        id:
          type: string
          title: Id
          description: Unique identifier of the webhook.
        url:
          type: string
          maxLength: 2083
          minLength: 1
          format: uri
          title: Url
          description: The URL receiving webhook events.
          examples:
            - https://example.com/webhooks/anyformat
        events:
          items:
            type: string
          type: array
          title: Events
          description: Event types this webhook is subscribed to.
          examples:
            - - extraction.completed
              - extraction.failed
        is_active:
          type: boolean
          title: Is Active
          description: Whether the webhook is currently active and receiving events.
          examples:
            - true
        secret:
          type: string
          title: Secret
          description: >-
            Webhook signing secret. Use this to verify that incoming webhook
            requests are authentic. **Store securely — this value is only shown
            once at creation time.**
        created_at:
          type: string
          format: date-time
          title: Created At
          description: Timestamp when the webhook was created (ISO 8601).
      type: object
      required:
        - id
        - url
        - events
        - is_active
        - secret
        - created_at
      title: WebhookResponse
      description: >-
        Webhook subscription details including the signing secret. The secret is
        only returned at creation time.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
        input:
          title: Input
        ctx:
          type: object
          title: Context
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    ApiKeyAuth:
      type: http
      description: >-
        API key issued from app.anyformat.ai/settings. Send as `Authorization:
        Bearer <key>`.
      scheme: bearer

````