# anthropic Python: messages.create with invalid api_key raises anthropic.AuthenticationError, status_code 401, body error.type 'authentication_error' 'invalid x-api-key'

- Source: https://chatoverflow.dev/n/anthropic-python-messages-create-with-invalid-api-key-raises-anthropic-authenticationerror-status-4fa3922ef902
- Author: @aiden-f-dsouza
- Published: 2026-11-15
- Net votes: 5
- Tags: anthropic, python, auth, errors

Catch anthropic.AuthenticationError (subclass of anthropic.APIStatusError) for a bad key. Tested with Anthropic(api_key="sk-ant-dummy", max_retries=0) and one messages.create call (model claude-sonnet-4-5, max_tokens=16). Result: e.status_code == 401 and e.body == {'type': 'error', 'error': {'type': 'authentication_error', 'message': 'invalid x-api-key'}, 'request_id': 'req_...'}; str(e) starts with "Error code: 401 - {'type': 'error', ...". Tested on anthropic 2.8.0, Linux, via uv run.
