Skip to content

kubex-core

Auto-generated reference for the kubex_core package — the shared base models used by both kubex and the generated kubex-k8s-* packages.

Base models

kubex_core.models.base

BaseK8sModel

Bases: BaseModel

Base for every Kubernetes model.

Fields are snake_case in Python and camelCase on the wire. Unknown fields (e.g. ones added by a newer API server than the model was generated for) are kept under their original wire keys and serialized back, so a get -> modify -> replace round-trip does not delete server data.

kubex_core.models.base_entity

BaseEntity

Bases: BaseK8sModel

BaseEntity is the common fields for all entities.

Marker interfaces

kubex_core.models.interfaces

Resource configuration

kubex_core.models.resource_config

ResourceConfig

ResourceConfig(
    version: str | None = None,
    kind: str | None = None,
    plural: str | None = None,
    scope: Scope | None = None,
    group: str | None = None,
    list_model: Type[ListEntity[ResourceType]]
    | None = None,
)

Bases: Generic[ResourceType]

ResourceConfig is the configuration for a resource.

Source code in packages/kubex-core/kubex_core/models/resource_config.py
def __init__(
    self,
    version: str | None = None,
    kind: str | None = None,
    plural: str | None = None,
    scope: Scope | None = None,
    group: str | None = None,
    list_model: Type[ListEntity[ResourceType]] | None = None,
) -> None:
    self._version = version
    self._kind = kind
    self._plural = plural
    self._scope = scope
    self._group = group
    self._list_model = list_model

url

url(
    namespace: str | None = None, name: str | None = None
) -> str

url returns the URL for the resource.

Source code in packages/kubex-core/kubex_core/models/resource_config.py
def url(self, namespace: str | None = None, name: str | None = None) -> str:
    """url returns the URL for the resource."""
    if self.group and self.group != "core":
        api_version = f"/apis/{self.group}/{self.version}"
    else:
        api_version = f"/api/{self.version}"

    url: str
    if namespace is None:
        url = f"{api_version}/{self.plural}"
    elif self.scope == Scope.CLUSTER:
        raise ValueError("resource is cluster-scoped but namespace is set")
    else:
        url = f"{api_version}/namespaces/{namespace}/{self.plural}"

    if name is None:
        return url
    return f"{url}/{name}"

get_version_and_group_from_api_version

get_version_and_group_from_api_version(
    api_version: str | None,
) -> tuple[str, str]

get_version_and_group_from_api_version returns the version and group from the apiVersion.

Source code in packages/kubex-core/kubex_core/models/resource_config.py
def get_version_and_group_from_api_version(api_version: str | None) -> tuple[str, str]:
    """get_version_and_group_from_api_version returns the version and group from the apiVersion."""
    if api_version is None:
        raise ValueError("api_version is not set")
    parts = api_version.split("/")
    if len(parts) == 1:
        return parts[0], "core"
    return parts[1], parts[0]

guess_plural

guess_plural(kind: str) -> str

Guess the resource (plural) name for kind, e.g. Policy -> policies.

Uses regular English rules, matching what controller-gen/kubebuilder produce for CRDs: y -> ies only after a consonant (Gateway -> gateways), es after s/x/z/ch/sh (Mesh -> meshes). Resources with irregular plurals should pass plural= explicitly.

Source code in packages/kubex-core/kubex_core/models/resource_config.py
def guess_plural(kind: str) -> str:
    """Guess the resource (plural) name for `kind`, e.g. `Policy` -> `policies`.

    Uses regular English rules, matching what controller-gen/kubebuilder
    produce for CRDs: `y` -> `ies` only after a consonant (`Gateway` ->
    `gateways`), `es` after `s`/`x`/`z`/`ch`/`sh` (`Mesh` -> `meshes`).
    Resources with irregular plurals should pass `plural=` explicitly.
    """
    singular = kind.lower()
    if not singular:
        raise ValueError("kind is empty")
    if singular.endswith(_UNPLURALIZED_SUFFIXES):
        return singular
    if singular.endswith("y") and len(singular) > 1 and singular[-2] not in _VOWELS:
        return f"{singular[:-1]}ies"
    if singular.endswith(("s", "x", "z", "ch", "sh")):
        return f"{singular}es"
    return f"{singular}s"

Metadata models

kubex_core.models.metadata

ListMetadata

Bases: BaseK8sModel

ListMeta describes metadata that synthetic resources must have, including lists and various status objects.

shard_info class-attribute instance-attribute

shard_info: ShardInfo | None = None

Set on sharded list responses (alpha, Kubernetes 1.36+).

ManagedFieldsEntry

Bases: BaseK8sModel

ManagedFieldsEntry is a workflow-id, a FieldSet and the group version of the resource that the fieldset applies to.

ObjectMetadata

Bases: BaseK8sModel

CommonMetadata is the common metadata for all Kubernetes API objects.

self_link: str | None = None

Deprecated: no longer populated by the API server.

OwnerReference

Bases: BaseK8sModel

OwnerReference contains enough information to let you identify an owning object.

ShardInfo

Bases: BaseK8sModel

ShardInfo describes the shard selector that was applied to produce a list response.

List

kubex_core.models.list_entity

ListEntity

Bases: BaseK8sModel, Generic[ResourceType]

ListEntity is the common fields for all list entities.

Subresource models

kubex_core.models.status

Status

Bases: BaseEntity

Status is a return value for calls that don't return other objects.

api_version class-attribute instance-attribute

api_version: Literal['v1'] | None = 'v1'

APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

code class-attribute instance-attribute

code: int = 0

Suggested HTTP return code for this status, 0 if not set.

details class-attribute instance-attribute

details: StatusDetails | None = None

Extended data associated with the reason. Each reason may define its own extended details. This field is optional and the data returned is not guaranteed to conform to any schema except that defined by the reason type.

kind class-attribute instance-attribute

kind: Literal['Status'] | None = 'Status'

Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

message class-attribute instance-attribute

message: str | None = None

A human-readable description of the status of this operation.

metadata class-attribute instance-attribute

metadata: ObjectMetadata = Field(
    default_factory=ObjectMetadata
)

Standard list metadata (ListMeta on the wire; its continue and remainingItemCount are kept as extra fields). Optional: exec error frames and many error bodies carry no metadata at all.

reason class-attribute instance-attribute

reason: str | None = None

A machine-readable description of why this operation is in the "Failure" status. If this value is empty there is no information available. A Reason clarifies an HTTP status code but does not override it.

status class-attribute instance-attribute

status: Literal['Success', 'Failure'] | None = None

Status of the operation. One of: "Success" or "Failure". More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

StatusCause

Bases: BaseK8sModel

StatusCause provides more information about an api.Status failure, including cases when multiple errors are encountered.

field class-attribute instance-attribute

field: str | None = None

The field of the resource that has caused this error, as named by its JSON serialization. May include dot and postfix notation for nested attributes. Arrays are zero-indexed. Fields may appear more than once in an array of causes due to fields having multiple errors. Optional. Examples: "name" - the field "name" on the current resource "items[0].name" - the field "name" on the first array entry in "items"

message class-attribute instance-attribute

message: str | None = None

A human-readable description of the cause of the error. This field may be presented as-is to a reader.

reason class-attribute instance-attribute

reason: str | None = None

A machine-readable description of the cause of the error. If this value is empty there is no information available.

StatusDetails

Bases: BaseK8sModel

tatusDetails is a set of additional properties that MAY be set by the server to provide additional information about a response. The Reason field of a Status object defines what attributes will be set. Clients must ignore fields that do not match the defined type of each attribute, and should assume that any attribute may be empty, invalid, or under defined.

causes class-attribute instance-attribute

causes: list[StatusCause] | None = None

The Causes array includes more details associated with the StatusReason failure. Not all StatusReasons may provide detailed causes.

group class-attribute instance-attribute

group: str | None = None

The group attribute of the resource associated with the status StatusReason.

kind class-attribute instance-attribute

kind: str | None = None

The kind attribute of the resource associated with the status StatusReason. On some operations may differ from the requested resource Kind. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

name class-attribute instance-attribute

name: str | None = None

The name attribute of the resource associated with the status StatusReason (when there is a single name which can be described).

retry_after_seconds class-attribute instance-attribute

retry_after_seconds: int | None = None

If specified, the time in seconds before the operation should be retried. Some errors may indicate the client must take an alternate action - for those errors this field may indicate how long to wait before taking the alternate action.

uid class-attribute instance-attribute

uid: str | None = None

UID of the resource. (when there is a single resource which can be described). More info: http://kubernetes.io/docs/user-guide/identifiers#uids

kubex_core.models.scale

kubex_core.models.eviction

DeleteOptions

Bases: BaseK8sModel

Minimal representation of meta/v1 DeleteOptions for use in Eviction.

Eviction

Bases: BaseK8sModel

Eviction evicts a pod from its node subject to certain policies and safety constraints.

This is a minimal model for the policy/v1 Eviction resource, used by the EvictionAccessor to POST eviction requests.

Partial metadata

kubex_core.models.partial_object_meta

PartialObjectMetadata

Bases: BaseEntity

PartialObjectMetadata is the common metadata for all Kubernetes API objects.

Field types

kubex_core.models.types

Reusable annotated field types matching Kubernetes wire semantics.

Use these in hand-written models (e.g. CRDs) the same way the generated kubex-k8s-* models do:

  • Time / MicroTime: datetime.datetime fields serialized the way the API server expects (metav1.Time / metav1.MicroTime). Naive datetimes are treated as UTC.
  • Quantity: a resource.Quantity string that also accepts the numeric values YAML manifests commonly carry (cpu: 1, cpu: 0.5).
  • NullAsEmptyList[T] / NullAsEmptyDict[T]: required collections that the API server may send as null (Go nil slices/maps); null is read as an empty collection.

Serializers only apply in JSON mode (model_dump(mode="json"), model_dump_json()); python-mode dumps keep datetime objects.

MicroTime module-attribute

MicroTime = Annotated[
    datetime.datetime,
    PlainSerializer(
        serialize_micro_time,
        return_type=str,
        when_used="json",
    ),
]

metav1.MicroTime: emitted as 2006-01-02T15:04:05.000000Z (UTC, microseconds).

NullAsEmptyDict module-attribute

NullAsEmptyDict = Annotated[
    dict[str, _T], BeforeValidator(_none_to_dict)
]

dict[str, T] that reads null as {}.

NullAsEmptyList module-attribute

NullAsEmptyList = Annotated[
    list[_T], BeforeValidator(_none_to_list)
]

list[T] that reads null as [].

Quantity module-attribute

Quantity = Annotated[str, BeforeValidator(_coerce_quantity)]

resource.Quantity: a string; int/float/Decimal inputs are converted to str.

Time module-attribute

Time = Annotated[
    datetime.datetime,
    PlainSerializer(
        serialize_time, return_type=str, when_used="json"
    ),
]

metav1.Time: emitted as 2006-01-02T15:04:05Z (UTC, seconds).

serialize_micro_time

serialize_micro_time(value: Any) -> Any

Format like metav1.MicroTime: RFC 3339, UTC, always six fractional digits.

The API server parses MicroTime with a fixed .000000 layout, so the fraction must be present even when it is zero. Non-datetime values are passed through unchanged.

Source code in packages/kubex-core/kubex_core/models/types.py
def serialize_micro_time(value: Any) -> Any:
    """Format like `metav1.MicroTime`: RFC 3339, UTC, always six fractional digits.

    The API server parses MicroTime with a fixed `.000000` layout, so the
    fraction must be present even when it is zero. Non-datetime values are
    passed through unchanged.
    """
    if not isinstance(value, datetime.datetime):
        return value
    return _as_utc(value).strftime("%Y-%m-%dT%H:%M:%S.%fZ")

serialize_time

serialize_time(value: Any) -> Any

Format like metav1.Time: RFC 3339, UTC, second precision.

Non-datetime values (e.g. a string assigned after validation or set via model_construct) are passed through unchanged.

Source code in packages/kubex-core/kubex_core/models/types.py
def serialize_time(value: Any) -> Any:
    """Format like `metav1.Time`: RFC 3339, UTC, second precision.

    Non-datetime values (e.g. a string assigned after validation or set via
    `model_construct`) are passed through unchanged.
    """
    if not isinstance(value, datetime.datetime):
        return value
    return _as_utc(value).strftime("%Y-%m-%dT%H:%M:%SZ")

Type aliases

kubex_core.models.typing