rohitg00/ai-engineering-from-scratch · error · ValueError

api_key must be non-empty

Error message

api_key must be non-empty

What it means

Raised in AnthropicMessagesHTTPTransport.__init__ when the api_key argument is empty or whitespace-only. The transport must never send an unauthenticated request, so it refuses construction rather than deferring failure to the first HTTP call.

Solutions

  1. Supply the real key from an environment variable (e.g. os.environ['ANTHROPIC_API_KEY'])
  2. Fail fast at app startup when the key variable is unset instead of constructing the transport
  3. Use a dummy non-empty key in tests via dependency-injected fakes rather than blank strings
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at certifications/claude/lessons/30-developer-application-capstone/code/main.py:44 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/62cd1b79373d2fe8. Report an issue: GitHub.

Appendix: source

Thrown at certifications/claude/lessons/30-developer-application-capstone/code/main.py:44

class MessagesTransport(Protocol):
    """Small dependency-injection boundary for a Messages API call."""

    def create_message(self, payload: dict[str, Any]) -> dict[str, Any]: ...


class AnthropicMessagesHTTPTransport:
    """Opt-in stdlib HTTP transport that never logs or persists its API key."""

    def __init__(
        self,
        api_key: str,
        endpoint: str = ANTHROPIC_MESSAGES_URL,
        timeout_seconds: float = 30.0,
        opener: Callable[..., Any] = urllib.request.urlopen,
    ) -> None:
        if not api_key.strip():
            raise ValueError("api_key must be non-empty")
        self._api_key = api_key
        self.endpoint = endpoint
        self.timeout_seconds = timeout_seconds
        self._opener = opener

    def create_message(self, payload: dict[str, Any]) -> dict[str, Any]:
        body = json.dumps(payload).encode("utf-8")
        request = urllib.request.Request(
            self.endpoint,
            data=body,
            method="POST",
            headers={
                "content-type": "application/json",
                "anthropic-version": ANTHROPIC_VERSION,
                "x-api-key": self._api_key,
            },
        )
        try:

View on GitHub (pinned to 39ea8a1c6d)