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

# Create Webhook

> Creates a new webhook for event notifications. A `scoped` webhook
requires at least one domain and the key must have write permission for
every supplied domain. A `global` webhook requires
`webhooks:write:all`; supplied domains are accepted but ignored, and
the response contains `domains: []`.




## OpenAPI

````yaml openapi.yaml POST /v2/accounts/{account_id}/webhooks
openapi: 3.1.0
info:
  title: AhaSend API v2
  description: >
    The AhaSend API v2 allows you to send transactional emails, manage domains,
    webhooks, routes, API keys, and view statistics.


    ## Authentication

    All API requests must be authenticated using a Bearer token in the
    Authorization header:

    ```

    Authorization: Bearer aha-sk-64-CHARACTER-RANDOM-STRING

    ```


    ## Scopes

    API keys have specific scopes that control access to different resources and
    actions:


    ### Message Scopes

    - `messages:send:all` - Send messages from any domain in the account

    - `messages:send:{domain}` - Send messages from a specific domain

    - `messages:cancel:all` - Cancel messages from any domain

    - `messages:cancel:{domain}` - Cancel messages from a specific domain

    - `messages:read:all` - Read messages from any domain

    - `messages:read:{domain}` - Read messages from a specific domain


    ### Domain Scopes

    - `domains:read` - Read all domains

    - `domains:write` - Create and update domains

    - `domains:delete:all` - Delete any domain

    - `domains:delete:{domain}` - Delete a specific domain


    ### Account Scopes

    - `accounts:read` - Read account information

    - `accounts:write` - Update account settings

    - `accounts:billing` - Access billing information

    - `accounts:members:read` - Read account members

    - `accounts:members:add` - Add account members

    - `accounts:members:update` - Update account members

    - `accounts:members:remove` - Remove account members


    ### Webhook Scopes

    - `webhooks:read:all` - Read all webhooks

    - `webhooks:read:{domain}` - Read webhooks for a specific domain

    - `webhooks:write:all` - Create and update webhooks

    - `webhooks:write:{domain}` - Create and update webhooks for a specific
    domain

    - `webhooks:delete:all` - Delete any webhook

    - `webhooks:delete:{domain}` - Delete webhooks for a specific domain


    ### Route Scopes

    - `routes:read:all` - Read all routes

    - `routes:read:{domain}` - Read routes for a specific domain

    - `routes:write:all` - Create and update routes

    - `routes:write:{domain}` - Create and update routes for a specific domain

    - `routes:delete:all` - Delete any route

    - `routes:delete:{domain}` - Delete routes for a specific domain


    ### Suppression Scopes

    - `suppressions:read` - Read suppressions

    - `suppressions:write` - Create suppressions

    - `suppressions:delete` - Delete suppressions

    - `suppressions:wipe` - Delete all suppressions (dangerous)


    ### SMTP Credentials Scopes

    - `smtp-credentials:read:all` - Read all SMTP credentials

    - `smtp-credentials:read:{domain}` - Read SMTP credentials for a specific
    domain

    - `smtp-credentials:write:all` - Create SMTP credentials

    - `smtp-credentials:write:{domain}` - Create SMTP credentials for a specific
    domain

    - `smtp-credentials:delete:all` - Delete any SMTP credentials

    - `smtp-credentials:delete:{domain}` - Delete SMTP credentials for a
    specific domain


    ### Statistics Scopes

    - `statistics-transactional:read:all` - Read all transactional statistics

    - `statistics-transactional:read:{domain}` - Read transactional statistics
    for a specific domain


    ### API Key Scopes

    - `api-keys:read` - Read API keys

    - `api-keys:write` - Create and update API keys

    - `api-keys:delete` - Delete API keys


    ### Sub-Account Scopes

    - `sub-accounts:read` - List and read sub accounts under the parent

    - `sub-accounts:write` - Create and update sub accounts

    - `sub-accounts:delete` - Soft-delete sub accounts

    - `sub-accounts:suspend` - Suspend and unsuspend sub accounts

    - `sub-accounts:usage` - Read per-sub-account usage and allocated cost

    - `sub-account-api-keys:read` - List and read API keys owned by sub accounts

    - `sub-account-api-keys:write` - Create and update API keys owned by sub
    accounts

    - `sub-account-api-keys:delete` - Delete API keys owned by sub accounts


    ## Rate Limiting

    - General API endpoints: 100 requests per second, 200 burst

    - Statistics endpoints: 1 request per second, 1 burst


    ## Pagination

    List endpoints use cursor-based pagination with the following parameters:

    - `limit`: Maximum number of items to return (default: 100, max: 100)

    - `after`: Pass `pagination.next_cursor` to fetch the next page

    - `before`: Pass `pagination.previous_cursor` to fetch the previous page


    `after` and `before` are mutually exclusive. A legacy `cursor` query may be

    accepted by parts of the server for backwards compatibility, but it is not

    part of the v2 public contract.


    ## Time Formats

    All timestamps must be in RFC3339 format, e.g., `2023-12-25T10:30:00Z`


    ## Idempotency

    The operations that explicitly declare the optional `Idempotency-Key`

    header support idempotency. Other POST operations do not gain idempotency

    implicitly. When the header is provided:

    - A fresh execution does not return `Idempotent-Replayed`.

    - A completed stored response is replayed with its original status and body
      and `Idempotent-Replayed: true`.
    - An unexpired in-progress execution returns HTTP 409 with
      `Idempotent-Replayed: false` and a positive integer `Retry-After` header.
    - Reusing a key with a different HTTP method, resolved request path, or
      request body returns HTTP 422. That response has neither
      `Idempotent-Replayed` nor `Retry-After`.
    - For ordinary idempotent operations, deterministic 2xx and 4xx outcomes
      produced after the idempotency middleware are stored and replayed.
      Authentication and IP-allow-list failures happen before idempotency and
      are therefore not stored.
    - The two secret-bearing API-key create operations use manual encrypted
      completion. They store and replay a successful 201, including the same
      one-time `secret_key`; a controller-produced 4xx is not stored and leaves
      the key in progress until its execution lease expires.
    - Server errors (5xx), handler failures, and panics are not stored. The key
      is released so retrying the same request with the same key re-executes it.
      The v2 API does not use an HTTP 412 failed-key tombstone.
    - Idempotency keys for non-secret responses expire after 24 hours.

    - Encrypted API-key creation replay responses expire after 5 minutes.


    ## IP Allow Lists

    Each API key can carry an `ip_allow_list`: a set of source IPs that restrict
    where the key may authenticate from.

    - Entries are CIDR blocks (e.g. `203.0.113.0/24`) or bare IPv4/IPv6
    addresses (stored as a `/32` or `/128`). They are canonicalized and
    de-duplicated; the allow-all prefixes `0.0.0.0/0` and `::/0` are rejected,
    and at most 100 entries are allowed after de-duplication (a longer list is
    rejected with HTTP 400).

    - An empty list (the default) places no restriction.

    - When the list is non-empty, any authenticated request whose client IP is
    not covered by an entry is rejected with HTTP 403 on every v2 endpoint,
    regardless of the key's scopes.

    - Manage the list with the `ip_allow_list` field on the API-key create and
    update endpoints (including the sub-account API-key endpoints).

    - When a key updates its own `ip_allow_list` to a value that excludes the
    caller's current IP, the update is rejected with HTTP 409 to prevent
    self-lockout. Updating a sub-account key from a parent key has no such
    guard.
  version: 2.0.0
  contact:
    email: support@ahasend.com
  license:
    name: MIT
    identifier: MIT
servers:
  - url: https://api.ahasend.com
    description: Production server
security:
  - BearerAuth: []
tags:
  - name: Utility
    description: Utility endpoints for health checks and diagnostics
  - name: API Keys
    description: Manage API keys for authentication and access control
  - name: Domains
    description: Manage sending domains
  - name: Messages
    description: Send and manage transactional messages
  - name: Accounts
    description: Manage account settings and members
  - name: Suppressions
    description: Manage email suppressions
  - name: Routes
    description: Manage inbound email routing
  - name: Webhooks
    description: Manage webhook notifications
  - name: SMTP Credentials
    description: Manage SMTP authentication credentials
  - name: Statistics
    description: Access transactional email statistics
  - name: Message Events
    description: Webhooks for outbound message delivery events
  - name: Suppression Events
    description: Webhooks for suppression list changes
  - name: Domain Events
    description: Webhooks for domain configuration issues
  - name: Route Events
    description: Webhooks for inbound email routing
paths:
  /v2/accounts/{account_id}/webhooks:
    post:
      tags:
        - Webhooks
      summary: Create Webhook
      description: |
        Creates a new webhook for event notifications. A `scoped` webhook
        requires at least one domain and the key must have write permission for
        every supplied domain. A `global` webhook requires
        `webhooks:write:all`; supplied domains are accepted but ignored, and
        the response contains `domains: []`.
      operationId: createWebhook
      parameters:
        - name: account_id
          in: path
          required: true
          description: Account ID
          schema:
            type: string
            format: uuid
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateWebhookRequest'
      responses:
        '201':
          description: Webhook created successfully
          headers:
            Idempotent-Replayed:
              $ref: '#/components/headers/IdempotentReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreatedWebhook'
        '400':
          description: Bad request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Forbidden
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          $ref: '#/components/responses/IdempotencyConflict'
        '422':
          $ref: '#/components/responses/IdempotencyPayloadMismatch'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - BearerAuth:
            - webhooks:write:all
        - BearerAuth:
            - webhooks:write:{domain}
      x-code-samples:
        - lang: go
          label: AhaSend Go SDK
          source: |
            package main

            import (
              "context"
              "fmt"
              "log"

              "github.com/AhaSend/ahasend-go/api"
              "github.com/AhaSend/ahasend-go/models/requests"
              "github.com/google/uuid"
            )

            func main() {
              // Create API client with authentication
              client := api.NewAPIClient(
                api.WithAPIKey("aha-sk-your-64-character-key"),
              )

              accountID := uuid.New()

              // Create context for the API call
              ctx := context.Background()

              // Call the ping endpoint
              response, httpResp, err := client.WebhooksAPI.CreateWebhook(
                ctx,
                accountID,
                requests.CreateWebhookRequest{
                  Name:   "Failures",
                  URL:    "https://mystartup.com/webhook",
                  Scope:  "global",
                  Enabled: true,
                  OnBounced: true,
                  OnTransientError: true,
                  OnFailed: true,
                },
                nil,
              )
              if err != nil {
                log.Fatalf("Error creating webhook: %v", err)
              }

              // Check response
              if httpResp.StatusCode == 201 {
                fmt.Printf("✅ Status: %d\n", httpResp.StatusCode)
                if response != nil {
                  fmt.Printf("Created webhook: %#v\n", response)
                }
              } else {
                fmt.Printf("❌ Unexpected status code: %d\n", httpResp.StatusCode)
              }
            }
components:
  parameters:
    IdempotencyKey:
      name: Idempotency-Key
      in: header
      required: false
      description: >
        Optional idempotency key for safe request retries. Must be a unique
        string for each logical request.

        An identical request with a completed stored outcome returns the
        original status and body. An in-progress

        execution returns 409, a changed method/path/body returns 422, and a
        released 5xx execution may run again.

        Keys for non-secret responses expire after 24 hours. API-key create
        responses include a one-time `secret_key`,

        so successful encrypted replay responses for those operations expire
        after 5 minutes.
      schema:
        type: string
        maxLength: 255
      example: user-12345-create-domain-20240101
  schemas:
    CreateWebhookRequest:
      type: object
      required:
        - name
        - url
        - scope
      properties:
        name:
          type: string
          maxLength: 255
          description: Webhook name
        url:
          type: string
          format: uri
          description: Webhook URL
        enabled:
          type: boolean
          description: Whether the webhook is enabled
          default: true
        on_reception:
          type: boolean
          description: Trigger on message reception
          default: false
        on_delivered:
          type: boolean
          description: Trigger on message delivery
          default: false
        on_transient_error:
          type: boolean
          description: Trigger on transient errors
          default: false
        on_failed:
          type: boolean
          description: Trigger on permanent failures
          default: false
        on_bounced:
          type: boolean
          description: Trigger on bounces
          default: false
        on_suppressed:
          type: boolean
          description: Trigger on suppressions
          default: false
        on_opened:
          type: boolean
          description: Trigger on opens
          default: false
        on_clicked:
          type: boolean
          description: Trigger on clicks
          default: false
        on_suppression_created:
          type: boolean
          description: Trigger on suppression creation
          default: false
        on_dns_error:
          type: boolean
          description: Trigger on DNS errors
          default: false
        scope:
          type: string
          enum:
            - global
            - scoped
          description: Webhook scope
        domains:
          type:
            - array
            - 'null'
          items:
            type: string
          description: |
            For `scoped`, a non-empty array is required. For `global`, this may
            be omitted, null, empty, or non-empty; supplied values are accepted
            but ignored.
      allOf:
        - if:
            properties:
              scope:
                const: scoped
            required:
              - scope
          then:
            required:
              - domains
            properties:
              domains:
                type: array
                minItems: 1
                items:
                  type: string
      example:
        name: Delivery Webhook
        url: https://example.com/webhook
        scope: global
        enabled: true
        on_delivered: true
    CreatedWebhook:
      allOf:
        - $ref: '#/components/schemas/Webhook'
        - type: object
          properties:
            secret:
              type: string
              description: >-
                Webhook signing secret. Returned only when the webhook is
                created.
          required:
            - secret
    ErrorResponse:
      type: object
      description: |
        Human-readable API error. The server currently sends no stable machine
        error code. In particular, clients must not parse `message` to
        distinguish IP-allow-list, scope, ownership, plan, self-lockout,
        suppression-duplicate, or other errors that share an HTTP status.
      additionalProperties: false
      required:
        - message
      properties:
        message:
          type: string
          description: Error description
      example:
        message: Error message
    Webhook:
      type: object
      properties:
        object:
          type: string
          enum:
            - webhook
          description: Object type identifier
        id:
          type: string
          format: uuid
          description: Unique identifier for the webhook
        created_at:
          type: string
          format: date-time
          description: When the webhook was created
        updated_at:
          type: string
          format: date-time
          description: When the webhook was last updated
        name:
          type: string
          description: Webhook name
        url:
          type: string
          format: uri
          description: Webhook URL
        enabled:
          type: boolean
          description: Whether the webhook is enabled
        on_reception:
          type: boolean
          description: Trigger on message reception
        on_delivered:
          type: boolean
          description: Trigger on message delivery
        on_transient_error:
          type: boolean
          description: Trigger on transient errors
        on_failed:
          type: boolean
          description: Trigger on permanent failures
        on_bounced:
          type: boolean
          description: Trigger on bounces
        on_suppressed:
          type: boolean
          description: Trigger on suppressions
        on_opened:
          type: boolean
          description: Trigger on opens
        on_clicked:
          type: boolean
          description: Trigger on clicks
        on_suppression_created:
          type: boolean
          description: Trigger on suppression creation
        on_dns_error:
          type: boolean
          description: Trigger on DNS errors
        scope:
          type: string
          enum:
            - global
            - scoped
          description: Webhook scope
        domains:
          type: array
          items:
            type: string
          description: >-
            Domains this webhook applies to. Always present; global webhooks
            return an empty array.
        success_count:
          type: integer
          description: Number of successful calls
        error_count:
          type: integer
          description: Number of unsuccessful calls
        errors_since_last_success:
          type: integer
          description: Number of consecutive failed calls
        last_request_at:
          type:
            - string
            - 'null'
          format: date-time
          description: When the webhook was last called
      required:
        - object
        - id
        - created_at
        - updated_at
        - name
        - url
        - enabled
        - on_reception
        - on_delivered
        - on_transient_error
        - on_failed
        - on_bounced
        - on_suppressed
        - on_opened
        - on_clicked
        - on_suppression_created
        - on_dns_error
        - scope
        - domains
        - success_count
        - error_count
        - errors_since_last_success
        - last_request_at
  headers:
    IdempotentReplayed:
      description: >
        Indicates that this response is a stored replay of a previous identical
        request.

        When this header is absent, the response is not a stored replay.
        Ordinary fresh

        responses do not send `false`; that value is reserved for an in-progress
        409.
      schema:
        type: string
        enum:
          - 'true'
    IdempotencyInProgress:
      description: |
        Identifies an idempotency-key execution that is still in progress. This
        header is emitted only on the specialized HTTP 409 response.
      schema:
        type: string
        enum:
          - 'false'
    IdempotencyRetryAfter:
      description: |
        Positive whole number of seconds after which the in-progress execution
        lease may be retried with the same key and unchanged request.
      schema:
        type: integer
        minimum: 1
  responses:
    IdempotencyConflict:
      description: |
        Request in progress. This response always includes
        `Idempotent-Replayed: false` and a positive integer `Retry-After`.
        Clients must use that header tuple, not the human-readable message, to
        distinguish this retryable idempotency state from other HTTP 409s.
      headers:
        Idempotent-Replayed:
          $ref: '#/components/headers/IdempotencyInProgress'
        Retry-After:
          $ref: '#/components/headers/IdempotencyRetryAfter'
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            message: A request with this idempotency key is already in progress
    IdempotencyPayloadMismatch:
      description: |
        Idempotency key was already used with a different HTTP method, resolved
        request path, or request body. This response includes neither
        `Idempotent-Replayed` nor `Retry-After`.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorResponse'
          example:
            message: idempotency key was already used with a different request payload
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: aha-sk-64-CHARACTER-RANDOM-STRING
      description: |
        API key for authentication. Non-empty Security Requirement values are
        AhaSend API-key roles. Roles listed within one requirement object are
        jointly required; separate requirement objects are alternatives.

````