Exploring the API with kubectl

Intermediate · 5 min

Find any resource, field or permission from the terminal: api-resources, explain, verbose logging, raw requests, custom columns, JSONPath and auth can-i.

Before thiskubectl, kubeconfig and contextsThe Kubernetes API and object model

CNCF [Cloud Native Computing Foundation] · 5 min

Exploring the API with kubectl

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CNCF [Cloud Native Computing Foundation]Report a problem with this video
Not started
Set this lesson's status

What you'll learn

  • The cluster documents itself. kubectl api-resources lists every type it serves, with short names, group, scope and verbs, including CRDs you installed.
  • kubectl explain reads the server's OpenAPI schema, so it shows the exact fields and docs for your cluster's version. --recursive prints the whole tree.
  • -v=6 shows each HTTP request kubectl makes and -v=8 shows headers and bodies. kubectl get --raw sends a request to any API path.
  • custom-columns, JSONPath, --field-selector and --sort-by turn kubectl get into a query tool, without jq.
  • kubectl auth can-i, with --list and --as, answers what an identity may do before you find out the hard way.

The docs are in the cluster

You are writing a manifest and cannot remember whether it is maxSurge or maxSurgePods, which API group CronJobs live in, or whether your CI ServiceAccount may delete Secrets. The web docs describe the latest release, not necessarily yours, and they know nothing about the CRDs your platform team installed last month.

The cluster, on the other hand, knows exactly what it serves. Every API server publishes discovery documents listing its types and an OpenAPI schema describing every field. kubectl can read all of it. Learning a handful of commands turns the terminal into the most accurate reference you have.

What types exist: api-resources

$ kubectl api-resources -o wide
NAME         SHORTNAMES  APIVERSION              NAMESPACED  KIND        VERBS                                                        CATEGORIES
pods         po          v1                      true        Pod         create,delete,deletecollection,get,list,patch,update,watch   all
deployments  deploy      apps/v1                 true        Deployment  create,delete,deletecollection,get,list,patch,update,watch   all
cronjobs     cj          batch/v1                true        CronJob     create,delete,deletecollection,get,list,patch,update,watch   all
leases                   coordination.k8s.io/v1  true        Lease       create,delete,deletecollection,get,list,patch,update,watch
events       ev          v1                      true        Event       create,delete,deletecollection,get,list,patch,update,watch
events       ev          events.k8s.io/v1        true        Event       create,delete,deletecollection,get,list,patch,update,watch

(Lines picked from the full list.) Each row gives the plural name, short names you can type instead (po, deploy, cj), the group and version, whether it is namespaced, the kind, and the verbs it supports. CATEGORIES explains what kubectl get all means: only resources in the all category, which is why it never shows ConfigMaps or Secrets. Note the two events rows: the same kind served by two groups.

Filters make it a query: kubectl api-resources --namespaced=false lists cluster-scoped types, and --verbs=list only those you can list. Installed CRDs appear here too, which makes this the first command to run on an unfamiliar cluster.

What fields exist: explain

kubectl explain fetches the OpenAPI schema from your server and prints the documentation for any field path:

$ kubectl explain deployment.spec.strategy.rollingUpdate.maxSurge
GROUP:      apps
KIND:       Deployment
VERSION:    v1

FIELD: maxSurge <IntOrString>

DESCRIPTION:
    The maximum number of pods that can be scheduled above the desired number of
    pods. Value can be an absolute number (ex: 5) or a percentage of desired
    pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is
    calculated from percentage by rounding up. Defaults to 25%. ...

--recursive prints the entire field tree below a path, with types and -required- markers:

$ kubectl explain pod.spec.containers --recursive
FIELDS:
  args	<[]string>
  command	<[]string>
  env	<[]EnvVar>
    name	<string> -required-
    value	<string>
    valueFrom	<EnvVarSource>
      configMapKeyRef	<ConfigMapKeySelector>
...

Because it reads the live schema, explain is version-correct by construction, and it works for CRDs whose authors wrote a structural schema. --api-version picks a specific version when a type is served in several.

What kubectl actually sends: verbosity and raw requests

kubectl hides HTTP, but it will show it to you. -v=6 logs each request:

$ kubectl get deploy shop -v=6
... "Response" verb="GET" url="https://127.0.0.1:6441/apis/apps/v1/namespaces/default/deployments/shop" status="200 OK" milliseconds=3

-v=8 adds headers and bodies, and reveals a detail: for get, kubectl sends Accept: application/json;as=Table;v=v1;g=meta.k8s.io. The server formats the table columns, which is how CRDs get their own kubectl get columns without any kubectl plugin.

To make requests yourself, kubectl get --raw sends a GET to any path with your kubeconfig’s credentials:

kubectl get --raw /apis/apps/v1 | jq '.resources[].name'
kubectl get --raw '/readyz?verbose'
kubectl get --raw /openapi/v3        # index of per-group OpenAPI documents

kubectl proxy goes further, opening a local HTTP port that forwards to the API server with your credentials attached, so curl localhost:8001/api/v1/namespaces just works. It is handy for exploring and for scripts in languages without a Kubernetes client.

Asking precise questions: output formats

kubectl get is more than a list. A few options turn it into a query language:

$ kubectl get pods -o custom-columns='NAME:.metadata.name,NODE:.spec.nodeName,PHASE:.status.phase,IMAGE:.spec.containers[0].image'
NAME                   NODE     PHASE     IMAGE
api-5f8476ddb6-dj789   fake-1   Pending   nginx:1.29

(One row of several shown.)

$ kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.conditions[?(@.type=="Ready")].status}{"\n"}{end}'
fake-1	Unknown
node-a	Unknown
node-b	Unknown

JSONPath’s range loops over items and the [?(@.type=="Ready")] filter picks one condition from a list. (Those lab nodes show Unknown because nothing was renewing their heartbeats, the behaviour from the nodes lesson.) Add --field-selector status.phase=Pending to filter on the server, --sort-by=.metadata.creationTimestamp to order, and -o name for script-friendly output. -l selects by label, which the labels lesson covers.

What you may do: auth can-i

The API also answers permission questions. kubectl auth can-i delete secrets -n payments returns yes or no. With --list it prints everything an identity may do, and --as lets an admin ask on someone else’s behalf:

$ kubectl auth can-i --list --as=system:serviceaccount:payments:ci -n payments
Resources                    Non-Resource URLs   Resource Names   Verbs
leases.coordination.k8s.io   []                  []               [create delete deletecollection get list patch update watch]
configmaps                   []                  []               [create delete deletecollection patch update get list watch]
pods                         []                  []               [create delete deletecollection patch update get list watch]
...

That is the ci ServiceAccount from the kubeconfig lesson, bound to the built-in edit role.

About the video

The embed is Mauricio Salatino’s KubeCon lightning talk “Boosting Your kubectl Productivity” (CNCF, November 2019, five minutes). Salatino was at Learnk8s, whose long guide of the same name is linked in deeper. The abstract promises ways to use kubectl more efficiently and more enjoyably, and the guide it comes from covers explain, api-resources, custom columns, JSONPath and shell completion. It was judged from that abstract and the guide; there are no chapters. It is short and predates kubectl events and kuberc, so the lesson does the detailed work. English was judged from the “English (US) original” audio track. The VarJosh CKA video in deeper is the long version for JSONPath, and opens with what happens under the hood of kubectl get pods.

What was run: every command above, api-resources, explain, -v=6 and -v=8, --raw, the custom columns, JSONPath and auth can-i --list, ran against a local v1.37.3 API server with kubectl v1.37.3, on 2026-11-28. kubectl proxy was described from the docs and not run.

Where this fits

You can now find and read anything in the API. The next group looks hard at the objects that run your code, starting with the smallest: Pods in depth.

Check yourself

  1. 01You need to write a PodDisruptionBudget but don't remember its API group or fields. Which two commands get you there without a browser?

    kubectl api-resources | grep -i disruption shows poddisruptionbudgets in policy/v1, short name pdb. Then kubectl explain pdb.spec, or explain pdb --recursive, lists the fields with their documentation, straight from your cluster's schema.

  2. 02Why might kubectl explain disagree with a blog post about a field?

    explain reads the OpenAPI schema served by your cluster, so it reflects that exact version and any CRDs installed. The blog may describe another release, a feature gate you don't have, or a field that has since been added or removed.

  3. 03How can you see which API path kubectl get deploy shop actually calls?

    Add -v=6. kubectl logs each request, for example GET https://.../apis/apps/v1/namespaces/default/deployments/shop with its status and latency. -v=8 adds headers, showing that kubectl asks the server for a Table so the server formats the columns.

  4. 04How do you list each node with its Ready status using only kubectl?

    kubectl get nodes -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.conditions[?(@.type=="Ready")].status}{"\n"}{end}'. The filter expression picks the Ready condition out of the conditions list.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark