Kubernetes
Python
API
Pods
Namespace

Kubernetes How do I get all pods in a namespace using the python api?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The Kubernetes Python client can list every pod in a namespace with a single API call, but the setup differs depending on where the code runs. Local scripts usually load a kubeconfig file, while code running inside the cluster uses the pod service account. Once configuration is loaded, list_namespaced_pod is the standard method.

Load Client Configuration Correctly

Before you can query pods, the Python client must know how to reach the API server and how to authenticate.

For local development:

python
1from kubernetes import client, config
2
3config.load_kube_config()
4v1 = client.CoreV1Api()

For code running inside a Kubernetes pod:

python
1from kubernetes import client, config
2
3config.load_incluster_config()
4v1 = client.CoreV1Api()

Do not use both in the same execution path unless you have a very deliberate fallback strategy. In most applications, one environment is known ahead of time.

List All Pods in a Namespace

The direct call is list_namespaced_pod.

python
1from kubernetes import client, config
2
3config.load_kube_config()
4v1 = client.CoreV1Api()
5
6namespace = "default"
7pods = v1.list_namespaced_pod(namespace=namespace)
8
9for pod in pods.items:
10    print(pod.metadata.name)

The result is a V1PodList. The actual pod objects are stored in pods.items.

If you want a little more context:

python
1for pod in pods.items:
2    print(
3        pod.metadata.name,
4        pod.status.phase,
5        pod.spec.node_name
6    )

That is often enough for scripts that inventory workloads or check pod state.

Filter with Selectors Instead of Post-Processing

If the namespace is large, pull only what you need. The API supports both label selectors and field selectors.

Label selector example:

python
1pods = v1.list_namespaced_pod(
2    namespace="default",
3    label_selector="app=api"
4)

Field selector example for only running pods:

python
1pods = v1.list_namespaced_pod(
2    namespace="default",
3    field_selector="status.phase=Running"
4)

This is better than fetching all pods and filtering in Python because the API server does part of the work for you.

Handle API Errors Explicitly

Production code should not assume the call always succeeds. Namespaces may not exist, RBAC may block access, or credentials may be invalid.

python
1from kubernetes import client, config
2from kubernetes.client.exceptions import ApiException
3
4config.load_kube_config()
5v1 = client.CoreV1Api()
6
7try:
8    pods = v1.list_namespaced_pod(namespace="default")
9    print(f"Found {len(pods.items)} pods")
10except ApiException as exc:
11    print(f"API call failed: {exc.status} {exc.reason}")

Typical meanings:

  • '403 usually means an RBAC problem'
  • '404 usually means the namespace name is wrong'
  • connection or TLS errors usually mean kubeconfig or cluster access is broken

Large Namespaces May Need Pagination

For very large namespaces, the response may be paginated. The client exposes this with limit and _continue.

python
1from kubernetes import client, config
2
3config.load_kube_config()
4v1 = client.CoreV1Api()
5
6token = None
7
8while True:
9    resp = v1.list_namespaced_pod(
10        namespace="default",
11        limit=200,
12        _continue=token
13    )
14
15    for pod in resp.items:
16        print(pod.metadata.name)
17
18    token = resp.metadata._continue
19    if not token:
20        break

You can ignore this in small clusters, but it matters in shared production namespaces with hundreds or thousands of pods.

Convert Pod Objects Into Simpler Data

If the result is being passed to other code, normalize it into dictionaries or dataclasses instead of passing client objects everywhere.

python
1pod_rows = []
2
3for pod in pods.items:
4    pod_rows.append(
5        {
6            "name": pod.metadata.name,
7            "namespace": pod.metadata.namespace,
8            "phase": pod.status.phase,
9            "node": pod.spec.node_name,
10        }
11    )
12
13print(pod_rows)

That makes downstream logging, JSON output, and reporting much easier.

Common Pitfalls

  • Using load_kube_config() inside a pod instead of load_incluster_config().
  • Forgetting RBAC permissions for the service account.
  • Pulling every pod and filtering client-side when selectors would do the job.
  • Ignoring pagination in large namespaces.
  • Treating pods.items as plain dictionaries instead of typed client objects.

Summary

  • Use CoreV1Api.list_namespaced_pod to get all pods in a namespace.
  • Load configuration from kubeconfig locally or in-cluster config inside Kubernetes.
  • Use label and field selectors when you only need a subset of pods.
  • Catch ApiException so permission and connectivity failures are visible.
  • Normalize results if the pod list is feeding automation or reports.

Course illustration
Course illustration

All Rights Reserved.