{"record":{"id":"98f6c8d8329217ee","repo":"calesthio/OpenMontage","slug":"kling-api-key-is-not-set-configure-kling-api-key","errorCode":null,"errorMessage":"KLING_API_KEY is not set. Configure KLING_API_KEY for official Kling API access.","messagePattern":"KLING_API_KEY is not set\\. Configure KLING_API_KEY for official Kling API access\\.","errorType":"exception","errorClass":"KlingAPIError","httpStatus":401,"severity":"critical","filePath":"tools/_kling/client.py","lineNumber":43,"sourceCode":"class KlingClient:\n    \"\"\"Small synchronous client for the official Kling API.\"\"\"\n\n    def __init__(\n        self,\n        api_key: str | None = None,\n        base_url: str | None = None,\n        session: Any | None = None,\n        max_retries: int = 2,\n    ) -> None:\n        self.api_key = api_key if api_key is not None else os.environ.get(\"KLING_API_KEY\")\n        self.base_url = (base_url or os.environ.get(\"KLING_API_BASE_URL\") or DEFAULT_API_BASE_URL).rstrip(\"/\")\n        self.session = session or requests.Session()\n        self.max_retries = max_retries\n\n    @property\n    def headers(self) -> dict[str, str]:\n        if not self.api_key:\n            raise KlingAPIError(\n                \"KLING_API_KEY is not set. Configure KLING_API_KEY for official Kling API access.\",\n                http_status=401,\n            )\n        return {\n            \"Authorization\": f\"Bearer {self.api_key}\",\n            \"Accept\": \"application/json\",\n            \"Content-Type\": \"application/json\",\n        }\n\n    def post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:\n        return self._request(\"post\", path, json=payload)\n\n    def get(self, path: str, params: dict[str, Any] | None = None) -> dict[str, Any]:\n        return self._request(\"get\", path, params=params)\n\n    def download(self, url: str, output_path: Path, timeout: int = 180) -> Path:\n        output_path.parent.mkdir(parents=True, exist_ok=True)\n        response = self.session.get(url, timeout=timeout)","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/calesthio/OpenMontage/blob/95e1c3d0ab93482159818560f6a8c8e866b9139f/tools/_kling/client.py#L25-L61","documentation":"KlingAPIError (with http_status=401) raised lazily by the client's headers property whenever an authenticated request is attempted and self.api_key is falsy. The key is read once at construction from the KLING_API_KEY environment variable; if it wasn't set and no explicit api_key was passed, every request fails here with an actionable message naming the exact env var.","triggerScenarios":"Constructing KlingClient in a shell/process where KLING_API_KEY was never exported; CI runners or agent sessions missing the secret; .env file present but not loaded; key passed as empty string (also falsy); subprocess spawning the client without inheriting the environment.","commonSituations":"New machine/container without the env var; direnv/pyenv activation missed; secret stored in .env but the process doesn't auto-load it; the key name typo'd (KLING_APIKEY / KLING_KEY).","solutions":["Export KLING_API_KEY in the environment where the process runs: export KLING_API_KEY=... (or add to .env + load it)","Pass api_key explicitly to the KlingClient constructor when managing secrets programmatically (e.g. from a secrets manager)","Verify with: python -c \"import os; print(bool(os.environ.get('KLING_API_KEY')))\"","In CI, add KLING_API_KEY to the runner's secret store / masked variables"],"exampleFix":"# before\nclient = KlingClient()  # env var not set -> 401 KlingAPIError on first request\n\n# after\nclient = KlingClient(api_key=os.environ[\"KLING_API_KEY\"])  # fail fast at construction","handlingStrategy":"validation","validationCode":"import os\nif not os.environ.get(\"KLING_API_KEY\"):\n    raise SystemExit(\"KLING_API_KEY not set — export it before running Kling tools\")\nclient = KlingClient()","typeGuard":"def kling_credentials_present() -> bool:\n    return bool(os.environ.get(\"KLING_API_KEY\"))","tryCatchPattern":"try:\n    client.get(\"/v1/models/test\")  # any cheap authenticated call\nexcept KlingAPIError as e:\n    if getattr(e, \"http_status\", None) == 401 and \"KLING_API_KEY\" in str(e):\n        raise SystemExit(\"configure KLING_API_KEY (env var or KlingClient(api_key=...))\")\n    raise","preventionTips":["Fail fast at process start, not on first request: assert the env var before constructing the client","Load .env explicitly (python-dotenv) rather than assuming auto-load","Add the secret to CI masked variables; pass api_key from a secrets manager in production"],"tags":["kling","auth","env-vars","credentials"],"backgroundTag":null,"analyzedSha":"95e1c3d0ab93482159818560f6a8c8e866b9139f","analyzedAt":"2026-08-15T06:31:20.014Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}