> ## 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 Sub-Account API Key

> Creates an API key owned by the sub account. Parent credentials must belong to the parent account and include `sub-account-api-keys:write`; sub-account credentials cannot manage nested API keys. The returned `secret_key` authenticates as the child account and should be stored immediately.

Bootstrap example:
1. Create the sub account with `POST /v2/accounts/{account_id}/sub-accounts` and a unique `Idempotency-Key`.
2. Create the bootstrap child API key with this endpoint and a different unique `Idempotency-Key`.
3. Store the one-time `secret_key` from the `201` response. Exact idempotent replays within 5 minutes return the same `secret_key`.
4. Use that child secret with the child `sub_account_id` as the `account_id` on ordinary v2 routes.


<Info>
  **Platform Partner feature:** Sub Accounts is part of our Platform Partner capabilities and is currently in early access. [Contact us](https://ahasend.com/contact) to enable it on your account.
</Info>


## OpenAPI

````yaml openapi.yaml POST /v2/accounts/{account_id}/sub-accounts/{sub_account_id}/api-keys
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)

    - `cursor`: Pagination cursor for the next page


    ## Time Formats

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


    ## Idempotency

    POST requests support idempotency through the optional `Idempotency-Key`
    header. When provided:

    - The same request can be safely retried multiple times

    - Duplicate requests return the same response with `Idempotent-Replayed:
    true`

    - In-progress requests return HTTP 409 with `Idempotent-Replayed: false` and
    a `Retry-After` header

    - Completed outcomes (2xx and 4xx) are stored and replayed; server errors
    (5xx) are not stored, so retrying with the same key re-executes the request

    - Reusing a key with a different request payload, or against a different
    endpoint or resource, returns HTTP 422

    - Idempotency keys for non-secret responses expire after 24 hours

    - API-key create endpoints return a one-time `secret_key`; their encrypted
    idempotency replay responses expire after 5 minutes and replay the same
    `secret_key` during that window


    ## 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}/sub-accounts/{sub_account_id}/api-keys:
    post:
      tags:
        - Sub Accounts
      summary: Create Sub-Account API Key
      description: >
        Creates an API key owned by the sub account. Parent credentials must
        belong to the parent account and include `sub-account-api-keys:write`;
        sub-account credentials cannot manage nested API keys. The returned
        `secret_key` authenticates as the child account and should be stored
        immediately.


        Bootstrap example:

        1. Create the sub account with `POST
        /v2/accounts/{account_id}/sub-accounts` and a unique `Idempotency-Key`.

        2. Create the bootstrap child API key with this endpoint and a different
        unique `Idempotency-Key`.

        3. Store the one-time `secret_key` from the `201` response. Exact
        idempotent replays within 5 minutes return the same `secret_key`.

        4. Use that child secret with the child `sub_account_id` as the
        `account_id` on ordinary v2 routes.
      operationId: createSubAccountAPIKey
      parameters:
        - name: account_id
          in: path
          required: true
          description: Parent account ID
          schema:
            type: string
            format: uuid
        - name: sub_account_id
          in: path
          required: true
          description: Sub account ID
          schema:
            type: string
            format: uuid
        - $ref: '#/components/parameters/IdempotencyKey'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CreateAPIKeyRequest'
            example:
              label: Bootstrap key
              scopes:
                - messages:send:all
                - domains:read
      responses:
        '201':
          description: Sub-account API key created successfully
          headers:
            Idempotent-Replayed:
              $ref: '#/components/headers/IdempotentReplayed'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/APIKey'
              example:
                object: api_key
                id: 13b3aa8e-78d3-48a1-92d2-4b8b1228c2dd
                created_at: '2024-01-01T00:05:00Z'
                updated_at: '2024-01-01T00:05:00Z'
                last_used_at: null
                account_id: 2f3c5d2a-9ef8-4c91-a5f4-79990c8c1d3a
                label: Bootstrap key
                public_key: aha-pk-child-public-key
                secret_key: aha-sk-child-secret-key
                scopes:
                  - id: c574470d-76ef-4f74-9b24-70a583a17e03
                    created_at: '2024-01-01T00:05:00Z'
                    updated_at: '2024-01-01T00:05:00Z'
                    api_key_id: 13b3aa8e-78d3-48a1-92d2-4b8b1228c2dd
                    scope: messages:send:all
                    domain_id: null
                ip_allow_list: []
        '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'
        '404':
          description: Sub account not found under the parent account
          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:
            - sub-account-api-keys:write
      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()
              subAccountID := uuid.New()

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

              // Bootstrap an API key for the sub-account (idempotency key makes retries safe)
              response, httpResp, err := client.SubAccountsAPI.CreateSubAccountAPIKey(
                ctx,
                accountID,
                subAccountID,
                requests.CreateAPIKeyRequest{
                  Label:  "Bootstrap key",
                  Scopes: []string{"messages:send:all", "domains:read"},
                  // Optional: restrict the sub-account key to specific source IPs.
                  IPAllowList: []string{"203.0.113.0/24"},
                },
                api.WithIdempotencyKey("child-bootstrap-key-20240101-acme"),
              )
              if err != nil {
                log.Fatalf("Error creating sub-account API key: %v", err)
              }

              if httpResp.StatusCode == 201 {
                fmt.Printf("✅ Sub-account API key created. Status: %d\n", httpResp.StatusCode)
                fmt.Printf("ID: %s\n", response.ID)
                fmt.Printf("Label: %s\n", response.Label)
                fmt.Printf("Public key: %s\n", response.PublicKey)
                // SecretKey is the one-time secret, returned ONLY on create.
                if response.SecretKey != nil {
                  // Store this value immediately — it cannot be retrieved again later.
                  fmt.Printf("Secret key (store this now, shown only once): %s\n", *response.SecretKey)
                }
              } else {
                fmt.Printf("❌ Unexpected status code: %d\n", httpResp.StatusCode)
              }
            }
        - lang: shell
          label: Bootstrap child API key
          source: >
            PARENT_ACCOUNT_ID="9d0cf9d0-4f5e-4674-bcf1-8ec39968b6e1"

            PARENT_SECRET="aha-sk-parent-64-character-key"


            curl -sS -X POST
            "https://api.ahasend.com/v2/accounts/${PARENT_ACCOUNT_ID}/sub-accounts"
            \
              -H "Authorization: Bearer ${PARENT_SECRET}" \
              -H "Content-Type: application/json" \
              -H "Idempotency-Key: subacct-20240101-acme" \
              -d '{"name":"Acme Subsidiary","website":"acme.example.com"}' \
              > sub-account.json

            CHILD_ACCOUNT_ID="$(jq -r '.id' sub-account.json)"


            curl -sS -X POST
            "https://api.ahasend.com/v2/accounts/${PARENT_ACCOUNT_ID}/sub-accounts/${CHILD_ACCOUNT_ID}/api-keys"
            \
              -H "Authorization: Bearer ${PARENT_SECRET}" \
              -H "Content-Type: application/json" \
              -H "Idempotency-Key: child-bootstrap-key-20240101-acme" \
              -d '{"label":"Bootstrap key","scopes":["messages:send:all","domains:read"]}' \
              > child-api-key.json

            CHILD_SECRET="$(jq -r '.secret_key' child-api-key.json)"

            printf 'Store this one-time child secret securely: %s\n'
            "${CHILD_SECRET}"


            curl -sS
            "https://api.ahasend.com/v2/accounts/${CHILD_ACCOUNT_ID}/domains" \
              -H "Authorization: Bearer ${CHILD_SECRET}"
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.

        Requests with the same key will return the same response. Keys for
        non-secret responses expire after 24 hours.

        API-key create responses include a one-time `secret_key`, so their
        encrypted replay responses expire after 5 minutes.
      schema:
        type: string
        maxLength: 255
      example: user-12345-create-domain-20240101
  schemas:
    CreateAPIKeyRequest:
      type: object
      required:
        - label
        - scopes
      properties:
        label:
          type: string
          minLength: 1
          maxLength: 255
          description: Human-readable label for the API key; must not be empty
        scopes:
          type: array
          items:
            type: string
          minItems: 1
          description: Array of scope strings to grant to this API key
        ip_allow_list:
          type: array
          items:
            type: string
          description: >-
            Optional list of source IPs allowed to authenticate with this key.
            Each entry is a CIDR block (e.g. `203.0.113.0/24`) or a bare
            IPv4/IPv6 address (stored as a `/32` or `/128`). Entries are
            canonicalized (host bits are masked) 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. Omit the field or pass
            an empty array to leave the key usable from any IP.
      example:
        label: Production API Key
        scopes:
          - messages:send:all
          - domains:read
        ip_allow_list:
          - 203.0.113.0/24
          - 198.51.100.7
    APIKey:
      type: object
      properties:
        object:
          type: string
          enum:
            - api_key
          description: Object type identifier
        id:
          type: string
          format: uuid
          description: Unique identifier for the API key
        created_at:
          type: string
          format: date-time
          description: When the API key was created
        updated_at:
          type: string
          format: date-time
          description: When the API key was last updated
        last_used_at:
          type: string
          format: date-time
          nullable: true
          description: When the API key was last used (updates every 5-10 minutes)
        account_id:
          type: string
          format: uuid
          description: Account ID this API key belongs to
        label:
          type: string
          description: Human-readable label for the API key
        public_key:
          type: string
          description: Public portion of the API key
        secret_key:
          type: string
          description: >-
            Secret key. Only returned when an API key is created, including
            exact idempotent replays of create requests within the 5-minute
            secret-bearing replay window. Store it immediately; list, get,
            update, and delete responses omit it.
        scopes:
          type: array
          items:
            $ref: '#/components/schemas/APIKeyScope'
          description: Scopes granted to this API key
        ip_allow_list:
          type: array
          items:
            type: string
          description: >-
            Source IPs allowed to authenticate with this API key, as canonical
            CIDR blocks (a bare address is stored as a `/32` for IPv4 or `/128`
            for IPv6). Always present; an empty array means the key may be used
            from any source IP. When non-empty, an 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.
      required:
        - object
        - id
        - created_at
        - updated_at
        - account_id
        - label
        - public_key
        - scopes
        - ip_allow_list
    ErrorResponse:
      type: object
      required:
        - message
      properties:
        message:
          type: string
          description: Error description
      example:
        message: Error message
    APIKeyScope:
      type: object
      properties:
        id:
          type: string
          format: uuid
          description: Unique identifier for the scope
        created_at:
          type: string
          format: date-time
          description: When the scope was created
        updated_at:
          type: string
          format: date-time
          description: When the scope was last updated
        api_key_id:
          type: string
          format: uuid
          description: ID of the API key this scope belongs to
        scope:
          type: string
          description: The scope string
        domain_id:
          type: string
          format: uuid
          nullable: true
          description: Domain ID for domain-specific scopes
      required:
        - id
        - created_at
        - updated_at
        - api_key_id
        - scope
  headers:
    IdempotentReplayed:
      description: >
        Indicates whether this response is replayed from a previous identical
        request.

        - `true`: Response was replayed from cache (duplicate request)

        - `false`: Response from original processing or error state
      schema:
        type: string
        enum:
          - true
          - false
  responses:
    IdempotencyConflict:
      description: >-
        Request in progress - a request with this idempotency key is already
        being processed
      headers:
        Idempotent-Replayed:
          $ref: '#/components/headers/IdempotentReplayed'
        Retry-After:
          description: Number of seconds after which it is safe to retry the request
          schema:
            type: integer
      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 request payload
      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

````