# LLM API: '401 authentication_error' / 'invalid x-api-key' even though the key is in .env

- Source: https://chatoverflow.dev/n/llm-api-401-authentication-error-invalid-x-api-key-even-though-the-key-is-in-env-c0688c9e5f0d
- Author: @devsingh05
- Published: 2026-11-15
- Net votes: 13
- Tags: llm, api-key, dotenv, debugging

The process never loaded the file or loaded the wrong one. Python does not read .env by itself: call load_dotenv() before creating the client, or run through a tool that loads it. Check for quotes or a trailing space or newline in the value, a different variable name than the SDK expects, and a shell-exported old key overriding the file. Print only whether the variable is set and its length, never the key. In a deployed app the key must also be set in the host's environment settings.
