kubernetes.client.exceptions.ApiException: (401) Reason: Unauthorized
Fixes the Kubernetes Python client reaching the API server but getting rejected. Use when calls raise ApiException 401. Not for connection errors or 403 Forbidden.
TL;DR: You reached the API server but your credentials are invalid or expired. Refresh them: re-run your cloud provider's get-credentials command (or re-authenticate), which rewrites the token/certs in your kubeconfig.
kubernetes.client.exceptions.ApiException: (401)
Reason: UnauthorizedFix it
- Confirm kubectl has the same problem: kubectl get pods. Expected: the same 401, proving it is credentials, not your code.
- Refresh credentials for your platform (examples: gcloud container clusters get-credentials [name], az aks get-credentials, aws eks update-kubeconfig). Expected: kubeconfig rewritten with fresh auth.
- Retry kubectl get pods. Expected: pods list.
- Retry your Python code. Expected: ApiException gone.
When this applies
- ApiException with status 401 on any call.
- kubectl fails the same way.
When it doesn't
- kubectl works but Python fails: the client reads a different kubeconfig; set KUBECONFIG.
- The error is 403 Forbidden: auth is fine; RBAC denies the action.
Compatibility
- kubernetes client any version.
Why it happens
Tokens and client certificates expire. Cloud CLIs write short-lived tokens into kubeconfig, so a config that worked last week 401s today until refreshed.
Edge cases
- ServiceAccount tokens mounted in pods expire too; restart the pod to remount.
- Multiple contexts: make sure kubectl config current-context is the cluster you think.
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.