kubernetes
python
kubernetes api
pods
labels

How can I get pods by label, using the python kubernetes api?

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

Introduction

In Kubernetes, labels are the normal way to select subsets of pods. The Python client exposes the same selector model that kubectl uses, so querying pods by label is mostly a matter of loading the right cluster credentials and passing a label_selector string to the list call. The part that usually trips people up is scope: whether to query one namespace or the whole cluster.

Load Configuration Correctly

The Python Kubernetes client needs either local kubeconfig credentials or in-cluster credentials.

python
1from kubernetes import client, config
2
3# For local scripts
4config.load_kube_config()
5
6# For code running inside the cluster, use this instead:
7# config.load_incluster_config()
8
9v1 = client.CoreV1Api()

If a script works on your laptop but fails in a pod, the first thing to check is whether you loaded the correct config source.

List Pods by Label in One Namespace

Use list_namespaced_pod and pass a Kubernetes label selector string.

python
1pods = v1.list_namespaced_pod(
2    namespace="default",
3    label_selector="app=web"
4)
5
6for pod in pods.items:
7    print(pod.metadata.name, pod.status.phase)

The selector syntax is the same style used by kubectl -l.

Useful examples include:

  • 'app=web'
  • 'env!=dev'
  • 'tier in (frontend,backend)'
  • 'release'

Query All Namespaces When You Really Need To

If the search must span the whole cluster, use list_pod_for_all_namespaces.

python
1pods = v1.list_pod_for_all_namespaces(label_selector="tier=backend")
2
3for pod in pods.items:
4    print(f"{pod.metadata.namespace}/{pod.metadata.name}")

This is more expensive on large clusters, so it is better to stay namespace-scoped whenever possible.

Build Useful Summaries

Most automation wants more than pod names. A small helper keeps the code readable.

python
1def summarize_pod(pod):
2    return {
3        "name": pod.metadata.name,
4        "namespace": pod.metadata.namespace,
5        "phase": pod.status.phase,
6        "node": pod.spec.node_name,
7        "images": [c.image for c in pod.spec.containers],
8    }
9
10for pod in pods.items:
11    print(summarize_pod(pod))

This is handy for audits, rollout checks, and operational dashboards.

Watch Matching Pods Over Time

If you want updates rather than a one-time list, use the watch API with the same selector.

python
1from kubernetes import watch
2
3w = watch.Watch()
4for event in w.stream(
5    v1.list_namespaced_pod,
6    namespace="default",
7    label_selector="app=web",
8    timeout_seconds=30,
9):
10    print(event["type"], event["object"].metadata.name)

That is useful for scripts that react to pod creation, deletion, or restart behavior.

Remember RBAC and Pagination

Two production concerns show up quickly:

  • RBAC permissions for list and watch
  • large result sets that should be paged

If you get authorization errors in-cluster, inspect the service account’s role bindings. If the cluster is large, use limit and the continue token instead of loading everything at once.

python
1response = v1.list_pod_for_all_namespaces(
2    label_selector="app=web",
3    limit=200,
4)
5print(len(response.items))

That keeps memory use predictable for broad queries.

Match kubectl Behavior When Debugging

If a selector works in kubectl but not in your script, compare the exact namespace and selector string first. A quick sanity check is to run the equivalent command line:

bash
kubectl get pods -n default -l app=web

If kubectl returns pods and the Python client does not, the issue is usually configuration loading, namespace mismatch, or RBAC rather than the selector itself.

Common Pitfalls

  • Loading local kubeconfig inside a pod instead of using in-cluster config.
  • Using the wrong selector syntax and assuming no pods matched.
  • Querying all namespaces when a single namespace would be faster and safer.
  • Forgetting that the service account needs list and possibly watch permissions.

Summary

  • Use label_selector with the Kubernetes Python client list methods.
  • Pick namespaced or all-namespace queries based on the real scope you need.
  • Reuse normal Kubernetes selector syntax such as app=web.
  • Add watch support, pagination, and RBAC checks for production scripts.
  • Keep the result formatting separate from the API call so automation stays readable.

Related reading
Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design

All Rights Reserved.