Significant-Gravitas/AutoGPT · error · HTTPException

No API key in request

Error message

No API key in request

What it means

APIKeyAuthenticator.__call__ raises HTTPException with status_if_missing (default HTTP_401_UNAUTHORIZED, configurable per authenticator instance — e.g. 403 where 401 would break browser flows) when the configured header (e.g. X-API-Key) is absent from the request. The underlying fastapi.security APIKeyHeader was constructed with auto_error=False so this custom, configurable-status error is raised instead. This is the 'missing header' branch, distinct from the 'present but invalid' branch that uses message_if_invalid.

Source

Thrown at autogpt_platform/backend/backend/api/utils/api_key_auth.py:86

            Callable[[str], Any] | Callable[[str], Awaitable[Any]]
        ] = None,
        status_if_missing: int = HTTP_401_UNAUTHORIZED,
        message_if_invalid: str = "Invalid API key",
    ):
        super().__init__(
            name=header_name,
            scheme_name=f"{__class__.__name__}-{header_name}",
            auto_error=False,
        )
        self.expected_token = expected_token
        self.custom_validator = validator
        self.status_if_missing = status_if_missing
        self.message_if_invalid = message_if_invalid

    async def __call__(self, request: Request) -> Any:
        api_key = await super().__call__(request)
        if api_key is None:
            raise HTTPException(
                status_code=self.status_if_missing, detail="No API key in request"
            )

        # Use custom validation if provided, otherwise use default equality check
        validator = self.custom_validator or self.default_validator
        result = (
            await validator(api_key)
            if inspect.iscoroutinefunction(validator)
            else validator(api_key)
        )

        if not result:
            raise HTTPException(
                status_code=self.status_if_missing, detail=self.message_if_invalid
            )

        # Store validation result in request state if it's not just a boolean
        if result is not True:

View on GitHub (pinned to 9c8bb5550f)

Solutions

  1. Send the exact header name the authenticator was constructed with (see its header_name), e.g. `X-API-Key: <key>` on every request.
  2. Verify intermediaries (proxies, API gateways, fetch wrappers) forward custom headers and handle CORS preflight for them.
  3. Distinguish this from an invalid key: missing header → 'No API key in request'; wrong value → the authenticator's message_if_invalid.
  4. Centralize header injection in one HTTP client wrapper instead of per-call.

Example fix

# before
resp = requests.get(url, headers={'Authorization': f'Bearer {key}'})
# after
resp = requests.get(url, headers={'X-API-Key': key})
Defensive patterns

Strategy: validation

Validate before calling

function withApiKey(headers: Record<string, string> = {}): Record<string, string> {
  if (!API_KEY) throw new Error('API key not configured');
  return { ...headers, 'X-API-Key': API_KEY };
}
await fetch(url, { headers: withApiKey() });

Type guard

function hasApiKeyHeader(headers: Headers, name = 'X-API-Key'): boolean {
  return Boolean(headers.get(name));
}

Try / catch

try {
  return await client.get(path, { headers: { 'X-API-Key': apiKey } });
} catch (e) {
  if (e.status === 401 && e.detail === 'No API key in request') {
    throw new Error(`Missing ${HEADER_NAME} header — check client config`);
  }
  throw e;
}

Prevention

When it happens

Trigger: Calling any endpoint protected by an APIKeyAuthenticator without the expected header — e.g. missing X-API-Key on external-api routes, or a webhook adapter route that requires a token header that wasn't sent.

Common situations: Clients sending the key as a Bearer Authorization header instead of the custom header name; typos in the header name (x-api-key casing is fine, but 'apikey' is not); proxies (nginx, CORS preflight handling) stripping custom headers; integration code that only sets the header on some requests.

Related errors


AI-assisted analysis of Significant-Gravitas/AutoGPT@9c8bb5550f (2026-08-14). Data as JSON: /api/errors/480c0a1024896b39. Report an issue: GitHub.