---
title: "Activate an installation"
description: "Bind a customer license to one persisted installation."
slug: "/docs/v1/api/activate"
section: "API reference"
order: 28
audience: "all"
level: "intermediate"
last_updated: "2026-10-17"
version: "v1"
related: ["/docs/v1/api/conventions", "/docs/v1/start/authentication"]
draft: false
---
Bind a [customer](/docs/v1/start/glossary#customer) [license](/docs/v1/start/glossary#license) to one persisted installation.

## What you will learn
- Send this exact operation with its required credentials and fields.
- Interpret success, refusal, side effects and retry risks.

## Prerequisites
- Complete [the Sandbox quickstart](/docs/v1/start/quickstart).
- Read [API conventions](/docs/v1/api/conventions) and [authentication](/docs/v1/start/authentication).
- Keep customer credentials private and management keys on your trusted backend.

## Method and path
POST /api/v1/licenses/activate

### When to use it
Bind an eligible customer license to the persisted random [installation ID](/docs/v1/start/glossary#installation-id) of a desktop app, CLI, plugin host or trusted service. Include email if your chosen application flow requires a matching email; this API also supports key-only [activation](/docs/v1/start/glossary#activation).

## Authentication and environment
Use the public X-App-ID and a customer [license key](/docs/v1/start/glossary#license-key). X-Environment defaults to SANDBOX; the license/customer lookup is environment-scoped.

## Request headers
| Header | Required | Description | Example |
| --- | --- | --- | --- |
| Accept | recommended | JSON responses | application/json |
| Content-Type | for JSON body | Use the documented JSON object | application/json |
| X-App-ID | yes | [Public App ID](/docs/v1/start/glossary#public-app-id),8–80 trimmed characters. | YOUR_PUBLIC_APP_ID |
| X-Environment | no | Activation environment; backend normalizes case. Does not override token/developer-key bindings. | SANDBOX |

## Path and query parameters
No path parameters are accepted.
No pagination, filtering, sorting or list query parameters are implemented. Use JSON rather than relying on alternate form/query parsing.

## Request body
| Field | Type | Required | Constraints/default | Description | Example |
| --- | --- | --- | --- | --- | --- |
| license_key | string | yes | minLength=12; maxLength=100 | Customer license key; case-insensitive hashed lookup. | "YOUR_CUSTOMER_LICENSE_KEY" |
| device_id | string | yes | minLength=16; maxLength=255 | Persisted random installation ID. | "YOUR_PERSISTED_INSTALLATION_ID" |
| email | string | no | maxLength=190 | Optional; nonempty normalized email must match the license customer. | "customer@example.invalid" |
| device_name | string | no | maxLength=160 | Optional descriptive label; invalid length becomes empty. | "Example workstation" |
| platform | string | no | maxLength=50 | Optional description, no OS enum. | "macOS" |
| app_version | string | no | maxLength=30 | Optional version; empty bypasses version-range check. | "1.0.0" |

### Full request JSON
```json
{
  "license_key": "YOUR_CUSTOMER_LICENSE_KEY",
  "device_id": "YOUR_PERSISTED_INSTALLATION_ID",
  "email": "customer@example.invalid",
  "device_name": "Example workstation",
  "platform": "macOS",
  "app_version": "1.0.0"
}
```

The schemas describe supported recommended input types. Current PHP parsing trims/casts strings and may ignore unknown fields; it is not strict JSON-schema validation. Invalid optional descriptive fields can become empty/null. [Conventions](/docs/v1/api/conventions) describes malformed JSON and alternate parsing.

## Success response
HTTP 200. The following is a real isolated Sandbox capture; secret values are replaced with explicit placeholders.
```json
{
  "success": true,
  "activation_token": "YOUR_ACTIVATION_TOKEN",
  "license": {
    "payload": {
      "license_id": "lic_578581bd80c2a672da30fc29",
      "product_id": "app_a642cd24641ec976626b",
      "product": "Docs fixture product",
      "plan": "fixture-plan",
      "status": "active",
      "environment": "sandbox",
      "expires_at": "2026-11-16T10:39:35+00:00",
      "license_key_mask": "TESTDOCS-••••-••••-HAHH",
      "starts_at": "2026-10-17T10:39:35+00:00",
      "created_at": "2026-10-17T12:39:35+00:00",
      "max_devices": 2,
      "max_activations": 4,
      "activation_count": 1,
      "min_version": null,
      "max_version": null,
      "active_devices": 1,
      "customer": {
        "id": "cus_d7db5516f8377f89a869e293",
        "name": "Synthetic contract customer",
        "email": "contract-6b9f0843f1d3609f@example.invalid",
        "company": null,
        "country": null
      },
      "product_details": {
        "id": "app_a642cd24641ec976626b",
        "name": "Docs fixture product",
        "platform": "desktop"
      },
      "plan_details": {
        "id": "plan_3bf54c099326639ee183661f",
        "name": "Fixture plan",
        "slug": "fixture-plan",
        "billing_type": "monthly",
        "price": 19.5,
        "currency": "EUR",
        "duration_days": 30,
        "trial_days": null
      },
      "features": {
        "pdf_export": true
      },
      "device": {
        "id": "dev_299a6753c013047b3ed013de",
        "installation_hash": "e119b615ebfb5e5a2da5ea9c2a64b2117621399ff61d16718d460e0bb919a988",
        "name": "Synthetic local installation",
        "platform": "test",
        "app_version": "1.0.0"
      },
      "server_time": "2026-10-17T10:39:35+00:00",
      "next_validation_at": "2026-10-18T10:39:35+00:00",
      "offline_grace_until": "2026-10-24T10:39:35+00:00"
    },
    "signature": "wYwFAPoyaaIVtq8zvUHlQeyqV91sI7115WJHUzY7unDEjOts7MrN_OL3PZAd-Ahd-OdfI-EjIwAVwhfLbYQlDQ",
    "algorithm": "Ed25519",
    "key_id": "ed25519_2b9bc7e214b1209f"
  },
  "request_id": "req_11a6f2cf9cfffdaf92e1a6ce"
}
```

### Response fields
| Field | Type | Required | Constraints | Description | Example |
| --- | --- | --- | --- | --- | --- |
| success | boolean | yes | const=true | The operation succeeded. | true |
| activation_token | string | yes | See description | act_ plus43 base64url characters; installation secret, do not log. | "YOUR_ACTIVATION_TOKEN" |
| license | object | yes | See description | Only payload is signed. This is PHP-specific canonical JSON, not RFC8785. | Nested object/array shown in full JSON |
| license.payload | object | yes | See description | Exact signed snapshot. Signature authenticity alone does not grant access. | Nested object/array shown in full JSON |
| license.payload.license_id | string | yes | See description | License public identifier. | "lic_578581bd80c2a672da30fc29" |
| license.payload.product_id | string | yes | See description | Public App ID; compare to configured [product](/docs/v1/start/glossary#product). | "app_a642cd24641ec976626b" |
| license.payload.product | string | yes | See description | Product display name. | "Docs fixture product" |
| license.payload.plan | string | yes | See description | Product-plan slug. | "fixture-plan" |
| license.payload.status | string | yes | enum=["active", "suspended", "revoked", "expired", "pending", "cancelled"] | Stored license status in lowercase. | "active" |
| license.payload.environment | string | yes | enum=["sandbox", "[live](/docs/v1/start/glossary#live)"] | Bound license environment. | "sandbox" |
| license.payload.expires_at | string or null | yes | format="date-time" | Independent license expiry; null has no configured expiry. | "2026-11-16T10:39:35+00:00" |
| license.payload.license_key_mask | string | yes | See description | Display-only masked key. | "TESTDOCS-••••-••••-HAHH" |
| license.payload.starts_at | string or null | yes | format="date-time" | Configured license start, currently not enforced by server eligibility. | "2026-10-17T10:39:35+00:00" |
| license.payload.created_at | string or null | yes | format="date-time" | Creation timestamp; database-timezone discrepancy is disclosed. | "2026-10-17T12:39:35+00:00" |
| license.payload.max_devices | integer | yes | See description | Concurrent [device](/docs/v1/start/glossary#device) limit. | 2 |
| license.payload.max_activations | integer or null | yes | See description | Cumulative activation cap; null means no configured cap. | 4 |
| license.payload.activation_count | integer | yes | See description | Cumulative consumed activations. | 1 |
| license.payload.min_version | string or null | yes | See description | Optional lower version restriction. | null |
| license.payload.max_version | string or null | yes | See description | Optional upper version restriction. | null |
| license.payload.active_devices | integer | yes | See description | Active count at snapshot time. | 1 |
| license.payload.customer | object | yes | See description | Customer information; personal data, not an authentication credential. | Nested object/array shown in full JSON |
| license.payload.customer.id | string | yes | See description | Customer public identifier. | "cus_d7db5516f8377f89a869e293" |
| license.payload.customer.name | string or null | yes | See description | Optional customer name. | "Synthetic contract customer" |
| license.payload.customer.email | string | yes | See description | Customer email associated with this license. | "contract-6b9f0843f1d3609f@example.invalid" |
| license.payload.customer.company | string or null | yes | See description | Optional company. | null |
| license.payload.customer.country | string or null | yes | See description | Optional country. | null |
| license.payload.product_details | object | yes | See description | Product display metadata. | Nested object/array shown in full JSON |
| license.payload.product_details.id | string | yes | See description | Public App ID. | "app_a642cd24641ec976626b" |
| license.payload.product_details.name | string | yes | See description | Product display name. | "Docs fixture product" |
| license.payload.product_details.platform | string | yes | See description | Lowercase configured product platform. | "desktop" |
| license.payload.plan_details | object | yes | See description | [Product plan](/docs/v1/start/glossary#product-plan), not the [developer](/docs/v1/start/glossary#developer) [platform subscription](/docs/v1/start/glossary#platform-subscription). | Nested object/array shown in full JSON |
| license.payload.plan_details.id | string | yes | See description | Internal product-plan identifier. | "plan_3bf54c099326639ee183661f" |
| license.payload.plan_details.name | string | yes | See description | Plan display name. | "Fixture plan" |
| license.payload.plan_details.slug | string | yes | See description | Plan slug. | "fixture-plan" |
| license.payload.plan_details.billing_type | string | yes | See description | Lowercase product-plan billing type. | "monthly" |
| license.payload.plan_details.price | number | yes | See description | PHP float; preserve numeric tokens such as19.0 for signatures. | 19.5 |
| license.payload.plan_details.currency | string | yes | See description | Configured product-plan currency. | "EUR" |
| license.payload.plan_details.duration_days | integer or null | yes | See description | Configured duration in days. | 30 |
| license.payload.plan_details.trial_days | integer or null | yes | See description | Configured trial duration in days. | null |
| license.payload.[features](/docs/v1/start/glossary#feature) | object or array | yes | See description | Dynamic plan feature JSON values; empty PHP feature array may be[]. Validate types before use. | Nested object/array shown in full JSON |
| license.payload.device | object | yes | See description | Installation binding and descriptions. | Nested object/array shown in full JSON |
| license.payload.device.id | string | yes | See description | Device public identifier. | "dev_299a6753c013047b3ed013de" |
| license.payload.device.installation_hash | string or null | yes | See description | SHA256 of supplied installation ID; null if validation header was omitted. | "e119b615ebfb5e5a2da5ea9c2a64b2117621399ff61d16718d460e0bb919a988" |
| license.payload.device.name | string or null | yes | See description | Optional device label; activation can return an empty string. | "Synthetic local installation" |
| license.payload.device.platform | string or null | yes | See description | Optional platform description. | "test" |
| license.payload.device.app_version | string or null | yes | See description | Optional application version. | "1.0.0" |
| license.payload.server_time | string | yes | format="date-time" | Signed snapshot time in UTC. | "2026-10-17T10:39:35+00:00" |
| license.payload.next_validation_at | string | yes | format="date-time" | server_time plus product interval hours. | "2026-10-18T10:39:35+00:00" |
| license.payload.offline_grace_until | string | yes | format="date-time" | server_time plus grace hours, not added after the [validation interval](/docs/v1/start/glossary#validation-interval). | "2026-10-24T10:39:35+00:00" |
| license.signature | string | yes | pattern="^[A-Za-z0-9_-]{86}$" | Unpadded base64url Ed25519 signature over canonical payload bytes. | "wYwFAPoyaaIVtq8zvUHlQeyqV91sI7115WJHUzY7unDEjOts7MrN_OL3PZAd-Ahd-OdfI-EjIwAVwhfLbYQlDQ" |
| license.algorithm | string | yes | const="Ed25519" | Fixed algorithm, not negotiated. | "Ed25519" |
| license.key_id | string | yes | See description | Must equal independently trusted key ID. | "ed25519_2b9bc7e214b1209f" |
| request_id | string | yes | pattern="^req_[a-f0-9]{24}$" | Request correlation ID. Replay bodies can retain an earlier ID. | "req_11a6f2cf9cfffdaf92e1a6ce" |

### Response headers
X-Request-ID identifies the current request. Successful limited calls include X-RateLimit-Remaining and X-RateLimit-Reset, the latter in Unix seconds.
Errors omit those rate headers and Retry-After. See the complete [rate-limit reference](/docs/v1/api/rate-limits).

## Error responses
| Code | HTTP | Cause | Fix | Retryable? |
| --- | --- | --- | --- | --- |
| RATE_LIMITED | 429 | Bucket exhausted; wait for window reset; no licensing Retry-After header | After window; apply jitter | After the 60-second window, with jitter |
| INVALID_REQUEST | 422 | Input constraints or entitlement/resource/renewal domain rejection | Correct input/plan; not blind retry | No blind retry; apply the correction |
| INVALID_LICENSE | 404 | Activation key/product/environment/customer email mismatch; SDK empty key local error has no HTTP | Correct details | No blind retry; apply the correction |
| LICENSE_EXPIRED | 403 | Elapsed expires_at before state check; or EXPIRED state; SDK local expiry has no HTTP | Renew eligible license | No blind retry; apply the correction |
| LICENSE_REVOKED | 403 | License REVOKED and no elapsed deadline taking precedence | Do not retry; contact developer | No blind retry; apply the correction |
| LICENSE_SUSPENDED | 403 | License SUSPENDED and no elapsed deadline taking precedence | Restore then reactivate | No blind retry; apply the correction |
| LICENSE_CANCELLED | 403 | License CANCELLED and no elapsed deadline taking precedence | Do not retry; new eligible license | No blind retry; apply the correction |
| LICENSE_PENDING | 403 | License PENDING and no elapsed deadline taking precedence | Wait for authorized activation | No blind retry; apply the correction |
| APP_VERSION_NOT_SUPPORTED | 403 | Nonempty activation app_version outside configured range | Use supported version | No blind retry; apply the correction |
| DEVICE_LIMIT_REACHED | 409 | New/inactive installation while active seats >= license.max_devices | Deactivate/reset a seat | No blind retry; apply the correction |
| ACTIVATION_LIMIT_REACHED | 409 | New/inactive installation while activation_count >= max_activations | Developer adjusts policy; reset-devices does not zero count | No blind retry; apply the correction |
| INTERNAL_ERROR | 500 | Uncaught exception at global boundary | Safe retry only for idempotent operation; preserve request_id | Only safe reads after backoff; reconcile mutations |

An unregistered path or wrong method is handled by the global router as NOT_FOUND (HTTP 404), not405. Every licensing error has success=false, error.code, error.message and request_id. [Errors](/docs/v1/api/errors) keeps SDK-local and operational namespaces separate.

## Side effects
Creates/reactivates a device and creates a new [activation token](/docs/v1/start/glossary#activation-token). A new or inactive device consumes activation_count and an active seat. Reusing an already ACTIVE device keeps the seat/count but revokes its earlier active tokens and issues a replacement token. Concurrent device checks and updates use a license transaction and row locks. Audit and [webhook](/docs/v1/start/glossary#webhook) license.activated are emitted; no email is sent directly. Device limits belong to the license, not the displayed platform-wide device allowance.

Authenticated requests can consume the [organization](/docs/v1/start/glossary#organization) monthly API usage counter once tenant context is established, including some failures. This usage counter is currently warning-only, not a monthly API rejection gate. Developer-key authentication can update last_used_at before a later failure. No request body or Authorization value is saved by the API metadata logger.

## Idempotency and concurrency
Idempotency-Key is ignored. Repeating activation can rotate the token even when the device is unchanged. Save only the latest accepted token through your secure-storage flow. Do not run simultaneous activation requests for one installation; their responses can arrive out of order and leave one caller holding an already-revoked token.

## Rate limits
20 requests per60 seconds for SHA256(IP + Public App ID + supplied trimmed license-key text). Early invalid input can reject before this bucket is reached. This is not an organization-wide abuse quota.
Fixed windows begin with the first hit after expiry. Attempted calls consume every bucket they reach, even if later business validation fails.

## Runnable examples
These are complete native HTTP transport programs, not full SDK clients or entitlement verifiers. JSON request bodies and credentials come from KDP_* environment variables. They print raw responses to a private terminal; do not send their stdout to application/CI logs. Use the [P5 verification guides](/docs/v1/security/verify-ed25519) before granting access.

Run sh request.sh activate.
### cURL
```curl
#!/bin/sh
# Purpose: inspect one Sandbox API operation; not signature verification.
# Requirements: POSIX sh, curl7.76+. Run: sh request.sh public-key
# Expected: JSON; exit0 HTTP2xx/1 HTTP rejection/2 setup or transport failure.
# KDP_* variables carry credentials/body. Output can contain newly issued secrets:
# use a private terminal only, never application/CI logs. Verify signed state separately.
set -eu
fail() { printf '%s\n' 'Check the operation and KDP_* configuration. Do not blindly retry mutations.' >&2; exit 2; }
[ "$#" -eq 1 ] || fail
name=$1
case "$name" in
  public-key) method='GET'; path='/public-key'; auth='public' ;;
  create-license) method='POST'; path='/licenses'; auth='developer' ;;
  activate) method='POST'; path='/licenses/activate'; auth='publicApp' ;;
  validate) method='POST'; path='/licenses/validate'; auth='activation' ;;
  deactivate) method='POST'; path='/licenses/deactivate'; auth='activation' ;;
  get-license) method='GET'; path='/licenses/{license}'; auth='developer' ;;
  revoke) method='POST'; path='/licenses/{license}/revoke'; auth='developer' ;;
  suspend) method='POST'; path='/licenses/{license}/suspend'; auth='developer' ;;
  restore) method='POST'; path='/licenses/{license}/restore'; auth='developer' ;;
  renew) method='POST'; path='/licenses/{license}/renew'; auth='developer' ;;
  reset-devices) method='POST'; path='/licenses/{license}/reset-devices'; auth='developer' ;;
  *) fail ;;
esac
base=${KDP_BASE_URL:-https://licensing.kdpika.com/api/v1}
base=${base%/}
case "$base" in *'@'*|*'?'*|*'#'*|*' '* ) fail ;; esac
case "$base" in
  https://*/api/v1) ;;
  http://127.0.0.1:*/api/v1|http://localhost:*/api/v1) [ "${KDP_ALLOW_LOOPBACK:-0}" = 1 ] || fail ;;
  *) fail ;;
esac
case "$path" in *'{license}'*)
  id=${KDP_LICENSE_ID:?Set KDP_LICENSE_ID}
  case "$id" in *[!A-Za-z0-9_-]*|'') fail ;; esac
  path=$(printf '%s' "$path" | sed "s/{license}/$id/") ;;
esac
set -- --silent --show-error --fail-with-body --connect-timeout 5 --max-time 15 --request "$method" \
  --header 'Accept: application/json' --header 'User-Agent: KDPikaDocsExample/1.0 curl'
case "$auth" in
  developer)
    case "${KDP_API_KEY:-}" in lmp_sandbox_*) ;; *) fail ;; esac
    set -- "$@" --header "Authorization: Bearer $KDP_API_KEY" ;;
  activation) set -- "$@" --header "Authorization: Bearer ${KDP_ACTIVATION_TOKEN:?Set KDP_ACTIVATION_TOKEN}" ;;
  publicApp) set -- "$@" --header "X-App-ID: ${KDP_APP_ID:?Set KDP_APP_ID}" --header 'X-Environment: SANDBOX' ;;
esac
if [ "$name" = create-license ]; then set -- "$@" --header "Idempotency-Key: ${KDP_IDEMPOTENCY_KEY:?Set KDP_IDEMPOTENCY_KEY}"; fi
if [ "$name" = validate ]; then set -- "$@" --header "X-Installation-ID: ${KDP_INSTALLATION_ID:?Set KDP_INSTALLATION_ID}"; fi
if [ "$method" = POST ]; then
  body=${KDP_BODY_JSON-'{}'}
  set -- "$@" --header 'Content-Type: application/json' --data-binary "$body"
fi
# Keep the response in memory only, separating the final status line. No file,
# --location, --insecure or --verbose. The caller must still inspect JSON success.
if response=$(curl "$@" --write-out '\n%{http_code}' "$base$path"); then transport=0; else transport=$?; fi
newline='
'
status=${response##*"$newline"}
payload=${response%"$newline"*}
case "$status" in [0-9][0-9][0-9]) ;; *) fail ;; esac
if [ "$transport" -ne 0 ] && [ "$transport" -ne 22 ]; then fail; fi
printf '%s\n' "$payload"
case "$status" in 2[0-9][0-9]) exit 0 ;; esac
printf '%s\n' 'The API did not accept the request. Inspect error.code/request_id; reconcile mutations before retrying.' >&2
exit 1
```

Run python3 request.py activate.
### Python
```python
"""Inspect one Sandbox API operation; transport example, not access authorization.
Requires Python3.9+ standard library. Run: python3 request.py public-key
Expected: full API JSON on stdout; exit0 on success,1 on API rejection,2 on setup/transport failure.
Credentials/body via KDP_* environment variables. Stdout may contain new secrets:
use only a private terminal, never application/CI logs. Verify signed state separately.
"""
import json
import os
import re
import sys
from urllib.error import HTTPError
from urllib.parse import urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener

# Preserve raw UTF-8 JSON even when piped on a non-UTF-8 Windows console.
sys.stdout.reconfigure(encoding='utf-8')

OPERATIONS = json.loads(r'''{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "create-license": {
    "method": "POST",
    "path": "/licenses",
    "auth": "developer"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  },
  "get-license": {
    "method": "GET",
    "path": "/licenses/{license}",
    "auth": "developer"
  },
  "revoke": {
    "method": "POST",
    "path": "/licenses/{license}/revoke",
    "auth": "developer"
  },
  "suspend": {
    "method": "POST",
    "path": "/licenses/{license}/suspend",
    "auth": "developer"
  },
  "restore": {
    "method": "POST",
    "path": "/licenses/{license}/restore",
    "auth": "developer"
  },
  "renew": {
    "method": "POST",
    "path": "/licenses/{license}/renew",
    "auth": "developer"
  },
  "reset-devices": {
    "method": "POST",
    "path": "/licenses/{license}/reset-devices",
    "auth": "developer"
  }
}''')


def required(name):
    value = os.environ.get(name, '')
    if not value or '\r' in value or '\n' in value:
        raise ValueError('Set a valid ' + name + '.')
    return value


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, request, file, code, message, headers, new_url):
        return None


def main():
    if len(sys.argv) != 2 or sys.argv[1] not in OPERATIONS:
        raise ValueError('Choose an operation: ' + ', '.join(OPERATIONS))
    operation = OPERATIONS[sys.argv[1]]
    base = os.environ.get('KDP_BASE_URL', 'https://licensing.kdpika.com/api/v1').rstrip('/')
    parsed = urlsplit(base)
    loopback = parsed.scheme == 'http' and parsed.hostname in ('127.0.0.1', 'localhost') and os.environ.get('KDP_ALLOW_LOOPBACK') == '1'
    if not parsed.hostname or (parsed.scheme != 'https' and not loopback) or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path != '/api/v1':
        raise ValueError('Use an HTTPS API base URL ending in /api/v1. Loopback HTTP needs explicit test opt-in.')
    path = operation['path']
    if '{license}' in path:
        identifier = required('KDP_LICENSE_ID')
        if not re.fullmatch(r'[A-Za-z0-9_-]+', identifier):
            raise ValueError('This sample accepts the simple license IDs issued by the platform.')
        path = path.replace('{license}', identifier)
    headers = {'Accept': 'application/json', 'User-Agent': 'KDPikaDocsExample/1.0 Python'}
    if operation['auth'] == 'developer':
        key = required('KDP_API_KEY')
        if not key.startswith('lmp_sandbox_'):
            raise ValueError('Use a Sandbox developer API key with this example.')
        headers['Authorization'] = 'Bearer ' + key
    elif operation['auth'] == 'activation':
        headers['Authorization'] = 'Bearer ' + required('KDP_ACTIVATION_TOKEN')
    elif operation['auth'] == 'publicApp':
        headers.update({'X-App-ID': required('KDP_APP_ID'), 'X-Environment': 'SANDBOX'})
    if sys.argv[1] == 'create-license':
        headers['Idempotency-Key'] = required('KDP_IDEMPOTENCY_KEY')
    if sys.argv[1] == 'validate':
        headers['X-Installation-ID'] = required('KDP_INSTALLATION_ID')
    body = None
    if operation['method'] == 'POST':
        source = os.environ.get('KDP_BODY_JSON', '{}')
        if not isinstance(json.loads(source), dict):
            raise ValueError('KDP_BODY_JSON must be a JSON object.')
        body = source.encode('utf-8')
        headers['Content-Type'] = 'application/json'
    request = Request(base + path, data=body, headers=headers, method=operation['method'])
    try:
        response = build_opener(NoRedirect()).open(request, timeout=15)
    except HTTPError as error:
        response = error
    raw = response.read().decode('utf-8')
    result = json.loads(raw)
    sys.stdout.write(raw + '\n')
    if not (200 <= response.status < 300 and result.get('success') is True):
        sys.stderr.write('The API rejected this request. Check error.code and request_id; do not blindly retry a mutation.\n')
        return 1
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main())
    except ValueError as error:
        # Configuration errors never interpolate credential values.
        sys.stderr.write(str(error) if str(error).startswith(('Set a valid KDP_', 'Choose an operation:', 'Use ', 'This sample ', 'KDP_BODY_JSON ')) else 'The response or request was not valid JSON.')
        sys.stderr.write('\n')
        sys.exit(2)
    except Exception:
        sys.stderr.write('Request unavailable. Check connectivity; reconcile uncertain mutations before retrying.\n')
        sys.exit(2)
```

Run node request.mjs activate.
### JavaScript (Node)
```javascript
// Purpose: inspect one Sandbox API operation; not an entitlement verifier.
// Requirements: Node18.20+ native fetch, trusted server/Electron main process.
// Run: node request.mjs public-key. Expected: JSON; exit0 success/1 rejection/2 transport or setup.
// Credentials/body use KDP_* environment variables. Output can contain new secrets.
// Use a private terminal, never application/CI logs. Verify signed state separately.
const operations = Object.freeze({
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "create-license": {
    "method": "POST",
    "path": "/licenses",
    "auth": "developer"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  },
  "get-license": {
    "method": "GET",
    "path": "/licenses/{license}",
    "auth": "developer"
  },
  "revoke": {
    "method": "POST",
    "path": "/licenses/{license}/revoke",
    "auth": "developer"
  },
  "suspend": {
    "method": "POST",
    "path": "/licenses/{license}/suspend",
    "auth": "developer"
  },
  "restore": {
    "method": "POST",
    "path": "/licenses/{license}/restore",
    "auth": "developer"
  },
  "renew": {
    "method": "POST",
    "path": "/licenses/{license}/renew",
    "auth": "developer"
  },
  "reset-devices": {
    "method": "POST",
    "path": "/licenses/{license}/reset-devices",
    "auth": "developer"
  }
});
function required(name) {
  const value = process.env[name];
  if (!value || /[\r\n]/.test(value)) throw new Error(`Set a valid ${name}.`);
  return value;
}
async function main() {
  const name = process.argv[2];
  if (process.argv.length !== 3 || !Object.hasOwn(operations, name)) throw new Error('Choose a documented operation.');
  const operation = operations[name];
  const base = (process.env.KDP_BASE_URL || 'https://licensing.kdpika.com/api/v1').replace(/\/+$/, '');
  const url = new URL(base);
  const loopback = url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname) && process.env.KDP_ALLOW_LOOPBACK === '1';
  if ((url.protocol !== 'https:' && !loopback) || url.username || url.password || url.search || url.hash || url.pathname !== '/api/v1') throw new Error('Use an HTTPS API URL ending in /api/v1; loopback HTTP requires explicit test opt-in.');
  let path = operation.path;
  if (path.includes('{license}')) {
    const id = required('KDP_LICENSE_ID');
    if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error('Use the simple license ID issued by this platform with this sample.');
    path = path.replace('{license}', id);
  }
  const headers = {'Accept': 'application/json', 'User-Agent': 'KDPikaDocsExample/1.0 Node'};
  if (operation.auth === 'developer') {
    const key = required('KDP_API_KEY');
    if (!key.startsWith('lmp_sandbox_')) throw new Error('Use a Sandbox developer key.');
    headers.Authorization = `Bearer ${key}`;
  } else if (operation.auth === 'activation') headers.Authorization = `Bearer ${required('KDP_ACTIVATION_TOKEN')}`;
  else if (operation.auth === 'publicApp') {
    headers['X-App-ID'] = required('KDP_APP_ID'); headers['X-Environment'] = 'SANDBOX';
  }
  if (name === 'create-license') headers['Idempotency-Key'] = required('KDP_IDEMPOTENCY_KEY');
  if (name === 'validate') headers['X-Installation-ID'] = required('KDP_INSTALLATION_ID');
  let body;
  if (operation.method === 'POST') {
    body = process.env.KDP_BODY_JSON || '{}';
    const value = JSON.parse(body);
    if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('KDP_BODY_JSON must be a JSON object.');
    headers['Content-Type'] = 'application/json';
  }
  const response = await fetch(base + path, {method: operation.method, headers, body, redirect: 'error', signal: AbortSignal.timeout(15000)});
  const raw = await response.text();
  const result = JSON.parse(raw);
  process.stdout.write(raw + '\n');
  if (!response.ok || result.success !== true) {
    process.stderr.write('The API rejected this request. Inspect error.code and request_id; reconcile mutations before retrying.\n');
    return 1;
  }
  return 0;
}
main().then(code => {process.exitCode = code;}).catch(() => {
  process.stderr.write('Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.\n');
  process.exitCode = 2;
});
```

Run php request.php activate.
### PHP
```php
<?php
declare(strict_types=1);
// Purpose: inspect one Sandbox API operation; not an entitlement verifier.
// Requirements: PHP8.1+, cURL extension. Run: php request.php public-key
// Expected: JSON, exit0 success/1 rejection/2 setup or transport failure.
// Credentials/body via KDP_* variables. Stdout may contain new credentials:
// use a private terminal only, not application/CI logs. Verify signed state separately.
$operations = json_decode(<<<'JSON'
{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "create-license": {
    "method": "POST",
    "path": "/licenses",
    "auth": "developer"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  },
  "get-license": {
    "method": "GET",
    "path": "/licenses/{license}",
    "auth": "developer"
  },
  "revoke": {
    "method": "POST",
    "path": "/licenses/{license}/revoke",
    "auth": "developer"
  },
  "suspend": {
    "method": "POST",
    "path": "/licenses/{license}/suspend",
    "auth": "developer"
  },
  "restore": {
    "method": "POST",
    "path": "/licenses/{license}/restore",
    "auth": "developer"
  },
  "renew": {
    "method": "POST",
    "path": "/licenses/{license}/renew",
    "auth": "developer"
  },
  "reset-devices": {
    "method": "POST",
    "path": "/licenses/{license}/reset-devices",
    "auth": "developer"
  }
}
JSON, true, 512, JSON_THROW_ON_ERROR);
function required(string $name): string {
    $value = (string) getenv($name);
    if ($value === '' || str_contains($value, "\r") || str_contains($value, "\n")) throw new RuntimeException('Missing configuration.');
    return $value;
}
try {
    $name = $argv[1] ?? '';
    if ($argc !== 2 || !isset($operations[$name])) throw new RuntimeException('Invalid operation.');
    $operation = $operations[$name];
    $base = rtrim(getenv('KDP_BASE_URL') ?: 'https://licensing.kdpika.com/api/v1', '/');
    $url = parse_url($base);
    $loopback = ($url['scheme'] ?? '') === 'http' && in_array($url['host'] ?? '', ['127.0.0.1', 'localhost'], true) && getenv('KDP_ALLOW_LOOPBACK') === '1';
    if (!$url || empty($url['host']) || (($url['scheme'] ?? '') !== 'https' && !$loopback) || isset($url['user'], $url['pass']) || isset($url['user']) || isset($url['query']) || isset($url['fragment']) || ($url['path'] ?? '') !== '/api/v1') throw new RuntimeException('Invalid base URL.');
    $path = $operation['path'];
    if (str_contains($path, '{license}')) {
        $id = required('KDP_LICENSE_ID');
        if (!preg_match('/^[A-Za-z0-9_-]+$/D', $id)) throw new RuntimeException('Invalid sample license ID.');
        $path = str_replace('{license}', $id, $path);
    }
    $headers = ['Accept: application/json', 'User-Agent: KDPikaDocsExample/1.0 PHP'];
    if ($operation['auth'] === 'developer') {
        $key = required('KDP_API_KEY');
        if (!str_starts_with($key, 'lmp_sandbox_')) throw new RuntimeException('Sandbox key required.');
        $headers[] = 'Authorization: Bearer ' . $key;
    } elseif ($operation['auth'] === 'activation') $headers[] = 'Authorization: Bearer ' . required('KDP_ACTIVATION_TOKEN');
    elseif ($operation['auth'] === 'publicApp') {
        $headers[] = 'X-App-ID: ' . required('KDP_APP_ID'); $headers[] = 'X-Environment: SANDBOX';
    }
    if ($name === 'create-license') $headers[] = 'Idempotency-Key: ' . required('KDP_IDEMPOTENCY_KEY');
    if ($name === 'validate') $headers[] = 'X-Installation-ID: ' . required('KDP_INSTALLATION_ID');
    $curl = curl_init($base . $path);
    $options = [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false, CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_TIMEOUT => 15, CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2, CURLOPT_CUSTOMREQUEST => $operation['method']];
    if ($operation['method'] === 'POST') {
        $body = getenv('KDP_BODY_JSON') ?: '{}';
        if (!is_object(json_decode($body, false, 512, JSON_THROW_ON_ERROR))) throw new RuntimeException('JSON object required.');
        $headers[] = 'Content-Type: application/json'; $options[CURLOPT_POSTFIELDS] = $body;
    }
    $options[CURLOPT_HTTPHEADER] = $headers;
    curl_setopt_array($curl, $options);
    $raw = curl_exec($curl);
    if ($raw === false) throw new RuntimeException('Transport unavailable.');
    $status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
    // No curl_close: PHP objects release the handle; PHP8.5 deprecates that call.
    $result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
    echo $raw . "\n";
    if ($status < 200 || $status >= 300 || ($result['success'] ?? null) !== true) {
        fwrite(STDERR, "The API rejected this request. Inspect error.code/request_id; reconcile mutations before retrying.\n"); exit(1);
    }
    exit(0);
} catch (Throwable) {
    fwrite(STDERR, "Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.\n"); exit(2);
}
```

Run dotnet run --project ApiExample.csproj -- activate.
### C#
```csharp
// Purpose: inspect one Sandbox API operation; transport only, not feature access.
// Requirements: .NET7+ console project. Run: dotnet run -- public-key
// Expected: JSON; exit0 success/1 API rejection/2 setup or transport failure.
// KDP_* environment variables carry credentials/body. Stdout can contain new secrets:
// use a private terminal, never application/CI logs. Verify signed state separately.
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;

Console.OutputEncoding = new UTF8Encoding(false);

const string Contract = """
{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "create-license": {
    "method": "POST",
    "path": "/licenses",
    "auth": "developer"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  },
  "get-license": {
    "method": "GET",
    "path": "/licenses/{license}",
    "auth": "developer"
  },
  "revoke": {
    "method": "POST",
    "path": "/licenses/{license}/revoke",
    "auth": "developer"
  },
  "suspend": {
    "method": "POST",
    "path": "/licenses/{license}/suspend",
    "auth": "developer"
  },
  "restore": {
    "method": "POST",
    "path": "/licenses/{license}/restore",
    "auth": "developer"
  },
  "renew": {
    "method": "POST",
    "path": "/licenses/{license}/renew",
    "auth": "developer"
  },
  "reset-devices": {
    "method": "POST",
    "path": "/licenses/{license}/reset-devices",
    "auth": "developer"
  }
}
""";
try
{
    using var operations = JsonDocument.Parse(Contract);
    if (args.Length != 1 || !operations.RootElement.TryGetProperty(args[0], out var operation)) throw new Exception("Invalid operation.");
    var name = args[0];
    string Required(string key)
    {
        var value = Environment.GetEnvironmentVariable(key);
        if (String.IsNullOrEmpty(value) || value.Contains('\r') || value.Contains('\n')) throw new Exception("Missing configuration.");
        return value;
    }
    var root = (Environment.GetEnvironmentVariable("KDP_BASE_URL") ?? "https://licensing.kdpika.com/api/v1").TrimEnd('/');
    var uri = new Uri(root);
    var loopback = uri.Scheme == "http" && (uri.Host == "127.0.0.1" || uri.Host == "localhost") && Environment.GetEnvironmentVariable("KDP_ALLOW_LOOPBACK") == "1";
    if ((uri.Scheme != "https" && !loopback) || uri.UserInfo != "" || uri.Query != "" || uri.Fragment != "" || uri.AbsolutePath != "/api/v1") throw new Exception("Invalid base URL.");
    var path = operation.GetProperty("path").GetString()!;
    if (path.Contains("{license}"))
    {
        var identifier = Required("KDP_LICENSE_ID");
        if (!Regex.IsMatch(identifier, "^[A-Za-z0-9_-]+$")) throw new Exception("Unsupported sample identifier.");
        path = path.Replace("{license}", identifier);
    }
    using var handler = new HttpClientHandler {AllowAutoRedirect = false};
    using var client = new HttpClient(handler) {Timeout = TimeSpan.FromSeconds(15)};
    using var request = new HttpRequestMessage(new HttpMethod(operation.GetProperty("method").GetString()!), root + path);
    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    request.Headers.UserAgent.ParseAdd("KDPikaDocsExample/1.0 CSharp");
    var auth = operation.GetProperty("auth").GetString();
    if (auth == "developer")
    {
        var key = Required("KDP_API_KEY");
        if (!key.StartsWith("lmp_sandbox_", StringComparison.Ordinal)) throw new Exception("Sandbox key required.");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
    }
    else if (auth == "activation") request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Required("KDP_ACTIVATION_TOKEN"));
    else if (auth == "publicApp")
    {
        request.Headers.Add("X-App-ID", Required("KDP_APP_ID")); request.Headers.Add("X-Environment", "SANDBOX");
    }
    if (name == "create-license") request.Headers.Add("Idempotency-Key", Required("KDP_IDEMPOTENCY_KEY"));
    if (name == "validate") request.Headers.Add("X-Installation-ID", Required("KDP_INSTALLATION_ID"));
    if (request.Method == HttpMethod.Post)
    {
        var body = Environment.GetEnvironmentVariable("KDP_BODY_JSON") ?? "{}";
        using var parsedBody = JsonDocument.Parse(body);
        if (parsedBody.RootElement.ValueKind != JsonValueKind.Object) throw new Exception("JSON object required.");
        request.Content = new StringContent(body, Encoding.UTF8, "application/json");
    }
    using var response = await client.SendAsync(request);
    var raw = await response.Content.ReadAsStringAsync();
    using var result = JsonDocument.Parse(raw);
    Console.WriteLine(raw);
    if (!response.IsSuccessStatusCode || !result.RootElement.TryGetProperty("success", out var success) || success.ValueKind != JsonValueKind.True)
    {
        Console.Error.WriteLine("The API rejected this request. Inspect error.code/request_id; reconcile mutations before retrying."); return 1;
    }
    return 0;
}
catch (Exception)
{
    Console.Error.WriteLine("Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations."); return 2;
}
```
```csharp
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup><Compile Remove="errors/**/*.cs" /><None Remove="errors/**/obj/**;errors/**/bin/**" /></ItemGroup>
</Project>
```

Run node compiled/request.js activate.
### TypeScript
```typescript
// Purpose: inspect one Sandbox API operation; not an entitlement verifier.
// Requirements: TypeScript7.0.2, @types/node22.19.7, Node18.20+ native fetch, trusted server/Electron main process.
// Run compiled request.js with public-key after strict TypeScript compilation. Expected: JSON; exit0 success/1 rejection/2 transport or setup.
// Credentials/body use KDP_* environment variables. Output can contain new secrets.
// Use a private terminal, never application/CI logs. Verify signed state separately.
const operations: Readonly<Record<string, {method:string;path:string;auth:string}>> = Object.freeze({
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
});
function required(name: string): string {
  const value = process.env[name];
  if (!value || /[\r\n]/.test(value)) throw new Error(`Set a valid ${name}.`);
  return value;
}
async function main() {
  const name = process.argv[2] ?? '';
  if (process.argv.length !== 3 || !Object.hasOwn(operations, name)) throw new Error('Choose a documented operation.');
  const operation = operations[name];
  const base = (process.env.KDP_BASE_URL || 'https://licensing.kdpika.com/api/v1').replace(/\/+$/, '');
  const url = new URL(base);
  const loopback = url.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(url.hostname) && process.env.KDP_ALLOW_LOOPBACK === '1';
  if ((url.protocol !== 'https:' && !loopback) || url.username || url.password || url.search || url.hash || url.pathname !== '/api/v1') throw new Error('Use an HTTPS API URL ending in /api/v1; loopback HTTP requires explicit test opt-in.');
  let path = operation.path;
  if (path.includes('{license}')) {
    const id = required('KDP_LICENSE_ID');
    if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error('Use the simple license ID issued by this platform with this sample.');
    path = path.replace('{license}', id);
  }
  const headers: Record<string,string> = {'Accept': 'application/json', 'User-Agent': 'KDPikaDocsExample/1.0 Node'};
  if (operation.auth === 'developer') {
    const key = required('KDP_API_KEY');
    if (!key.startsWith('lmp_sandbox_')) throw new Error('Use a Sandbox developer key.');
    headers.Authorization = `Bearer ${key}`;
  } else if (operation.auth === 'activation') headers.Authorization = `Bearer ${required('KDP_ACTIVATION_TOKEN')}`;
  else if (operation.auth === 'publicApp') {
    headers['X-App-ID'] = required('KDP_APP_ID'); headers['X-Environment'] = 'SANDBOX';
  }
  if (name === 'create-license') headers['Idempotency-Key'] = required('KDP_IDEMPOTENCY_KEY');
  if (name === 'validate') headers['X-Installation-ID'] = required('KDP_INSTALLATION_ID');
  let body;
  if (operation.method === 'POST') {
    body = process.env.KDP_BODY_JSON || '{}';
    const value = JSON.parse(body);
    if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('KDP_BODY_JSON must be a JSON object.');
    headers['Content-Type'] = 'application/json';
  }
  const response = await fetch(base + path, {method: operation.method, headers, body, redirect: 'error', signal: AbortSignal.timeout(15000)});
  const raw = await response.text();
  const result = JSON.parse(raw);
  process.stdout.write(raw + '\n');
  if (!response.ok || result.success !== true) {
    process.stderr.write('The API rejected this request. Inspect error.code and request_id; reconcile mutations before retrying.\n');
    return 1;
  }
  return 0;
}
main().then(code => {process.exitCode = code;}).catch(() => {
  process.stderr.write('Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.\n');
  process.exitCode = 2;
});
```

Run java -cp .:gson.jar Request activate.
### Java
```java
// Purpose: inspect one client-callable Sandbox operation, not grant feature access.
// Requires Java17+, Gson2.14.0. Run: java -cp .:gson.jar Request public-key
// Windows classpaths use semicolons. Expected: JSON; exit0 success/1 API error/2 setup or transport.
// Credentials/body: KDP_* environment variables. Private terminal only; output may contain secrets.
import java.net.URI;
import java.net.http.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import com.google.gson.*;

public final class Request {
    static final String CONTRACT = """
{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
}
""";
    static String required(String name) {
        String value = System.getenv(name);
        if (value == null || value.isEmpty() || value.contains("\r") || value.contains("\n")) throw new IllegalArgumentException("Missing configuration.");
        return value;
    }
    public static void main(String[] args) {
        try {
            JsonObject operations = JsonParser.parseString(CONTRACT).getAsJsonObject();
            if (args.length != 1 || !operations.has(args[0])) throw new IllegalArgumentException("Unknown operation.");
            String name = args[0]; JsonObject op = operations.getAsJsonObject(name);
            String base = System.getenv().getOrDefault("KDP_BASE_URL", "https://licensing.kdpika.com/api/v1").replaceAll("/+$", "");
            URI uri = URI.create(base);
            boolean local = "http".equals(uri.getScheme()) && ("localhost".equals(uri.getHost()) || "127.0.0.1".equals(uri.getHost())) && "1".equals(System.getenv("KDP_ALLOW_LOOPBACK"));
            if (uri.getHost() == null || (!"https".equals(uri.getScheme()) && !local) || uri.getUserInfo() != null || uri.getQuery() != null || uri.getFragment() != null || !"/api/v1".equals(uri.getPath())) throw new IllegalArgumentException("Invalid base URL.");
            HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + op.get("path").getAsString())).timeout(Duration.ofSeconds(15))
                .header("Accept", "application/json").header("User-Agent", "KDPikaDocsExample/1.0 Java");
            String auth = op.get("auth").getAsString();
            if (auth.equals("publicApp")) request.header("X-App-ID", required("KDP_APP_ID")).header("X-Environment", "SANDBOX");
            if (auth.equals("activation")) request.header("Authorization", "Bearer " + required("KDP_ACTIVATION_TOKEN"));
            if (name.equals("validate")) request.header("X-Installation-ID", required("KDP_INSTALLATION_ID"));
            if (op.get("method").getAsString().equals("POST")) {
                String body = System.getenv().getOrDefault("KDP_BODY_JSON", "{}");
                if (!JsonParser.parseString(body).isJsonObject()) throw new IllegalArgumentException("JSON object required.");
                request.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8));
            } else request.GET();
            HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
            HttpResponse<String> response = client.send(request.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
            JsonObject result = JsonParser.parseString(response.body()).getAsJsonObject();
            System.out.write(response.body().getBytes(StandardCharsets.UTF_8)); System.out.write(10);
            if (response.statusCode() < 200 || response.statusCode() >= 300 || !result.has("success") || !result.get("success").equals(new JsonPrimitive(true))) {
                System.err.println("API rejection. Inspect error.code/request_id; reconcile mutations before retrying."); System.exit(1);
            }
        } catch (Exception error) {
            System.err.println("Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations."); System.exit(2);
        }
    }
}
```

Run go run request.go activate.
### Go
```go
// Purpose: inspect one client-callable Sandbox operation, not grant access.
// Requires Go1.20+ standard library. Run: go run request.go public-key
// Expected: JSON, exit0 success/1 API rejection/2 setup or transport failure.
// Credentials/body: KDP_* variables; output may contain secrets. Private terminal only.
package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

type operation struct {
	Method string `json:"method"`
	Path   string `json:"path"`
	Auth   string `json:"auth"`
}

const contract = `{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
}`

func required(name string) string {
	v := os.Getenv(name)
	if v == "" || strings.ContainsAny(v, "\r\n") {
		panic("configuration")
	}
	return v
}
func execute() int {
	var operations map[string]operation
	if json.Unmarshal([]byte(contract), &operations) != nil || len(os.Args) != 2 {
		panic("operation")
	}
	name := os.Args[1]
	op, ok := operations[name]
	if !ok {
		panic("operation")
	}
	base := os.Getenv("KDP_BASE_URL")
	if base == "" {
		base = "https://licensing.kdpika.com/api/v1"
	}
	base = strings.TrimRight(base, "/")
	u, err := url.Parse(base)
	if err != nil {
		panic("URL")
	}
	local := u.Scheme == "http" && (u.Hostname() == "127.0.0.1" || u.Hostname() == "localhost") && os.Getenv("KDP_ALLOW_LOOPBACK") == "1"
	if u.Hostname() == "" || (u.Scheme != "https" && !local) || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "/api/v1" {
		panic("URL")
	}
	body := ""
	if op.Method == "POST" {
		body = os.Getenv("KDP_BODY_JSON")
		if body == "" {
			body = "{}"
		}
		var object map[string]json.RawMessage
		if json.Unmarshal([]byte(body), &object) != nil || object == nil {
			panic("body")
		}
	}
	request, err := http.NewRequest(op.Method, base+op.Path, strings.NewReader(body))
	if err != nil {
		panic("request")
	}
	request.Header.Set("Accept", "application/json")
	request.Header.Set("User-Agent", "KDPikaDocsExample/1.0 Go")
	if op.Method == "POST" {
		request.Header.Set("Content-Type", "application/json")
	}
	if op.Auth == "publicApp" {
		request.Header.Set("X-App-ID", required("KDP_APP_ID"))
		request.Header.Set("X-Environment", "SANDBOX")
	}
	if op.Auth == "activation" {
		request.Header.Set("Authorization", "Bearer "+required("KDP_ACTIVATION_TOKEN"))
	}
	if name == "validate" {
		request.Header.Set("X-Installation-ID", required("KDP_INSTALLATION_ID"))
	}
	client := &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
	response, err := client.Do(request)
	if err != nil {
		panic("transport")
	}
	defer response.Body.Close()
	raw, err := io.ReadAll(io.LimitReader(response.Body, 1048577))
	if err != nil || len(raw) > 1048576 {
		panic("response")
	}
	var result struct {
		Success bool `json:"success"`
	}
	if json.Unmarshal(raw, &result) != nil {
		panic("JSON")
	}
	fmt.Println(string(raw))
	if response.StatusCode < 200 || response.StatusCode >= 300 || !result.Success {
		fmt.Fprintln(os.Stderr, "API rejection. Inspect error.code/request_id; reconcile mutations before retrying.")
		return 1
	}
	return 0
}
func main() {
	code := 2
	func() {
		defer func() {
			if recover() != nil {
				fmt.Fprintln(os.Stderr, "Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.")
			}
		}()
		code = execute()
	}()
	os.Exit(code)
}
```

Run cargo run --locked --manifest-path rust/Cargo.toml -- activate.
### Rust
```rust
// Purpose: inspect one client-callable Sandbox operation; not entitlement verification.
// Requires Rust1.82+, pinned Cargo.toml/Cargo.lock. Run: cargo run -- public-key
// Expected: raw JSON; exit0 success/1 API rejection/2 setup or transport failure.
// KDP_* variables carry credentials/body; private terminal only, output may contain secrets.
use serde_json::Value;
use std::{env, process, time::Duration};
const CONTRACT: &str = r#"{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
}"#;
fn required(name: &str) -> Result<String, Box<dyn std::error::Error>> {
    let value = env::var(name)?;
    if value.is_empty() || value.contains('\r') || value.contains('\n') {
        return Err("configuration".into());
    };
    Ok(value)
}
fn execute() -> Result<i32, Box<dyn std::error::Error>> {
    let operations: Value = serde_json::from_str(CONTRACT)?;
    let args: Vec<String> = env::args().collect();
    if args.len() != 2 {
        return Err("operation".into());
    }
    let name = &args[1];
    let op = operations.get(name).ok_or("operation")?;
    let base = env::var("KDP_BASE_URL")
        .unwrap_or_else(|_| "https://licensing.kdpika.com/api/v1".into())
        .trim_end_matches('/')
        .to_string();
    let uri = url::Url::parse(&base)?;
    let local = uri.scheme() == "http"
        && matches!(uri.host_str(), Some("127.0.0.1" | "localhost"))
        && env::var("KDP_ALLOW_LOOPBACK").unwrap_or_default() == "1";
    if uri.host_str().is_none()
        || (uri.scheme() != "https" && !local)
        || !uri.username().is_empty()
        || uri.password().is_some()
        || uri.query().is_some()
        || uri.fragment().is_some()
        || uri.path() != "/api/v1"
    {
        return Err("URL".into());
    }
    let method = op["method"].as_str().ok_or("method")?;
    let agent = ureq::AgentBuilder::new()
        .timeout(Duration::from_secs(15))
        .redirects(0)
        .build();
    let target = base + op["path"].as_str().ok_or("path")?;
    let mut request = agent
        .request(method, &target)
        .set("Accept", "application/json")
        .set("User-Agent", "KDPikaDocsExample/1.0 Rust");
    if op["auth"] == "publicApp" {
        request = request
            .set("X-App-ID", &required("KDP_APP_ID")?)
            .set("X-Environment", "SANDBOX")
    }
    if op["auth"] == "activation" {
        request = request.set(
            "Authorization",
            &("Bearer ".to_string() + &required("KDP_ACTIVATION_TOKEN")?),
        )
    }
    if name == "validate" {
        request = request.set("X-Installation-ID", &required("KDP_INSTALLATION_ID")?)
    }
    let answer = if method == "POST" {
        let body = env::var("KDP_BODY_JSON").unwrap_or_else(|_| "{}".into());
        if !serde_json::from_str::<Value>(&body)?.is_object() {
            return Err("body".into());
        }
        request
            .set("Content-Type", "application/json")
            .send_string(&body)
    } else {
        request.call()
    };
    let response = match answer {
        Ok(response) => response,
        Err(ureq::Error::Status(_, response)) => response,
        Err(error) => return Err(Box::new(error)),
    };
    let status = response.status();
    let raw = response.into_string()?;
    let result: Value = serde_json::from_str(&raw)?;
    println!("{}", raw);
    if !(200..300).contains(&status) || result["success"] != true {
        eprintln!(
            "API rejection. Inspect error.code/request_id; reconcile mutations before retrying."
        );
        return Ok(1);
    }
    Ok(0)
}
fn main() {
    process::exit(match execute() {
        Ok(code) => code,
        Err(_) => {
            eprintln!("Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.");
            2
        }
    })
}
```
```rust
[package]
name = "kdpika-api-example"
version = "1.0.0"
edition = "2021"
rust-version = "1.82"

[dependencies]
ureq = { version = "=2.12.1", default-features = false, features = ["tls"] }
url = "=2.5.2"
serde_json = "=1.0.145"
# Keep the tested Rust1.82 toolchain compatible with this pinned lock.
zeroize = "=1.8.1"
```

Run ruby request.rb activate.
### Ruby
```ruby
# Purpose: inspect one client-callable Sandbox operation, not grant feature access.
# Requires Ruby2.6+ standard library. Run: ruby request.rb public-key
# Expected: JSON; exit0 success/1 API rejection/2 setup or transport failure.
# Credentials/body: KDP_* variables. Private terminal only; output may contain secrets.
require 'json'
require 'net/http'
require 'uri'
require 'openssl'
STDOUT.set_encoding(Encoding::UTF_8)
OPERATIONS = JSON.parse(<<~'JSON')
{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
}
JSON
def required(name)
  value = ENV.fetch(name, '')
  raise 'configuration' if value.empty? || value.match?(/[\r\n]/)
  value
end
begin
  raise 'operation' unless ARGV.length == 1 && OPERATIONS.key?(ARGV[0])
  name = ARGV[0]; op = OPERATIONS.fetch(name)
  base = ENV.fetch('KDP_BASE_URL', 'https://licensing.kdpika.com/api/v1').sub(%r{/+$}, '')
  uri = URI.parse(base)
  local = uri.scheme == 'http' && ['127.0.0.1','localhost'].include?(uri.host) && ENV['KDP_ALLOW_LOOPBACK'] == '1'
  raise 'URL' unless uri.host && (uri.scheme == 'https' || local) && !uri.userinfo && !uri.query && !uri.fragment && uri.path == '/api/v1'
  target = URI.parse(base + op.fetch('path'))
  request = op.fetch('method') == 'GET' ? Net::HTTP::Get.new(target) : Net::HTTP::Post.new(target)
  request['Accept'] = 'application/json'; request['User-Agent'] = 'KDPikaDocsExample/1.0 Ruby'
  if op['auth'] == 'publicApp'
    request['X-App-ID'] = required('KDP_APP_ID'); request['X-Environment'] = 'SANDBOX'
  elsif op['auth'] == 'activation'
    request['Authorization'] = 'Bearer ' + required('KDP_ACTIVATION_TOKEN')
  end
  request['X-Installation-ID'] = required('KDP_INSTALLATION_ID') if name == 'validate'
  if op['method'] == 'POST'
    body = ENV.fetch('KDP_BODY_JSON', '{}'); raise 'JSON object' unless JSON.parse(body).is_a?(Hash)
    request['Content-Type'] = 'application/json'; request.body = body
  end
  http = Net::HTTP.new(target.host, target.port, nil)
  http.use_ssl = target.scheme == 'https'; http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.open_timeout = 5; http.read_timeout = 15
  response = http.request(request) # Net::HTTP does not follow redirects.
  result = JSON.parse(response.body)
  puts response.body
  unless response.code.to_i.between?(200,299) && result['success'] == true
    warn 'API rejection. Inspect error.code/request_id; reconcile mutations before retrying.'; exit 1
  end
rescue StandardError
  warn 'Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.'; exit 2
end
```

Run java -cp request.jar:gson.jar RequestKt activate.
### Kotlin
```kotlin
// Purpose: inspect one client-callable Sandbox operation; not an entitlement verifier.
// Requires Kotlin2.4.21/JVM17+, Gson2.14.0. Run compiled RequestKt with public-key.
// Expected: raw JSON; exit0 success/1 API rejection/2 setup or transport failure.
// KDP_* variables carry credentials/body; private terminal only, never application/CI logs.
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import com.google.gson.JsonParser
import com.google.gson.JsonPrimitive
import kotlin.system.exitProcess

val operationsJson = """
{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
}
""".trimIndent()
fun required(name: String): String = (System.getenv(name) ?: "").also {
    require(it.isNotEmpty() && !it.contains('\r') && !it.contains('\n')) { "Missing configuration." }
}
fun main(args: Array<String>) {
    try {
        val operations = JsonParser.parseString(operationsJson).asJsonObject
        require(args.size == 1 && operations.has(args[0]))
        val name = args[0]; val op = operations.getAsJsonObject(name)
        val base = (System.getenv("KDP_BASE_URL") ?: "https://licensing.kdpika.com/api/v1").trimEnd('/')
        val uri = URI.create(base)
        val local = uri.scheme == "http" && uri.host in listOf("localhost", "127.0.0.1") && System.getenv("KDP_ALLOW_LOOPBACK") == "1"
        require(uri.host != null && (uri.scheme == "https" || local) && uri.userInfo == null && uri.query == null && uri.fragment == null && uri.path == "/api/v1")
        val request = HttpRequest.newBuilder(URI.create(base + op["path"].asString)).timeout(Duration.ofSeconds(15))
            .header("Accept", "application/json").header("User-Agent", "KDPikaDocsExample/1.0 Kotlin")
        when (op["auth"].asString) {
            "publicApp" -> request.header("X-App-ID", required("KDP_APP_ID")).header("X-Environment", "SANDBOX")
            "activation" -> request.header("Authorization", "Bearer " + required("KDP_ACTIVATION_TOKEN"))
        }
        if (name == "validate") request.header("X-Installation-ID", required("KDP_INSTALLATION_ID"))
        if (op["method"].asString == "POST") {
            val body = System.getenv("KDP_BODY_JSON") ?: "{}"
            require(JsonParser.parseString(body).isJsonObject)
            request.header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString(body))
        } else request.GET()
        val client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build()
        val response = client.send(request.build(), HttpResponse.BodyHandlers.ofString())
        val result = JsonParser.parseString(response.body()).asJsonObject
        System.out.write(response.body().toByteArray(Charsets.UTF_8)); System.out.write(10)
        if (response.statusCode() !in 200..299 || result["success"] != JsonPrimitive(true)) {
            System.err.println("API rejection. Inspect error.code/request_id; reconcile mutations before retrying."); exitProcess(1)
        }
    } catch (error: Exception) {
        System.err.println("Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations."); exitProcess(2)
    }
}
```

Run ./request activate.
### Swift
```swift
// Purpose: inspect one client-callable Sandbox operation, not grant feature access.
// Requires Swift5.7+, Foundation; FoundationNetworking on Linux.
// Build: swiftc -parse-as-library request.swift -o request; run: ./request public-key
// Expected: JSON; exit0 success/1 API rejection/2 setup or transport failure.
// Credentials/body: KDP_* variables. Private terminal only; output may contain secrets.
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
let contract = #"""
{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
}
"""#
enum SetupError: Error {case invalid}
func required(_ name:String) throws -> String {
    let value=ProcessInfo.processInfo.environment[name] ?? ""
    guard !value.isEmpty && !value.contains("\r") && !value.contains("\n") else {throw SetupError.invalid};return value
}
final class NoRedirect: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
    func urlSession(_ session:URLSession,task:URLSessionTask,willPerformHTTPRedirection response:HTTPURLResponse,newRequest request:URLRequest,completionHandler:@escaping(URLRequest?)->Void){completionHandler(nil)}
}
@main struct Example {
    static func main() async {
        do {
            let env=ProcessInfo.processInfo.environment
            let operations=try JSONSerialization.jsonObject(with:Data(contract.utf8)) as! [String:[String:String]]
            guard CommandLine.arguments.count==2,let op=operations[CommandLine.arguments[1]] else {throw SetupError.invalid}
            let name=CommandLine.arguments[1]
            let base=(env["KDP_BASE_URL"] ?? "https://licensing.kdpika.com/api/v1").replacingOccurrences(of:"/+$",with:"",options:.regularExpression)
            guard let parts=URLComponents(string:base),let host=parts.host else {throw SetupError.invalid}
            let local=parts.scheme=="http" && ["localhost","127.0.0.1"].contains(host) && env["KDP_ALLOW_LOOPBACK"]=="1"
            guard (parts.scheme=="https" || local) && parts.user==nil && parts.password==nil && parts.query==nil && parts.fragment==nil && parts.path=="/api/v1",let url=URL(string:base+op["path"]!) else {throw SetupError.invalid}
            var request=URLRequest(url:url);request.httpMethod=op["method"];request.timeoutInterval=15
            request.setValue("application/json",forHTTPHeaderField:"Accept");request.setValue("KDPikaDocsExample/1.0 Swift",forHTTPHeaderField:"User-Agent")
            if op["auth"]=="publicApp" {request.setValue(try required("KDP_APP_ID"),forHTTPHeaderField:"X-App-ID");request.setValue("SANDBOX",forHTTPHeaderField:"X-Environment")}
            if op["auth"]=="activation" {request.setValue("Bearer "+(try required("KDP_ACTIVATION_TOKEN")),forHTTPHeaderField:"Authorization")}
            if name=="validate" {request.setValue(try required("KDP_INSTALLATION_ID"),forHTTPHeaderField:"X-Installation-ID")}
            if op["method"]=="POST" {
                let body=Data((env["KDP_BODY_JSON"] ?? "{}").utf8)
                guard try JSONSerialization.jsonObject(with:body) is [String:Any] else {throw SetupError.invalid}
                request.httpBody=body;request.setValue("application/json",forHTTPHeaderField:"Content-Type")
            }
            let session=URLSession(configuration:.ephemeral,delegate:NoRedirect(),delegateQueue:nil)
            defer {session.invalidateAndCancel()}
            let (raw,response)=try await session.data(for:request)
            guard let http=response as? HTTPURLResponse,let result=try JSONSerialization.jsonObject(with:raw) as? [String:Any],let text=String(data:raw,encoding:.utf8) else {throw SetupError.invalid}
            _ = text // Decoding above checks UTF-8 without reserializing JSON.
            FileHandle.standardOutput.write(raw);FileHandle.standardOutput.write(Data([10]))
            guard (200..<300).contains(http.statusCode),result["success"] as? Bool == true else {
                FileHandle.standardError.write(Data("API rejection. Inspect error.code/request_id; reconcile mutations before retrying.\n".utf8));exit(1)
            }
        } catch {
            FileHandle.standardError.write(Data("Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.\n".utf8));exit(2)
        }
    }
}
```

Run dart run request.dart activate.
### Dart
```dart
// Purpose: inspect one client-callable Sandbox operation, not grant feature access.
// Requires Dart3.7+ standard library. Run: dart run request.dart public-key
// Expected: JSON; exit0 success/1 API rejection/2 setup or transport failure.
// KDP_* variables carry credentials/body. Private terminal only; output can contain secrets.
import 'dart:convert';
import 'dart:io';

const contract = r'''{
  "public-key": {
    "method": "GET",
    "path": "/public-key",
    "auth": "public"
  },
  "activate": {
    "method": "POST",
    "path": "/licenses/activate",
    "auth": "publicApp"
  },
  "validate": {
    "method": "POST",
    "path": "/licenses/validate",
    "auth": "activation"
  },
  "deactivate": {
    "method": "POST",
    "path": "/licenses/deactivate",
    "auth": "activation"
  }
}''';
String required(String name) {
  final value = Platform.environment[name] ?? '';
  if (value.isEmpty || value.contains('\r') || value.contains('\n'))
    throw StateError('configuration');
  return value;
}

Future<void> main(List<String> args) async {
  stdout.encoding = utf8;
  final client = HttpClient()..connectionTimeout = const Duration(seconds: 5);
  try {
    final operations = jsonDecode(contract) as Map<String, dynamic>;
    if (args.length != 1 || !operations.containsKey(args[0]))
      throw StateError('operation');
    final name = args[0];
    final op = operations[name] as Map<String, dynamic>;
    final base =
        (Platform.environment['KDP_BASE_URL'] ??
                'https://licensing.kdpika.com/api/v1')
            .replaceFirst(RegExp(r'/+$'), '');
    final uri = Uri.parse(base);
    final local =
        uri.scheme == 'http' &&
        ['127.0.0.1', 'localhost'].contains(uri.host) &&
        Platform.environment['KDP_ALLOW_LOOPBACK'] == '1';
    if (uri.host.isEmpty ||
        (uri.scheme != 'https' && !local) ||
        uri.userInfo.isNotEmpty ||
        uri.hasQuery ||
        uri.hasFragment ||
        uri.path != '/api/v1')
      throw StateError('URL');
    final request = await client
        .openUrl(
          op['method'] as String,
          Uri.parse(base + (op['path'] as String)),
        )
        .timeout(const Duration(seconds: 15));
    request.followRedirects = false;
    request.headers.set('Accept', 'application/json');
    request.headers.set('User-Agent', 'KDPikaDocsExample/1.0 Dart');
    if (op['auth'] == 'publicApp') {
      request.headers.set('X-App-ID', required('KDP_APP_ID'));
      request.headers.set('X-Environment', 'SANDBOX');
    }
    if (op['auth'] == 'activation')
      request.headers.set(
        'Authorization',
        'Bearer ${required('KDP_ACTIVATION_TOKEN')}',
      );
    if (name == 'validate')
      request.headers.set('X-Installation-ID', required('KDP_INSTALLATION_ID'));
    if (op['method'] == 'POST') {
      final body = Platform.environment['KDP_BODY_JSON'] ?? '{}';
      if (jsonDecode(body) is! Map) throw StateError('JSON object');
      request.headers.set('Content-Type', 'application/json');
      request.add(utf8.encode(body));
    }
    final response = await request.close().timeout(const Duration(seconds: 15));
    final raw = await utf8.decoder
        .bind(response)
        .join()
        .timeout(const Duration(seconds: 15));
    final result = jsonDecode(raw) as Map<String, dynamic>;
    stdout.writeln(raw);
    if (response.statusCode < 200 ||
        response.statusCode >= 300 ||
        result['success'] != true) {
      stderr.writeln(
        'API rejection. Inspect error.code/request_id; reconcile mutations before retrying.',
      );
      exitCode = 1;
    }
  } catch (error) {
    stderr.writeln(
      'Request unavailable or configuration invalid. Check KDP_* settings/connectivity; do not blindly retry mutations.',
    );
    exitCode = 2;
  } finally {
    client.close(force: true);
  }
}
```

Run ./request-c activate.
### C
```c
/* C11 entry point. Build with client_http.c include, yyjson0.13.0 and libcurl7.76+.
 * Run request public-key; expected JSON, exit0 success/1 rejection/2 unavailable. */
#include "client_http.c"
int main(int argc,char **argv){return kdpika_example_main(argc,argv);}
```
```c
/* Purpose: shared native libcurl transport for C11 and C++17 Sandbox examples.
 * Requires libcurl7.76+, yyjson0.13.0. Build commands are in the sample README.
 * Run request public-key. JSON stdout; exit0 success/1 rejection/2 setup/transport.
 * Credentials/body: KDP_* environment. Private terminal only; output may contain secrets.
 * Transport inspection only: verify signed state and policy before authorizing access.
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <curl/curl.h>
#include "yyjson.h"
static const char *kdp_contract="{\"public-key\":{\"method\":\"GET\",\"path\":\"/public-key\",\"auth\":\"public\"},\"activate\":{\"method\":\"POST\",\"path\":\"/licenses/activate\",\"auth\":\"publicApp\"},\"validate\":{\"method\":\"POST\",\"path\":\"/licenses/validate\",\"auth\":\"activation\"},\"deactivate\":{\"method\":\"POST\",\"path\":\"/licenses/deactivate\",\"auth\":\"activation\"}}";
typedef struct {char *data;size_t size;} kdp_buffer;
static size_t kdp_receive(char *data,size_t size,size_t count,void *context){
    kdp_buffer *b=(kdp_buffer *)context;
    if(size && count>SIZE_MAX/size)return 0;
    size_t n=size*count;if(n>1048576-b->size)return 0;
    char *p=(char *)realloc(b->data,b->size+n+1);if(!p)return 0;
    b->data=p;memcpy(p+b->size,data,n);b->size+=n;p[b->size]=0;return n;
}
static const char *kdp_env(const char *name){const char *v=getenv(name);return v?v:"";}
static const char *kdp_required(const char *name){const char *v=kdp_env(name);return *v&&!strchr(v,'\r')&&!strchr(v,'\n')?v:NULL;}
static int kdp_header(struct curl_slist **headers,const char *name,const char *value){
    if(!value)return 0;size_t n=strlen(name)+strlen(value)+3;char *line=(char *)malloc(n);if(!line)return 0;
    snprintf(line,n,"%s: %s",name,value);struct curl_slist *next=curl_slist_append(*headers,line);free(line);
    if(!next)return 0;*headers=next;return 1;
}
static int kdpika_example_main(int argc,char **argv){
    int code=2;CURL *curl=NULL;CURLU *url=NULL;struct curl_slist *headers=NULL;
    yyjson_doc *ops=NULL,*bodydoc=NULL,*result=NULL;char *scheme=NULL,*host=NULL,*path=NULL,*part=NULL,*target=NULL;
    kdp_buffer buffer={NULL,0};const char *base=kdp_env("KDP_BASE_URL"),*body=kdp_env("KDP_BODY_JSON");
    const char *method=NULL,*route=NULL,*auth=NULL;yyjson_val *op=NULL;long status=0;
    if(argc!=2)goto cleanup;
    if(!*base)base="https://licensing.kdpika.com/api/v1";
    if(!*body)body="{}";
    ops=yyjson_read(kdp_contract,strlen(kdp_contract),0);if(!ops)goto cleanup;
    op=yyjson_obj_get(yyjson_doc_get_root(ops),argv[1]);if(!op)goto cleanup;
    method=yyjson_get_str(yyjson_obj_get(op,"method"));route=yyjson_get_str(yyjson_obj_get(op,"path"));auth=yyjson_get_str(yyjson_obj_get(op,"auth"));
    if(!method||!route||!auth||curl_global_init(CURL_GLOBAL_DEFAULT)!=0)goto cleanup;
    url=curl_url();if(!url||curl_url_set(url,CURLUPART_URL,base,0)!=CURLUE_OK)goto cleanup;
    if(curl_url_get(url,CURLUPART_SCHEME,&scheme,0)||curl_url_get(url,CURLUPART_HOST,&host,0)||curl_url_get(url,CURLUPART_PATH,&path,0))goto cleanup;
    if(strcmp(path,"/api/v1")!=0)goto cleanup;
    if(strcmp(scheme,"https")!=0 && !(strcmp(scheme,"http")==0 && (!strcmp(host,"localhost")||!strcmp(host,"127.0.0.1")) && !strcmp(kdp_env("KDP_ALLOW_LOOPBACK"),"1")))goto cleanup;
    {CURLUPart forbidden[]={CURLUPART_USER,CURLUPART_PASSWORD,CURLUPART_QUERY,CURLUPART_FRAGMENT};
    for(size_t i=0;i<sizeof(forbidden)/sizeof(forbidden[0]);i++){if(curl_url_get(url,forbidden[i],&part,0)==CURLUE_OK)goto cleanup;}}
    target=(char *)malloc(strlen(base)+strlen(route)+1);if(!target)goto cleanup;strcpy(target,base);strcat(target,route);
    if(!kdp_header(&headers,"Accept","application/json")||!kdp_header(&headers,"User-Agent","KDPikaDocsExample/1.0 Native"))goto cleanup;
    if(!strcmp(auth,"publicApp")&&(!kdp_header(&headers,"X-App-ID",kdp_required("KDP_APP_ID"))||!kdp_header(&headers,"X-Environment","SANDBOX")))goto cleanup;
    if(!strcmp(auth,"activation")){
        const char *token=kdp_required("KDP_ACTIVATION_TOKEN");if(!token)goto cleanup;
        char *bearer=(char *)malloc(strlen(token)+8);if(!bearer)goto cleanup;strcpy(bearer,"Bearer ");strcat(bearer,token);
        int ok=kdp_header(&headers,"Authorization",bearer);free(bearer);if(!ok)goto cleanup;
    }
    if(!strcmp(argv[1],"validate")&&!kdp_header(&headers,"X-Installation-ID",kdp_required("KDP_INSTALLATION_ID")))goto cleanup;
    curl=curl_easy_init();if(!curl)goto cleanup;
    curl_easy_setopt(curl,CURLOPT_URL,target);curl_easy_setopt(curl,CURLOPT_CUSTOMREQUEST,method);
    curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,0L);curl_easy_setopt(curl,CURLOPT_CONNECTTIMEOUT,5L);curl_easy_setopt(curl,CURLOPT_TIMEOUT,15L);
    curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,1L);curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,2L);
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,kdp_receive);curl_easy_setopt(curl,CURLOPT_WRITEDATA,&buffer);
    if(!strcmp(method,"POST")){
        bodydoc=yyjson_read(body,strlen(body),0);if(!bodydoc||!yyjson_is_obj(yyjson_doc_get_root(bodydoc)))goto cleanup;
        if(!kdp_header(&headers,"Content-Type","application/json"))goto cleanup;
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,body);
    }
    curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);if(curl_easy_perform(curl)!=CURLE_OK)goto cleanup;
    curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&status);
    result=yyjson_read(buffer.data,buffer.size,0);if(!result||!yyjson_is_obj(yyjson_doc_get_root(result)))goto cleanup;
    printf("%s\n",buffer.data);
    code=status>=200&&status<300&&yyjson_is_true(yyjson_obj_get(yyjson_doc_get_root(result),"success"))?0:1;
cleanup:
    if(code)fprintf(stderr,"Request rejected, unavailable or configuration invalid. Inspect JSON error.code/request_id when returned; do not blindly retry mutations.\n");
    if(curl)curl_easy_cleanup(curl);if(url)curl_url_cleanup(url);curl_slist_free_all(headers);
    curl_free(scheme);curl_free(host);curl_free(path);curl_free(part);free(target);free(buffer.data);
    yyjson_doc_free(ops);yyjson_doc_free(bodydoc);yyjson_doc_free(result);return code;
}
```

Run ./request-cpp activate.
### C++
```cpp
// C++17 entry point using the complete adjacent native transport.
// Requires yyjson0.13.0 and libcurl7.76+. Run request public-key; JSON/exit0,1,2.
#include "client_http.c"
int main(int argc,char **argv){return kdpika_example_main(argc,argv);}
```
```cpp
/* Purpose: shared native libcurl transport for C11 and C++17 Sandbox examples.
 * Requires libcurl7.76+, yyjson0.13.0. Build commands are in the sample README.
 * Run request public-key. JSON stdout; exit0 success/1 rejection/2 setup/transport.
 * Credentials/body: KDP_* environment. Private terminal only; output may contain secrets.
 * Transport inspection only: verify signed state and policy before authorizing access.
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <curl/curl.h>
#include "yyjson.h"
static const char *kdp_contract="{\"public-key\":{\"method\":\"GET\",\"path\":\"/public-key\",\"auth\":\"public\"},\"activate\":{\"method\":\"POST\",\"path\":\"/licenses/activate\",\"auth\":\"publicApp\"},\"validate\":{\"method\":\"POST\",\"path\":\"/licenses/validate\",\"auth\":\"activation\"},\"deactivate\":{\"method\":\"POST\",\"path\":\"/licenses/deactivate\",\"auth\":\"activation\"}}";
typedef struct {char *data;size_t size;} kdp_buffer;
static size_t kdp_receive(char *data,size_t size,size_t count,void *context){
    kdp_buffer *b=(kdp_buffer *)context;
    if(size && count>SIZE_MAX/size)return 0;
    size_t n=size*count;if(n>1048576-b->size)return 0;
    char *p=(char *)realloc(b->data,b->size+n+1);if(!p)return 0;
    b->data=p;memcpy(p+b->size,data,n);b->size+=n;p[b->size]=0;return n;
}
static const char *kdp_env(const char *name){const char *v=getenv(name);return v?v:"";}
static const char *kdp_required(const char *name){const char *v=kdp_env(name);return *v&&!strchr(v,'\r')&&!strchr(v,'\n')?v:NULL;}
static int kdp_header(struct curl_slist **headers,const char *name,const char *value){
    if(!value)return 0;size_t n=strlen(name)+strlen(value)+3;char *line=(char *)malloc(n);if(!line)return 0;
    snprintf(line,n,"%s: %s",name,value);struct curl_slist *next=curl_slist_append(*headers,line);free(line);
    if(!next)return 0;*headers=next;return 1;
}
static int kdpika_example_main(int argc,char **argv){
    int code=2;CURL *curl=NULL;CURLU *url=NULL;struct curl_slist *headers=NULL;
    yyjson_doc *ops=NULL,*bodydoc=NULL,*result=NULL;char *scheme=NULL,*host=NULL,*path=NULL,*part=NULL,*target=NULL;
    kdp_buffer buffer={NULL,0};const char *base=kdp_env("KDP_BASE_URL"),*body=kdp_env("KDP_BODY_JSON");
    const char *method=NULL,*route=NULL,*auth=NULL;yyjson_val *op=NULL;long status=0;
    if(argc!=2)goto cleanup;
    if(!*base)base="https://licensing.kdpika.com/api/v1";
    if(!*body)body="{}";
    ops=yyjson_read(kdp_contract,strlen(kdp_contract),0);if(!ops)goto cleanup;
    op=yyjson_obj_get(yyjson_doc_get_root(ops),argv[1]);if(!op)goto cleanup;
    method=yyjson_get_str(yyjson_obj_get(op,"method"));route=yyjson_get_str(yyjson_obj_get(op,"path"));auth=yyjson_get_str(yyjson_obj_get(op,"auth"));
    if(!method||!route||!auth||curl_global_init(CURL_GLOBAL_DEFAULT)!=0)goto cleanup;
    url=curl_url();if(!url||curl_url_set(url,CURLUPART_URL,base,0)!=CURLUE_OK)goto cleanup;
    if(curl_url_get(url,CURLUPART_SCHEME,&scheme,0)||curl_url_get(url,CURLUPART_HOST,&host,0)||curl_url_get(url,CURLUPART_PATH,&path,0))goto cleanup;
    if(strcmp(path,"/api/v1")!=0)goto cleanup;
    if(strcmp(scheme,"https")!=0 && !(strcmp(scheme,"http")==0 && (!strcmp(host,"localhost")||!strcmp(host,"127.0.0.1")) && !strcmp(kdp_env("KDP_ALLOW_LOOPBACK"),"1")))goto cleanup;
    {CURLUPart forbidden[]={CURLUPART_USER,CURLUPART_PASSWORD,CURLUPART_QUERY,CURLUPART_FRAGMENT};
    for(size_t i=0;i<sizeof(forbidden)/sizeof(forbidden[0]);i++){if(curl_url_get(url,forbidden[i],&part,0)==CURLUE_OK)goto cleanup;}}
    target=(char *)malloc(strlen(base)+strlen(route)+1);if(!target)goto cleanup;strcpy(target,base);strcat(target,route);
    if(!kdp_header(&headers,"Accept","application/json")||!kdp_header(&headers,"User-Agent","KDPikaDocsExample/1.0 Native"))goto cleanup;
    if(!strcmp(auth,"publicApp")&&(!kdp_header(&headers,"X-App-ID",kdp_required("KDP_APP_ID"))||!kdp_header(&headers,"X-Environment","SANDBOX")))goto cleanup;
    if(!strcmp(auth,"activation")){
        const char *token=kdp_required("KDP_ACTIVATION_TOKEN");if(!token)goto cleanup;
        char *bearer=(char *)malloc(strlen(token)+8);if(!bearer)goto cleanup;strcpy(bearer,"Bearer ");strcat(bearer,token);
        int ok=kdp_header(&headers,"Authorization",bearer);free(bearer);if(!ok)goto cleanup;
    }
    if(!strcmp(argv[1],"validate")&&!kdp_header(&headers,"X-Installation-ID",kdp_required("KDP_INSTALLATION_ID")))goto cleanup;
    curl=curl_easy_init();if(!curl)goto cleanup;
    curl_easy_setopt(curl,CURLOPT_URL,target);curl_easy_setopt(curl,CURLOPT_CUSTOMREQUEST,method);
    curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,0L);curl_easy_setopt(curl,CURLOPT_CONNECTTIMEOUT,5L);curl_easy_setopt(curl,CURLOPT_TIMEOUT,15L);
    curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,1L);curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,2L);
    curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,kdp_receive);curl_easy_setopt(curl,CURLOPT_WRITEDATA,&buffer);
    if(!strcmp(method,"POST")){
        bodydoc=yyjson_read(body,strlen(body),0);if(!bodydoc||!yyjson_is_obj(yyjson_doc_get_root(bodydoc)))goto cleanup;
        if(!kdp_header(&headers,"Content-Type","application/json"))goto cleanup;
        curl_easy_setopt(curl,CURLOPT_POSTFIELDS,body);
    }
    curl_easy_setopt(curl,CURLOPT_HTTPHEADER,headers);if(curl_easy_perform(curl)!=CURLE_OK)goto cleanup;
    curl_easy_getinfo(curl,CURLINFO_RESPONSE_CODE,&status);
    result=yyjson_read(buffer.data,buffer.size,0);if(!result||!yyjson_is_obj(yyjson_doc_get_root(result)))goto cleanup;
    printf("%s\n",buffer.data);
    code=status>=200&&status<300&&yyjson_is_true(yyjson_obj_get(yyjson_doc_get_root(result),"success"))?0:1;
cleanup:
    if(code)fprintf(stderr,"Request rejected, unavailable or configuration invalid. Inspect JSON error.code/request_id when returned; do not blindly retry mutations.\n");
    if(curl)curl_easy_cleanup(curl);if(url)curl_url_cleanup(url);curl_slist_free_all(headers);
    curl_free(scheme);curl_free(host);curl_free(path);curl_free(part);free(target);free(buffer.data);
    yyjson_doc_free(ops);yyjson_doc_free(bodydoc);yyjson_doc_free(result);return code;
}
```

## Expected result
A correctly authenticated eligible request returns the documented HTTP status and schema. Check the actual success/error result and [request IDs](/docs/v1/start/glossary#request-id); a successful transport or unsigned management response does not grant a feature.

## Common mistakes
- Mixing Public App IDs, internal product IDs and product-plan IDs.
- Assuming a mutation timeout means no work committed, or assuming Idempotency-Key protects every action.
- Logging raw responses that contain a newly issued license key or activation token.

## Security notes
Keep lmp_ credentials out of shipped desktop/browser code. Verify signed payload bytes and product/environment/installation/status/time/feature policy. The examples do not fix the documented idempotency, cache canonicalization or current-key-only rotation limitations.

## Troubleshooting
| Symptom | Cause | Action |
| --- | --- | --- |
| RATE_LIMITED (HTTP 429) | Bucket exhausted; wait for window reset; no licensing Retry-After header | After window; apply jitter |
| INVALID_REQUEST (HTTP 422) | Input constraints or entitlement/resource/renewal domain rejection | Correct input/plan; not blind retry |
| INVALID_LICENSE (HTTP 404) | Activation key/product/environment/customer email mismatch; SDK empty key local error has no HTTP | Correct details |
| LICENSE_EXPIRED (HTTP 403) | Elapsed expires_at before state check; or EXPIRED state; SDK local expiry has no HTTP | Renew eligible license |
| LICENSE_REVOKED (HTTP 403) | License REVOKED and no elapsed deadline taking precedence | Do not retry; contact developer |
| LICENSE_SUSPENDED (HTTP 403) | License SUSPENDED and no elapsed deadline taking precedence | Restore then reactivate |
| LICENSE_CANCELLED (HTTP 403) | License CANCELLED and no elapsed deadline taking precedence | Do not retry; new eligible license |
| LICENSE_PENDING (HTTP 403) | License PENDING and no elapsed deadline taking precedence | Wait for authorized activation |
| APP_VERSION_NOT_SUPPORTED (HTTP 403) | Nonempty activation app_version outside configured range | Use supported version |
| DEVICE_LIMIT_REACHED (HTTP 409) | New/inactive installation while active seats >= license.max_devices | Deactivate/reset a seat |
| ACTIVATION_LIMIT_REACHED (HTTP 409) | New/inactive installation while activation_count >= max_activations | Developer adjusts policy; reset-devices does not zero count |
| INTERNAL_ERROR (HTTP 500) | Uncaught exception at global boundary | Safe retry only for idempotent operation; preserve request_id |

## Next steps
Read [idempotency](/docs/v1/api/idempotency) and [signed responses](/docs/v1/security/signed-responses) before integrating a purchase-to-license workflow.

## Related
- [API conventions](/docs/v1/api/conventions)
- [Errors](/docs/v1/api/errors)
- [License lifecycle](/docs/v1/start/license-lifecycle)
