Skip to content

kubex.api

Auto-generated reference for the kubex.api module. Private descriptors (e.g. _LogsDescriptor) are excluded; they exist to wire the subresource accessors onto Api[T] and are not part of the public API.

Api class

kubex.api.api

Api

Api(
    resource_type: Type[ResourceType],
    client: BaseClient,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
)

Bases: Generic[ResourceType]

API for interacting with a Kubernetes resource type.

Parameters:

Name Type Description Default
resource_type Type[ResourceType]

The resource model class to operate on, e.g. Pod.

required
client BaseClient

The client used to send requests.

required
namespace ApiNamespaceTypes

The default namespace for this API's calls; each method can override it. If omitted, a namespace-scoped resource uses the client's configured namespace (the kubeconfig context's namespace, or the pod's own namespace in-cluster). Pass None for no default, which means "all namespaces" for list, watch and delete_collection. Cluster-scoped resources never get a namespace; passing one for them raises ValueError.

Ellipsis

Raises:

Type Description
ValueError

namespace is given for a cluster-scoped resource.

Source code in kubex/api/api.py
def __init__(
    self,
    resource_type: Type[ResourceType],
    client: BaseClient,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
) -> None:
    self._resource = resource_type
    self._client = client
    self._request_builder = RequestBuilder(
        resource_config=resource_type.__RESOURCE_CONFIG__,
    )
    scope = self._resource.__RESOURCE_CONFIG__.scope
    if namespace is Ellipsis:
        # Unspecified: seed from the client's configured namespace, but only
        # for namespace-scoped resources -- a cluster-scoped resource must
        # never receive a namespace, configured or not. An explicit `None`
        # (rather than omitting the argument) still means "all namespaces"
        # and is never overridden by the client's configured namespace.
        # An empty configured namespace (e.g. `namespace: ""` in a kubeconfig
        # context) means "not set", not an empty path segment.
        namespace = (
            client.configuration.namespace or None
            if scope == Scope.NAMESPACE
            else None
        )
    self._namespace = namespace
    ensure_optional_namespace(namespace, self._namespace, scope)
    self.metadata = MetadataAccessor(
        client=self._client,
        request_builder=self._request_builder,
        namespace=self._namespace,
        scope=self._resource.__RESOURCE_CONFIG__.scope,
        resource_type=self._resource,
    )

create async

create(
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Create a resource.

Parameters:

Name Type Description Default
data ResourceType

The resource instance to create.

required
namespace ApiNamespaceTypes

The namespace to create the resource in. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this request sets.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the created resource instance, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

Conflict

a resource with this name already exists.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def create(
    self,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Create a resource.

    Args:
        data: The resource instance to create.
        namespace: The namespace to create the resource in. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this request sets.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the created resource instance, as stored by the API server.

    Raises:
        ValueError: an argument is invalid, e.g. a namespace that is missing for
            a namespace-scoped resource or given for a cluster-scoped one, or an
            unknown option value (e.g. for ``dry_run``).
        Conflict: a resource with this name already exists.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    options = PostOptions(dry_run=dry_run, field_manager=field_manager)
    request = self._request_builder.create(
        _namespace,
        options,
        data.model_dump_json(by_alias=True, exclude_none=True),
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource.model_validate_json(response.content)

delete async

delete(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    grace_period_seconds: int | None = None,
    propagation_policy: PropagationPolicyTypes = None,
    preconditions: Precondition | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Status | ResourceType

Delete the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to delete.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to delete. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without deleting anything (True, "All" or DryRun.ALL).

None
grace_period_seconds int | None

The duration in seconds before the object should be deleted, overriding its default grace period. 0 deletes immediately.

None
propagation_policy PropagationPolicyTypes

Whether and how dependents are garbage collected: "Foreground", "Background" or "Orphan" (or the PropagationPolicy enum).

None
preconditions Precondition | None

Conditions the object must meet to be deleted (Precondition(uid=..., resource_version=...)); the server returns 409 Conflict if they don't hold.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
Status Status | ResourceType

the resource has been fully deleted.

ResourceType Status | ResourceType

deletion has started, but the resource still exists (e.g. it has finalizers or a termination grace period); the returned object has deletionTimestamp set. For details see Resource deletion documentation.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

preconditions do not hold.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def delete(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    grace_period_seconds: int | None = None,
    propagation_policy: PropagationPolicyTypes = None,
    preconditions: Precondition | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Status | ResourceType:
    """Delete the specified resource.

    Args:
        name: The name of the resource to delete.
        namespace: The namespace of the namespaced resource to delete. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without deleting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        grace_period_seconds: The duration in seconds before the object should be
            deleted, overriding its default grace period. ``0`` deletes immediately.
        propagation_policy: Whether and how dependents are garbage collected:
            ``"Foreground"``, ``"Background"`` or ``"Orphan"`` (or the
            ``PropagationPolicy`` enum).
        preconditions: Conditions the object must meet to be deleted
            (``Precondition(uid=..., resource_version=...)``); the server returns
            ``409 Conflict`` if they don't hold.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        Status: the resource has been fully deleted.
        ResourceType: deletion has started, but the resource still exists (e.g.
            it has finalizers or a termination grace period); the returned
            object has ``deletionTimestamp`` set. For details see
            [Resource deletion documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#resource-deletion).

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: ``preconditions`` do not hold.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    options = DeleteOptions(
        dry_run=dry_run,
        grace_period_seconds=grace_period_seconds,
        propagation_policy=propagation_policy,
        preconditions=preconditions,
    )
    request = self._request_builder.delete(
        name, _namespace, options, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    try:
        return Status.model_validate_json(response.content)
    except ValidationError:
        return self._resource.model_validate_json(response.content)

delete_collection async

delete_collection(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    dry_run: DryRunTypes = None,
    grace_period_seconds: int | None = None,
    propagation_policy: PropagationPolicyTypes = None,
    preconditions: Precondition | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Status | ListEntity[ResourceType]

Delete collection of resources.

Deletes every resource matching the filters in a single call. Without any selector, that is every resource of this type in the namespace (or, with namespace=None, in all namespaces).

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace to delete resources in. If not provided, the namespace provided when creating the API will be used. Pass None to delete matching resources in all namespaces. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
label_selector str | None

Only delete resources whose labels match this selector. For details look at Label Selectors documentation.

None
field_selector str | None

Only delete resources whose fields match this selector. For details look at Field Selectors documentation.

None
timeout_seconds int | None

Server-side timeout (in seconds) for the call; sent as the Kubernetes timeoutSeconds query parameter. For an HTTP client-side timeout, use request_timeout.

None
limit int | None

Sent as the Kubernetes limit list option, as in list().

None
continue_token str | None

Sent as the Kubernetes continue list option, as in list().

None
version_match VersionMatchTypes

How the API server should interpret resource_version; sent as the Kubernetes resourceVersionMatch query parameter.

None
resource_version ResourceVersionTypes

The resource version at which to select the resources, as in list().

None
dry_run DryRunTypes

Validate the request without deleting anything (True, "All" or DryRun.ALL).

None
grace_period_seconds int | None

The duration in seconds before each object should be deleted, overriding its default grace period. 0 deletes immediately.

None
propagation_policy PropagationPolicyTypes

Whether and how dependents are garbage collected: "Foreground", "Background" or "Orphan" (or the PropagationPolicy enum).

None
preconditions Precondition | None

Conditions each object must meet to be deleted (Precondition(uid=..., resource_version=...)).

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
Status Status | ListEntity[ResourceType]

the API server reported the result as a Status.

Status | ListEntity[ResourceType]

ListEntity[ResourceType]: the API server returned the list of deleted resources instead; which of the two you get depends on the Kubernetes version.

Raises:

Type Description
ValueError

an argument is invalid, e.g. a namespace given for a cluster-scoped resource, or an unknown option value (e.g. for dry_run or version_match).

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def delete_collection(
    self,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    dry_run: DryRunTypes = None,
    grace_period_seconds: int | None = None,
    propagation_policy: PropagationPolicyTypes = None,
    preconditions: Precondition | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Status | ListEntity[ResourceType]:
    """Delete collection of resources.

    Deletes every resource matching the filters in a single call. Without
    any selector, that is every resource of this type in the namespace (or,
    with ``namespace=None``, in all namespaces).

    Args:
        namespace: The namespace to delete resources in. If not provided,
            the namespace provided when creating the API will be used.
            Pass ``None`` to delete matching resources in all namespaces.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        label_selector: Only delete resources whose labels match this selector.
            For details look at [Label Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors).
        field_selector: Only delete resources whose fields match this selector.
            For details look at [Field Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/).
        timeout_seconds: Server-side timeout (in seconds) for the call;
            sent as the Kubernetes ``timeoutSeconds`` query parameter. For an
            HTTP client-side timeout, use ``request_timeout``.
        limit: Sent as the Kubernetes ``limit`` list option, as in ``list()``.
        continue_token: Sent as the Kubernetes ``continue`` list option, as in
            ``list()``.
        version_match: How the API server should interpret ``resource_version``; sent
            as the Kubernetes ``resourceVersionMatch`` query parameter.
        resource_version: The resource version at which to select the resources,
            as in ``list()``.
        dry_run: Validate the request without deleting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        grace_period_seconds: The duration in seconds before each object should be
            deleted, overriding its default grace period. ``0`` deletes immediately.
        propagation_policy: Whether and how dependents are garbage collected:
            ``"Foreground"``, ``"Background"`` or ``"Orphan"`` (or the
            ``PropagationPolicy`` enum).
        preconditions: Conditions each object must meet to be deleted
            (``Precondition(uid=..., resource_version=...)``).
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        Status: the API server reported the result as a ``Status``.
        ListEntity[ResourceType]: the API server returned the list of deleted
            resources instead; which of the two you get depends on the
            Kubernetes version.

    Raises:
        ValueError: an argument is invalid, e.g. a namespace given for a
            cluster-scoped resource, or an unknown option value (e.g. for
            ``dry_run`` or ``version_match``).
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_optional_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    list_options = ListOptions(
        label_selector=label_selector,
        field_selector=field_selector,
        timeout_seconds=timeout_seconds,
        limit=limit,
        continue_token=continue_token,
        version_match=version_match,
        resource_version=resource_version,
    )
    delete_options = DeleteOptions(
        dry_run=dry_run,
        grace_period_seconds=grace_period_seconds,
        propagation_policy=propagation_policy,
        preconditions=preconditions,
    )
    request = self._request_builder.delete_collection(
        _namespace,
        list_options,
        delete_options,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    list_model = self._resource.__RESOURCE_CONFIG__.list_model
    try:
        return Status.model_validate_json(response.content)
    except ValidationError:
        return list_model.model_validate_json(response.content)

get async

get(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Read the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to read.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to read. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
resource_version ResourceVersionTypes

The resource version to read. If not provided, the current resource version will be read. For details look at Resource Version Semantics documentation.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the resource instance.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one.

NotFound

the resource does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def get(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Read the specified resource.

    Args:
        name: The name of the resource to read.
        namespace: The namespace of the namespaced resource to read. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        resource_version: The resource version to read. If not provided,
            the current resource version will be read. For details look at
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list).
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the resource instance.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one.
        NotFound: the resource does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    options = GetOptions(resource_version=resource_version)
    request = self._request_builder.get(
        name, _namespace, options, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return self._resource.model_validate_json(response.content)

list async

list(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: Literal[RAISE, "raise"] = InvalidObjects.RAISE,
) -> ListEntity[ResourceType]
list(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: Literal[INCLUDE, "include"],
) -> ListWithInvalid[ResourceType]
list(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: InvalidObjectsTypes,
) -> ListEntity[ResourceType]
list(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: InvalidObjectsTypes = InvalidObjects.RAISE,
) -> ListEntity[ResourceType]

List objects of kind.

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace of the namespaced resource to list. If not provided, the namespace provided when creating the API will be used. Pass None to list across all namespaces. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
label_selector str | None

A selector to restrict the list of returned objects by their labels. For details look at Label Selectors documentation.

None
field_selector str | None

A selector to restrict the list of returned objects by their fields. For details look at Field Selectors documentation.

None
timeout_seconds int | None

Server-side timeout (in seconds) for the list/watch call; sent as the Kubernetes timeoutSeconds query parameter. For an HTTP client-side timeout, use request_timeout.

None
limit int | None

The maximum number of items to return. If more items match, the returned list's metadata.continue_ holds a token for the next page.

None
continue_token str | None

The metadata.continue_ token from the previous page, to fetch the next one. Pass the same filters as for that page.

None
version_match VersionMatchTypes

How the API server should interpret resource_version; sent as the Kubernetes resourceVersionMatch query parameter. See Resource Version Semantics documentation.

None
resource_version ResourceVersionTypes

The resource version to list. If not provided, the current resource version will be listed. For details look at Resource Version Semantics documentation.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis
invalid InvalidObjectsTypes

What to do with an object that does not fit the model. InvalidObjects.RAISE (the default) raises pydantic's ValidationError. InvalidObjects.INCLUDE returns a ListWithInvalid that keeps such objects in invalid, each an InvalidObject with its raw data, the error and its metadata.

RAISE

Returns:

Type Description
ListEntity[ResourceType]

ListEntity[ResourceType]: the list of resources, with the list's metadata (resource_version, continue_). A ListWithInvalid with invalid=InvalidObjects.INCLUDE.

Raises:

Type Description
ValueError

an argument is invalid, e.g. a namespace given for a cluster-scoped resource, or an unknown option value (e.g. for version_match).

ValidationError

an object does not fit the model (unless invalid=InvalidObjects.INCLUDE), or the response is not a valid list; with INCLUDE, also an object without a readable metadata.name.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def list(
    self,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: InvalidObjectsTypes = InvalidObjects.RAISE,
) -> ListEntity[ResourceType]:
    """List objects of kind.

    Args:
        namespace: The namespace of the namespaced resource to list. If not provided,
            the namespace provided when creating the API will be used.
            Pass ``None`` to list across all namespaces.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        label_selector: A selector to restrict the list of returned objects by their labels.
            For details look at [Label Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors).
        field_selector: A selector to restrict the list of returned objects by their fields.
            For details look at [Field Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/).
        timeout_seconds: Server-side timeout (in seconds) for the list/watch call;
            sent as the Kubernetes ``timeoutSeconds`` query parameter. For an
            HTTP client-side timeout, use ``request_timeout``.
        limit: The maximum number of items to return. If more items match, the
            returned list's ``metadata.continue_`` holds a token for the next page.
        continue_token: The ``metadata.continue_`` token from the previous page,
            to fetch the next one. Pass the same filters as for that page.
        version_match: How the API server should interpret ``resource_version``; sent
            as the Kubernetes ``resourceVersionMatch`` query parameter. See
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list).
        resource_version: The resource version to list. If not provided,
            the current resource version will be listed. For details look at
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list).
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.
        invalid: What to do with an object that does not fit the model.
            ``InvalidObjects.RAISE`` (the default) raises pydantic's
            ``ValidationError``. ``InvalidObjects.INCLUDE`` returns a
            ``ListWithInvalid`` that keeps such objects in ``invalid``, each an
            ``InvalidObject`` with its raw data, the error and its metadata.

    Returns:
        ListEntity[ResourceType]: the list of resources, with the list's
            ``metadata`` (``resource_version``, ``continue_``). A
            ``ListWithInvalid`` with ``invalid=InvalidObjects.INCLUDE``.

    Raises:
        ValueError: an argument is invalid, e.g. a namespace given for a
            cluster-scoped resource, or an unknown option value (e.g. for
            ``version_match``).
        ValidationError: an object does not fit the model (unless
            ``invalid=InvalidObjects.INCLUDE``), or the response is not a
            valid list; with ``INCLUDE``, also an object without a readable
            ``metadata.name``.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    invalid_objects = InvalidObjects(invalid)
    _namespace = ensure_optional_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    options = ListOptions(
        label_selector=label_selector,
        field_selector=field_selector,
        timeout_seconds=timeout_seconds,
        limit=limit,
        continue_token=continue_token,
        version_match=version_match,
        resource_version=resource_version,
    )
    request = self._request_builder.list(
        _namespace, options, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    list_model = self._resource.__RESOURCE_CONFIG__.list_model
    if invalid_objects is InvalidObjects.INCLUDE:
        return _validate_list_with_invalid(
            self._resource, list_model, response.content
        )
    return list_model.model_validate_json(response.content)

patch async

patch(
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Patch the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to patch.

required
patch Patch

The patch to send: ApplyPatch (server-side apply), MergePatch, StrategicMergePatch or JsonPatch. Its type sets the request's Content-Type.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to patch. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this patch sets. Required for ApplyPatch.

None
force bool | None

Take over fields currently owned by another field manager instead of failing with 409 Conflict. Only valid with ApplyPatch.

None
field_validation FieldValidationTypes

How the API server handles unknown or duplicate fields in the patch: "Strict" (reject the request), "Warn" (accept it with a warning; the server default) or "Ignore" (drop them silently). Also accepts the FieldValidation enum.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the patched resource. An ApplyPatch for a resource that does not exist yet creates it and returns the new resource.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run or field_validation).

NotFound

the resource does not exist (an ApplyPatch creates it instead).

Conflict

an ApplyPatch conflicts with fields owned by another field manager and force is not set.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def patch(
    self,
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Patch the specified resource.

    Args:
        name: The name of the resource to patch.
        patch: The patch to send: ``ApplyPatch`` (server-side apply),
            ``MergePatch``, ``StrategicMergePatch`` or ``JsonPatch``. Its type
            sets the request's ``Content-Type``.
        namespace: The namespace of the namespaced resource to patch. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this patch sets. Required for ``ApplyPatch``.
        force: Take over fields currently owned by another field manager instead
            of failing with ``409 Conflict``. Only valid with ``ApplyPatch``.
        field_validation: How the API server handles unknown or duplicate fields in
            the patch: ``"Strict"`` (reject the request), ``"Warn"`` (accept it
            with a warning; the server default) or ``"Ignore"`` (drop them
            silently). Also accepts the ``FieldValidation`` enum.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the patched resource. An ``ApplyPatch`` for a resource
            that does not exist yet creates it and returns the new resource.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run`` or ``field_validation``).
        NotFound: the resource does not exist (an ``ApplyPatch`` creates it
            instead).
        Conflict: an ``ApplyPatch`` conflicts with fields owned by another
            field manager and ``force`` is not set.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    options = PatchOptions(
        dry_run=dry_run,
        field_manager=field_manager,
        force=force,
        field_validation=field_validation,
    )
    request = self._request_builder.patch(
        name, _namespace, options, patch, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return self._resource.model_validate_json(response.content)

replace async

replace(
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Replace the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to replace.

required
data ResourceType

The complete new state of the resource. If its metadata.resource_version is set (e.g. from a previous get()), the request fails with 409 Conflict when the resource has changed since that version.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to replace. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this request sets.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the replaced resource, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

the resource has changed since the metadata.resource_version that was sent.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def replace(
    self,
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Replace the specified resource.

    Args:
        name: The name of the resource to replace.
        data: The complete new state of the resource. If its
            ``metadata.resource_version`` is set (e.g. from a previous ``get()``),
            the request fails with ``409 Conflict`` when the resource has changed
            since that version.
        namespace: The namespace of the namespaced resource to replace. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this request sets.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the replaced resource, as stored by the API server.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: the resource has changed since the
            ``metadata.resource_version`` that was sent.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    options = PostOptions(dry_run=dry_run, field_manager=field_manager)
    request = self._request_builder.replace(
        name,
        _namespace,
        options,
        data.model_dump_json(by_alias=True, exclude_none=True),
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource.model_validate_json(response.content)

watch async

watch(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    allow_bookmarks: bool | None = None,
    send_initial_events: bool | None = None,
    resource_version: ResourceVersionTypes = None,
    timeout_seconds: int | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: Literal[RAISE, "raise"] = InvalidObjects.RAISE,
) -> AsyncGenerator[WatchEvent[ResourceType], None]
watch(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    allow_bookmarks: bool | None = None,
    send_initial_events: bool | None = None,
    resource_version: ResourceVersionTypes = None,
    timeout_seconds: int | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: Literal[INCLUDE, "include"],
) -> AsyncGenerator[
    WatchEvent[ResourceType] | InvalidWatchEvent, None
]
watch(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    allow_bookmarks: bool | None = None,
    send_initial_events: bool | None = None,
    resource_version: ResourceVersionTypes = None,
    timeout_seconds: int | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: InvalidObjectsTypes,
) -> AsyncGenerator[
    WatchEvent[ResourceType] | InvalidWatchEvent, None
]
watch(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    allow_bookmarks: bool | None = None,
    send_initial_events: bool | None = None,
    resource_version: ResourceVersionTypes = None,
    timeout_seconds: int | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: InvalidObjectsTypes = InvalidObjects.RAISE,
) -> AsyncGenerator[
    WatchEvent[ResourceType] | InvalidWatchEvent, None
]

Watch for changes to the specified resource.

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace to watch. If not provided, the namespace provided when creating the API will be used. Pass None to watch all namespaces. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
label_selector str | None

Only watch resources whose labels match this selector. For details look at Label Selectors documentation.

None
field_selector str | None

Only watch resources whose fields match this selector. For details look at Field Selectors documentation.

None
allow_bookmarks bool | None

Request periodic BOOKMARK events carrying a fresh resourceVersion. Defaults to True when send_initial_events is True (the server requires it); passing False together with send_initial_events=True raises ValueError.

None
send_initial_events bool | None

Start the stream with synthetic ADDED events for the current state, followed by a bookmark annotated with k8s.io/initial-events-end (see WatchEvent.is_initial_events_end).

None
resource_version ResourceVersionTypes

Only deliver changes made after this resource version, e.g. the list metadata.resource_version from a previous list(). If not provided, the stream starts with synthetic ADDED events for every existing resource and then follows changes. For details look at Resource Version Semantics documentation.

None
timeout_seconds int | None

Server-side timeout (in seconds); the server ends the stream cleanly after it.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client's default for streams, which does not cut off an idle watch. An explicit short read/total timeout will terminate a quiet stream.

Ellipsis
invalid InvalidObjectsTypes

What to do with an ADDED, MODIFIED or DELETED object that does not fit the model. InvalidObjects.RAISE (the default) raises pydantic's ValidationError, which ends the stream. InvalidObjects.INCLUDE yields an InvalidWatchEvent for it and the stream goes on.

RAISE

Yields:

Type Description
AsyncGenerator[WatchEvent[ResourceType] | InvalidWatchEvent, None]

WatchEvent[ResourceType]: one event per change, with its type (ADDED, MODIFIED, DELETED or BOOKMARK) and object (the resource, or a Bookmark for BOOKMARK events). ERROR events are raised as exceptions instead. With invalid=InvalidObjects.INCLUDE, an InvalidWatchEvent for each object that does not fit the model.

Raises:

Type Description
ValueError

an argument is invalid, e.g. a namespace given for a cluster-scoped resource, or allow_bookmarks=False together with send_initial_events=True.

ValidationError

an object does not fit the model (unless invalid=InvalidObjects.INCLUDE), or a bookmark does not parse; with INCLUDE, also an object without a readable metadata.name.

Gone

the requested resource_version is too old (HTTP 410), either on connect or as an ERROR event mid-stream; re-list and watch again from the new resourceVersion.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached, or the connection broke mid-stream.

KubexTimeoutError

the request timed out on the client side, including mid-stream.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/api.py
async def watch(
    self,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    allow_bookmarks: bool | None = None,
    send_initial_events: bool | None = None,
    resource_version: ResourceVersionTypes = None,
    timeout_seconds: int | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
    invalid: InvalidObjectsTypes = InvalidObjects.RAISE,
) -> AsyncGenerator[WatchEvent[ResourceType] | InvalidWatchEvent, None]:
    """Watch for changes to the specified resource.

    Args:
        namespace: The namespace to watch. If not provided,
            the namespace provided when creating the API will be used.
            Pass ``None`` to watch all namespaces.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        label_selector: Only watch resources whose labels match this selector.
            For details look at [Label Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors).
        field_selector: Only watch resources whose fields match this selector.
            For details look at [Field Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/).
        allow_bookmarks: Request periodic ``BOOKMARK`` events carrying a fresh
            ``resourceVersion``. Defaults to ``True`` when ``send_initial_events``
            is ``True`` (the server requires it); passing ``False`` together with
            ``send_initial_events=True`` raises ``ValueError``.
        send_initial_events: Start the stream with synthetic ``ADDED`` events for
            the current state, followed by a bookmark annotated with
            ``k8s.io/initial-events-end`` (see
            ``WatchEvent.is_initial_events_end``).
        resource_version: Only deliver changes made after this resource version,
            e.g. the list ``metadata.resource_version`` from a previous
            ``list()``. If not provided, the stream starts with synthetic
            ``ADDED`` events for every existing resource and then follows
            changes. For details look at
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-watch).
        timeout_seconds: Server-side timeout (in seconds); the server ends the
            stream cleanly after it.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client's default
            for streams, which does not cut off an idle watch. An explicit
            short read/total timeout will terminate a quiet stream.
        invalid: What to do with an ``ADDED``, ``MODIFIED`` or ``DELETED``
            object that does not fit the model. ``InvalidObjects.RAISE`` (the
            default) raises pydantic's ``ValidationError``, which ends the
            stream. ``InvalidObjects.INCLUDE`` yields an ``InvalidWatchEvent``
            for it and the stream goes on.

    Yields:
        WatchEvent[ResourceType]: one event per change, with its ``type``
            (``ADDED``, ``MODIFIED``, ``DELETED`` or ``BOOKMARK``) and
            ``object`` (the resource, or a ``Bookmark`` for ``BOOKMARK``
            events). ``ERROR`` events are raised as exceptions instead. With
            ``invalid=InvalidObjects.INCLUDE``, an ``InvalidWatchEvent`` for
            each object that does not fit the model.

    Raises:
        ValueError: an argument is invalid, e.g. a namespace given for a
            cluster-scoped resource, or ``allow_bookmarks=False`` together with
            ``send_initial_events=True``.
        ValidationError: an object does not fit the model (unless
            ``invalid=InvalidObjects.INCLUDE``), or a bookmark does not parse;
            with ``INCLUDE``, also an object without a readable
            ``metadata.name``.
        Gone: the requested ``resource_version`` is too old (HTTP 410), either
            on connect or as an ``ERROR`` event mid-stream; re-list and watch
            again from the new ``resourceVersion``.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached, or the
            connection broke mid-stream.
        KubexTimeoutError: the request timed out on the client side, including
            mid-stream.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    invalid_objects = InvalidObjects(invalid)
    _namespace = ensure_optional_namespace(
        namespace, self._namespace, self._resource.__RESOURCE_CONFIG__.scope
    )
    options = WatchOptions(
        label_selector=label_selector,
        field_selector=field_selector,
        allow_bookmarks=allow_bookmarks,
        send_initial_events=send_initial_events,
        resource_version=resource_version,
        timeout_seconds=timeout_seconds,
    )
    request = self._request_builder.watch(
        _namespace,
        options,
        request_timeout=request_timeout,
    )
    async for line in self._client.stream_lines(request):
        # Parse before yielding: the yield stays outside any ``except``, so an
        # exception thrown into the generator is never mistaken for ours.
        event = _parse_watch_event(
            self._resource, json.loads(line), invalid_objects
        )
        yield event

create_api async

create_api(
    resource_type: Type[ResourceType],
    *,
    client: BaseClient | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
) -> Api[ResourceType]

Create an API for the specified resource type.

Parameters:

Name Type Description Default
resource_type Type[ResourceType]

The resource type to create an API for.

required
client BaseClient | None

The client to use for the API. If not provided, a new client will be created.

None
namespace ApiNamespaceTypes

The namespace to use for the API. If set all operations will be performed in this namespace. The Api namespace can be overridden by passing a namespace to the individual methods. If omitted, a namespace-scoped resource falls back to the client's configured namespace (e.g. the in-cluster pod's own namespace); pass None explicitly for "all namespaces" instead. Cluster-scoped resources never receive a namespace.

Ellipsis

Returns:

Type Description
Api[ResourceType]

An Api instance for the specified resource type.

Raises:

Type Description
ValueError

namespace is given for a cluster-scoped resource.

ConfigurationError

no client was given and no configuration could be loaded (no usable kubeconfig, and not running inside a cluster).

ImportError

no client was given and neither aiohttp nor httpx is installed.

Source code in kubex/api/api.py
async def create_api(
    resource_type: Type[ResourceType],
    *,
    client: BaseClient | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
) -> Api[ResourceType]:
    """Create an API for the specified resource type.

    Args:
        resource_type: The resource type to create an API for.
        client: The client to use for the API. If not provided,
            a new client will be created.
        namespace: The namespace to use for the API. If set all
            operations will be performed in this namespace.
            The Api namespace can be overridden by passing a
            namespace to the individual methods. If omitted, a
            namespace-scoped resource falls back to the client's
            configured namespace (e.g. the in-cluster pod's own
            namespace); pass ``None`` explicitly for "all namespaces"
            instead. Cluster-scoped resources never receive a namespace.

    Returns:
        An Api instance for the specified resource type.

    Raises:
        ValueError: ``namespace`` is given for a cluster-scoped resource.
        ConfigurationError: no ``client`` was given and no configuration could be
            loaded (no usable kubeconfig, and not running inside a cluster).
        ImportError: no ``client`` was given and neither ``aiohttp`` nor ``httpx``
            is installed.
    """
    client = client or await create_client()
    return Api(resource_type, client=client, namespace=namespace)

Logs subresource

kubex.api._logs

LogsAccessor

LogsAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
)

Bases: Generic[ResourceType]

Accessor for logs subresource operations.

Source code in kubex/api/_logs.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type

get async

get(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    container: str | None = None,
    limit_bytes: int | None = None,
    pretty: bool | None = None,
    previous: bool | None = None,
    since_seconds: int | None = None,
    since_time: datetime | None = None,
    tail_lines: int | None = None,
    timestamps: bool | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> str

Read logs of the specified resource.

since_seconds and since_time (a timezone-aware datetime, sent as an RFC 3339 UTC sinceTime) are mutually exclusive.

Parameters:

Name Type Description Default
name str

The name of the resource to read logs of.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
container str | None

The container to read logs of. Required when the Pod has more than one container; the API server rejects the request otherwise.

None
limit_bytes int | None

The maximum number of bytes of log output to return.

None
pretty bool | None

Ask the API server to pretty-print the output.

None
previous bool | None

Return logs of the previous, terminated instance of the container (e.g. after a crash).

None
since_seconds int | None

Only return logs newer than this many seconds.

None
since_time datetime | None

Only return logs newer than this timezone-aware instant. A naive datetime raises ValueError.

None
tail_lines int | None

Only return this many lines from the end of the log.

None
timestamps bool | None

Prefix each line with its RFC 3339 timestamp.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
str str

the log output, decoded as text.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one; or both since_seconds and since_time are given, or since_time is a naive datetime.

BadRequest

the API server rejected the arguments, e.g. container was not given for a pod with several containers.

NotFound

the pod does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_logs.py
async def get(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    container: str | None = None,
    limit_bytes: int | None = None,
    pretty: bool | None = None,
    previous: bool | None = None,
    since_seconds: int | None = None,
    since_time: datetime | None = None,
    tail_lines: int | None = None,
    timestamps: bool | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> str:
    """Read logs of the specified resource.

    ``since_seconds`` and ``since_time`` (a timezone-aware datetime, sent as
    an RFC 3339 UTC ``sinceTime``) are mutually exclusive.

    Args:
        name: The name of the resource to read logs of.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        container: The container to read logs of. Required when the Pod has
            more than one container; the API server rejects the request otherwise.
        limit_bytes: The maximum number of bytes of log output to return.
        pretty: Ask the API server to pretty-print the output.
        previous: Return logs of the previous, terminated instance of the
            container (e.g. after a crash).
        since_seconds: Only return logs newer than this many seconds.
        since_time: Only return logs newer than this timezone-aware instant.
            A naive datetime raises ``ValueError``.
        tail_lines: Only return this many lines from the end of the log.
        timestamps: Prefix each line with its RFC 3339 timestamp.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        str: the log output, decoded as text.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one; or both
            ``since_seconds`` and ``since_time`` are given, or ``since_time`` is a
            naive datetime.
        BadRequest: the API server rejected the arguments, e.g. ``container``
            was not given for a pod with several containers.
        NotFound: the pod does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = LogOptions(
        container=container,
        limit_bytes=limit_bytes,
        pretty=pretty,
        previous=previous,
        since_seconds=since_seconds,
        since_time=since_time,
        tail_lines=tail_lines,
        timestamps=timestamps,
    )
    request = self._request_builder.logs(
        name, _namespace, options=options, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return response.text

stream async

stream(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    container: str | None = None,
    limit_bytes: int | None = None,
    pretty: bool | None = None,
    previous: bool | None = None,
    since_seconds: int | None = None,
    since_time: datetime | None = None,
    tail_lines: int | None = None,
    timestamps: bool | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncGenerator[str, None]

Stream logs of the specified resource.

Follows the log (follow=true): the stream continues until the container exits or the caller stops iterating. since_seconds and since_time (a timezone-aware datetime, sent as an RFC 3339 UTC sinceTime) are mutually exclusive.

Parameters:

Name Type Description Default
name str

The name of the resource to stream logs of.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
container str | None

The container to stream logs of. Required when the Pod has more than one container; the API server rejects the request otherwise.

None
limit_bytes int | None

The maximum number of bytes of log output to return.

None
pretty bool | None

Ask the API server to pretty-print the output.

None
previous bool | None

Return logs of the previous, terminated instance of the container (e.g. after a crash).

None
since_seconds int | None

Only return logs newer than this many seconds.

None
since_time datetime | None

Only return logs newer than this timezone-aware instant, e.g. the timestamp of the last line processed before a reconnect. A naive datetime raises ValueError.

None
tail_lines int | None

Start with only this many lines from the end of the log.

None
timestamps bool | None

Prefix each line with its RFC 3339 timestamp.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client's default for streams, which does not cut off an idle stream. An explicit short read/total timeout will terminate a quiet stream.

Ellipsis

Yields:

Name Type Description
str AsyncGenerator[str, None]

one log line at a time, without the trailing newline.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one; or both since_seconds and since_time are given, or since_time is a naive datetime.

BadRequest

the API server rejected the arguments, e.g. container was not given for a pod with several containers.

NotFound

the pod does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached, or the connection broke mid-stream.

KubexTimeoutError

the request timed out on the client side, including mid-stream.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_logs.py
async def stream(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    container: str | None = None,
    limit_bytes: int | None = None,
    pretty: bool | None = None,
    previous: bool | None = None,
    since_seconds: int | None = None,
    since_time: datetime | None = None,
    tail_lines: int | None = None,
    timestamps: bool | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncGenerator[str, None]:
    """Stream logs of the specified resource.

    Follows the log (``follow=true``): the stream continues until the
    container exits or the caller stops iterating. ``since_seconds`` and
    ``since_time`` (a timezone-aware datetime, sent as an RFC 3339 UTC
    ``sinceTime``) are mutually exclusive.

    Args:
        name: The name of the resource to stream logs of.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        container: The container to stream logs of. Required when the Pod has
            more than one container; the API server rejects the request otherwise.
        limit_bytes: The maximum number of bytes of log output to return.
        pretty: Ask the API server to pretty-print the output.
        previous: Return logs of the previous, terminated instance of the
            container (e.g. after a crash).
        since_seconds: Only return logs newer than this many seconds.
        since_time: Only return logs newer than this timezone-aware instant,
            e.g. the timestamp of the last line processed before a reconnect.
            A naive datetime raises ``ValueError``.
        tail_lines: Start with only this many lines from the end of the log.
        timestamps: Prefix each line with its RFC 3339 timestamp.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client's default
            for streams, which does not cut off an idle stream. An explicit
            short read/total timeout will terminate a quiet stream.

    Yields:
        str: one log line at a time, without the trailing newline.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one; or both
            ``since_seconds`` and ``since_time`` are given, or ``since_time`` is a
            naive datetime.
        BadRequest: the API server rejected the arguments, e.g. ``container``
            was not given for a pod with several containers.
        NotFound: the pod does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached, or the
            connection broke mid-stream.
        KubexTimeoutError: the request timed out on the client side, including
            mid-stream.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = LogOptions(
        container=container,
        limit_bytes=limit_bytes,
        pretty=pretty,
        previous=previous,
        since_seconds=since_seconds,
        since_time=since_time,
        tail_lines=tail_lines,
        timestamps=timestamps,
    )
    request = self._request_builder.stream_logs(
        name, _namespace, options=options, request_timeout=request_timeout
    )
    async for line in self._client.stream_lines(request):
        yield line

Scale subresource

kubex.api._scale

ScaleAccessor

ScaleAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
)

Bases: Generic[ResourceType]

Accessor for scale subresource operations.

Source code in kubex/api/_scale.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type

get async

get(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Scale

Read the scale of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to read.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to read. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
Scale Scale

the resource's scale: spec.replicas is the desired replica count and status.replicas the observed one.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one.

NotFound

the resource does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_scale.py
async def get(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Scale:
    """Read the scale of the specified resource.

    Args:
        name: The name of the resource to read.
        namespace: The namespace of the namespaced resource to read. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        Scale: the resource's scale: ``spec.replicas`` is the desired replica
            count and ``status.replicas`` the observed one.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one.
        NotFound: the resource does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    request = self._request_builder.get_subresource(
        SCALE_SUBRESOURCE, name, _namespace, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return Scale.model_validate_json(response.content)

patch async

patch(
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Scale

Patch the scale of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose scale to patch.

required
patch Patch

The patch to send: ApplyPatch (server-side apply), MergePatch, StrategicMergePatch or JsonPatch, e.g. a MergePatch setting spec.replicas. Its type sets the request's Content-Type.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this patch sets. Required for ApplyPatch.

None
force bool | None

Take over fields currently owned by another field manager instead of failing with 409 Conflict. Only valid with ApplyPatch.

None
field_validation FieldValidationTypes

How the API server handles unknown or duplicate fields in the patch: "Strict" (reject the request), "Warn" (accept it with a warning; the server default) or "Ignore" (drop them silently). Also accepts the FieldValidation enum.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
Scale Scale

the scale after the patch.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

an ApplyPatch conflicts with fields owned by another field manager and force is not set.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_scale.py
async def patch(
    self,
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Scale:
    """Patch the scale of the specified resource.

    Args:
        name: The name of the resource whose scale to patch.
        patch: The patch to send: ``ApplyPatch`` (server-side apply),
            ``MergePatch``, ``StrategicMergePatch`` or ``JsonPatch``, e.g. a
            ``MergePatch`` setting ``spec.replicas``. Its type sets the
            request's ``Content-Type``.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this patch sets. Required for ``ApplyPatch``.
        force: Take over fields currently owned by another field manager instead
            of failing with ``409 Conflict``. Only valid with ``ApplyPatch``.
        field_validation: How the API server handles unknown or duplicate fields in
            the patch: ``"Strict"`` (reject the request), ``"Warn"`` (accept it
            with a warning; the server default) or ``"Ignore"`` (drop them
            silently). Also accepts the ``FieldValidation`` enum.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        Scale: the scale after the patch.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: an ``ApplyPatch`` conflicts with fields owned by another field
            manager and ``force`` is not set.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PatchOptions(
        dry_run=dry_run,
        field_manager=field_manager,
        force=force,
        field_validation=field_validation,
    )
    request = self._request_builder.patch_subresource(
        SCALE_SUBRESOURCE,
        name,
        _namespace,
        options=options,
        patch=patch,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return Scale.model_validate_json(response.content)

replace async

replace(
    name: str,
    scale: Scale,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Scale

Replace the scale of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose scale to replace.

required
scale Scale

The new scale, usually the Scale from get() with spec.replicas changed. If its metadata.resource_version is set, the request fails with 409 Conflict when the resource has changed since that version.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this request sets.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
Scale Scale

the updated scale.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

the resource has changed since the metadata.resource_version that was sent.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_scale.py
async def replace(
    self,
    name: str,
    scale: Scale,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Scale:
    """Replace the scale of the specified resource.

    Args:
        name: The name of the resource whose scale to replace.
        scale: The new scale, usually the ``Scale`` from ``get()`` with
            ``spec.replicas`` changed. If its ``metadata.resource_version`` is set,
            the request fails with ``409 Conflict`` when the resource has changed
            since that version.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this request sets.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        Scale: the updated scale.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: the resource has changed since the ``metadata.resource_version``
            that was sent.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PostOptions(dry_run=dry_run, field_manager=field_manager)
    request = self._request_builder.replace_subresource(
        SCALE_SUBRESOURCE,
        name,
        _namespace,
        data=scale.model_dump_json(by_alias=True, exclude_none=True),
        options=options,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return Scale.model_validate_json(response.content)

Status subresource

StatusAccessor.get/replace/patch are inherited from ResourceSubresourceAccessor (shared with ResizeAccessor and EphemeralContainersAccessor), hence inherited_members below.

kubex.api._status

StatusAccessor

StatusAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
)

Bases: ResourceSubresourceAccessor[ResourceType]

Accessor for status subresource operations.

Source code in kubex/api/_subresource_accessor.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type

get async

get(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Read this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to read.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to read. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource, as returned by the subresource endpoint.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one.

NotFound

the resource does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def get(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Read this subresource of the specified resource.

    Args:
        name: The name of the resource to read.
        namespace: The namespace of the namespaced resource to read. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource, as returned by the subresource endpoint.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one.
        NotFound: the resource does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    request = self._request_builder.get_subresource(
        self._subresource, name, _namespace, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

patch async

patch(
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Patch this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose subresource to patch.

required
patch Patch

The patch to send: ApplyPatch (server-side apply), MergePatch, StrategicMergePatch or JsonPatch. Its type sets the request's Content-Type. The API server only persists the part this subresource covers.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this patch sets. Required for ApplyPatch.

None
force bool | None

Take over fields currently owned by another field manager instead of failing with 409 Conflict. Only valid with ApplyPatch.

None
field_validation FieldValidationTypes

How the API server handles unknown or duplicate fields in the patch: "Strict" (reject the request), "Warn" (accept it with a warning; the server default) or "Ignore" (drop them silently). Also accepts the FieldValidation enum.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource after the patch, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

an ApplyPatch conflicts with fields owned by another field manager and force is not set.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def patch(
    self,
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Patch this subresource of the specified resource.

    Args:
        name: The name of the resource whose subresource to patch.
        patch: The patch to send: ``ApplyPatch`` (server-side apply),
            ``MergePatch``, ``StrategicMergePatch`` or ``JsonPatch``. Its type
            sets the request's ``Content-Type``. The API server only persists
            the part this subresource covers.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this patch sets. Required for ``ApplyPatch``.
        force: Take over fields currently owned by another field manager instead
            of failing with ``409 Conflict``. Only valid with ``ApplyPatch``.
        field_validation: How the API server handles unknown or duplicate fields in
            the patch: ``"Strict"`` (reject the request), ``"Warn"`` (accept it
            with a warning; the server default) or ``"Ignore"`` (drop them
            silently). Also accepts the ``FieldValidation`` enum.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource after the patch, as stored by the API
            server.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: an ``ApplyPatch`` conflicts with fields owned by another field
            manager and ``force`` is not set.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PatchOptions(
        dry_run=dry_run,
        field_manager=field_manager,
        force=force,
        field_validation=field_validation,
    )
    request = self._request_builder.patch_subresource(
        self._subresource,
        name,
        _namespace,
        options=options,
        patch=patch,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

replace async

replace(
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Replace this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose subresource to replace.

required
data ResourceType

The resource carrying the new subresource content. The API server only persists the part this subresource covers (e.g. .status for the status subresource). If its metadata.resource_version is set (e.g. from a previous get()), the request fails with 409 Conflict when the resource has changed since that version.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this request sets.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource after the update, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

the resource has changed since the metadata.resource_version that was sent.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def replace(
    self,
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Replace this subresource of the specified resource.

    Args:
        name: The name of the resource whose subresource to replace.
        data: The resource carrying the new subresource content. The API server
            only persists the part this subresource covers (e.g. ``.status`` for
            the status subresource). If its ``metadata.resource_version`` is set
            (e.g. from a previous ``get()``), the request fails with
            ``409 Conflict`` when the resource has changed since that version.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this request sets.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource after the update, as stored by the API
            server.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: the resource has changed since the ``metadata.resource_version``
            that was sent.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PostOptions(dry_run=dry_run, field_manager=field_manager)
    request = self._request_builder.replace_subresource(
        self._subresource,
        name,
        _namespace,
        data=data.model_dump_json(by_alias=True, exclude_none=True),
        options=options,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

Eviction subresource

kubex.api._eviction

EvictionAccessor

EvictionAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
)

Bases: Generic[ResourceType]

Accessor for eviction subresource operations.

Source code in kubex/api/_eviction.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type

create async

create(
    name: str,
    eviction: Eviction,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Status

Create an eviction for the specified resource.

Evicts the pod gracefully while respecting its PodDisruptionBudgets, the mechanism behind kubectl drain.

Parameters:

Name Type Description Default
name str

The name of the pod to evict.

required
eviction Eviction

The Eviction body to post; its delete_options (e.g. grace_period_seconds) control the resulting deletion.

required
namespace ApiNamespaceTypes

The namespace of the pod to evict. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without evicting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

Sent as the Kubernetes fieldManager query parameter.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
Status Status

the API server's response once the eviction is accepted.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the pod does not exist.

TooManyRequests

the eviction would violate a PodDisruptionBudget (HTTP 429). Retry later; retry_after holds the server's suggested delay when it sends one.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_eviction.py
async def create(
    self,
    name: str,
    eviction: Eviction,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> Status:
    """Create an eviction for the specified resource.

    Evicts the pod gracefully while respecting its PodDisruptionBudgets, the
    mechanism behind ``kubectl drain``.

    Args:
        name: The name of the pod to evict.
        eviction: The ``Eviction`` body to post; its ``delete_options`` (e.g.
            ``grace_period_seconds``) control the resulting deletion.
        namespace: The namespace of the pod to evict. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without evicting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: Sent as the Kubernetes ``fieldManager`` query parameter.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        Status: the API server's response once the eviction is accepted.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the pod does not exist.
        TooManyRequests: the eviction would violate a PodDisruptionBudget
            (HTTP 429). Retry later; ``retry_after`` holds the server's suggested
            delay when it sends one.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PostOptions(dry_run=dry_run, field_manager=field_manager)
    request = self._request_builder.create_subresource(
        EVICTION_SUBRESOURCE,
        name,
        _namespace,
        data=eviction.model_dump_json(by_alias=True, exclude_none=True),
        options=options,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return Status.model_validate_json(response.content)

Ephemeral containers subresource

kubex.api._ephemeral_containers

EphemeralContainersAccessor

EphemeralContainersAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
)

Bases: ResourceSubresourceAccessor[ResourceType]

Accessor for ephemeral containers subresource operations.

Source code in kubex/api/_subresource_accessor.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type

get async

get(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Read this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to read.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to read. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource, as returned by the subresource endpoint.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one.

NotFound

the resource does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def get(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Read this subresource of the specified resource.

    Args:
        name: The name of the resource to read.
        namespace: The namespace of the namespaced resource to read. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource, as returned by the subresource endpoint.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one.
        NotFound: the resource does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    request = self._request_builder.get_subresource(
        self._subresource, name, _namespace, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

patch async

patch(
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Patch this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose subresource to patch.

required
patch Patch

The patch to send: ApplyPatch (server-side apply), MergePatch, StrategicMergePatch or JsonPatch. Its type sets the request's Content-Type. The API server only persists the part this subresource covers.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this patch sets. Required for ApplyPatch.

None
force bool | None

Take over fields currently owned by another field manager instead of failing with 409 Conflict. Only valid with ApplyPatch.

None
field_validation FieldValidationTypes

How the API server handles unknown or duplicate fields in the patch: "Strict" (reject the request), "Warn" (accept it with a warning; the server default) or "Ignore" (drop them silently). Also accepts the FieldValidation enum.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource after the patch, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

an ApplyPatch conflicts with fields owned by another field manager and force is not set.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def patch(
    self,
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Patch this subresource of the specified resource.

    Args:
        name: The name of the resource whose subresource to patch.
        patch: The patch to send: ``ApplyPatch`` (server-side apply),
            ``MergePatch``, ``StrategicMergePatch`` or ``JsonPatch``. Its type
            sets the request's ``Content-Type``. The API server only persists
            the part this subresource covers.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this patch sets. Required for ``ApplyPatch``.
        force: Take over fields currently owned by another field manager instead
            of failing with ``409 Conflict``. Only valid with ``ApplyPatch``.
        field_validation: How the API server handles unknown or duplicate fields in
            the patch: ``"Strict"`` (reject the request), ``"Warn"`` (accept it
            with a warning; the server default) or ``"Ignore"`` (drop them
            silently). Also accepts the ``FieldValidation`` enum.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource after the patch, as stored by the API
            server.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: an ``ApplyPatch`` conflicts with fields owned by another field
            manager and ``force`` is not set.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PatchOptions(
        dry_run=dry_run,
        field_manager=field_manager,
        force=force,
        field_validation=field_validation,
    )
    request = self._request_builder.patch_subresource(
        self._subresource,
        name,
        _namespace,
        options=options,
        patch=patch,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

replace async

replace(
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Replace this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose subresource to replace.

required
data ResourceType

The resource carrying the new subresource content. The API server only persists the part this subresource covers (e.g. .status for the status subresource). If its metadata.resource_version is set (e.g. from a previous get()), the request fails with 409 Conflict when the resource has changed since that version.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this request sets.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource after the update, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

the resource has changed since the metadata.resource_version that was sent.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def replace(
    self,
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Replace this subresource of the specified resource.

    Args:
        name: The name of the resource whose subresource to replace.
        data: The resource carrying the new subresource content. The API server
            only persists the part this subresource covers (e.g. ``.status`` for
            the status subresource). If its ``metadata.resource_version`` is set
            (e.g. from a previous ``get()``), the request fails with
            ``409 Conflict`` when the resource has changed since that version.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this request sets.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource after the update, as stored by the API
            server.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: the resource has changed since the ``metadata.resource_version``
            that was sent.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PostOptions(dry_run=dry_run, field_manager=field_manager)
    request = self._request_builder.replace_subresource(
        self._subresource,
        name,
        _namespace,
        data=data.model_dump_json(by_alias=True, exclude_none=True),
        options=options,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

Resize subresource

kubex.api._resize

ResizeAccessor

ResizeAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
)

Bases: ResourceSubresourceAccessor[ResourceType]

Accessor for resize subresource operations.

Source code in kubex/api/_subresource_accessor.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type

get async

get(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Read this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to read.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to read. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource, as returned by the subresource endpoint.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one.

NotFound

the resource does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def get(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Read this subresource of the specified resource.

    Args:
        name: The name of the resource to read.
        namespace: The namespace of the namespaced resource to read. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource, as returned by the subresource endpoint.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one.
        NotFound: the resource does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    request = self._request_builder.get_subresource(
        self._subresource, name, _namespace, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

patch async

patch(
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Patch this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose subresource to patch.

required
patch Patch

The patch to send: ApplyPatch (server-side apply), MergePatch, StrategicMergePatch or JsonPatch. Its type sets the request's Content-Type. The API server only persists the part this subresource covers.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this patch sets. Required for ApplyPatch.

None
force bool | None

Take over fields currently owned by another field manager instead of failing with 409 Conflict. Only valid with ApplyPatch.

None
field_validation FieldValidationTypes

How the API server handles unknown or duplicate fields in the patch: "Strict" (reject the request), "Warn" (accept it with a warning; the server default) or "Ignore" (drop them silently). Also accepts the FieldValidation enum.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource after the patch, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

an ApplyPatch conflicts with fields owned by another field manager and force is not set.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def patch(
    self,
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Patch this subresource of the specified resource.

    Args:
        name: The name of the resource whose subresource to patch.
        patch: The patch to send: ``ApplyPatch`` (server-side apply),
            ``MergePatch``, ``StrategicMergePatch`` or ``JsonPatch``. Its type
            sets the request's ``Content-Type``. The API server only persists
            the part this subresource covers.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this patch sets. Required for ``ApplyPatch``.
        force: Take over fields currently owned by another field manager instead
            of failing with ``409 Conflict``. Only valid with ``ApplyPatch``.
        field_validation: How the API server handles unknown or duplicate fields in
            the patch: ``"Strict"`` (reject the request), ``"Warn"`` (accept it
            with a warning; the server default) or ``"Ignore"`` (drop them
            silently). Also accepts the ``FieldValidation`` enum.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource after the patch, as stored by the API
            server.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: an ``ApplyPatch`` conflicts with fields owned by another field
            manager and ``force`` is not set.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PatchOptions(
        dry_run=dry_run,
        field_manager=field_manager,
        force=force,
        field_validation=field_validation,
    )
    request = self._request_builder.patch_subresource(
        self._subresource,
        name,
        _namespace,
        options=options,
        patch=patch,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

replace async

replace(
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType

Replace this subresource of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource whose subresource to replace.

required
data ResourceType

The resource carrying the new subresource content. The API server only persists the part this subresource covers (e.g. .status for the status subresource). If its metadata.resource_version is set (e.g. from a previous get()), the request fails with 409 Conflict when the resource has changed since that version.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this request sets.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
ResourceType ResourceType

the full resource after the update, as stored by the API server.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist.

Conflict

the resource has changed since the metadata.resource_version that was sent.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_subresource_accessor.py
async def replace(
    self,
    name: str,
    data: ResourceType,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ResourceType:
    """Replace this subresource of the specified resource.

    Args:
        name: The name of the resource whose subresource to replace.
        data: The resource carrying the new subresource content. The API server
            only persists the part this subresource covers (e.g. ``.status`` for
            the status subresource). If its ``metadata.resource_version`` is set
            (e.g. from a previous ``get()``), the request fails with
            ``409 Conflict`` when the resource has changed since that version.
        namespace: The namespace of the namespaced resource. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this request sets.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ResourceType: the full resource after the update, as stored by the API
            server.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist.
        Conflict: the resource has changed since the ``metadata.resource_version``
            that was sent.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PostOptions(dry_run=dry_run, field_manager=field_manager)
    request = self._request_builder.replace_subresource(
        self._subresource,
        name,
        _namespace,
        data=data.model_dump_json(by_alias=True, exclude_none=True),
        options=options,
        request_timeout=request_timeout,
    )
    response = await self._client.request(request)
    return self._resource_type.model_validate_json(response.content)

Exec subresource

kubex.api._exec

ExecAccessor

ExecAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
    channel_protocols: tuple[
        ChannelProtocol, ...
    ] = DEFAULT_PROTOCOLS,
)

Bases: Generic[ResourceType]

Accessor for the Pod exec subresource.

.. warning::

Experimental. The WebSocket-based subresources (exec, attach, portforward) are still under active development and their API may change in future releases without notice.

Source code in kubex/api/_exec.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
    channel_protocols: tuple[ChannelProtocol, ...] = DEFAULT_PROTOCOLS,
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type
    self._channel_protocols = channel_protocols

run async

run(
    name: str,
    *,
    command: Sequence[str],
    container: str | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
    stdin: bytes | None = None,
    stdout: bool = True,
    stderr: bool = True,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ExecResult

Run a command and collect stdout/stderr until the channel closes.

.. warning::

Experimental. This WebSocket-based API is still under active development and may change in future releases without notice.

Unlike :meth:stream, the request_timeout bound (when provided) applies to both the handshake (via the per-call HTTP timeout propagated to the WebSocket upgrade) and the post-handshake command execution + status collection (via a separate wall-clock cancel scope that does not envelope teardown — see below). The wall-clock bound is derived from Timeout.total if set, otherwise Timeout.read (read's strict per-byte-inactivity semantics do not map cleanly onto a long-lived WebSocket session, so it is treated as a call-level upper bound here as a pragmatic approximation that prevents indefinite hangs). Ellipsis defers to the client default for the handshake without imposing an additional wall-clock bound; an explicit None disables timeouts entirely.

stdin is sent in frames of at most 32 KiB and then half-closed. A failure while sending it (e.g. the command exited without reading all of it) is logged, not raised: the result reflects what the server reported. Use :meth:ExecResult.raise_for_status to turn a non-successful status into an exception.

Parameters:

Name Type Description Default
name str

The name of the Pod to run the command in.

required
command Sequence[str]

The command and its arguments, e.g. ["cat", "/etc/hostname"]. Must be a non-empty sequence of strings, not a single string.

required
container str | None

The container to run the command in. Required when the Pod has more than one container.

None
namespace ApiNamespaceTypes

The namespace of the Pod. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
stdin bytes | None

Bytes to send to the command's stdin, which is then closed. None (the default) does not open a stdin channel at all; b"" opens it and closes it right away.

None
stdout bool

Capture stdout.

True
stderr bool

Capture stderr.

True
request_timeout ApiRequestTimeoutTypes

Timeout override for this call, bounding both the handshake and the command's run; see above. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely. Omit to use the client default for the handshake only.

Ellipsis

Returns:

Name Type Description
ExecResult ExecResult

the captured stdout and stderr bytes and the status the server reported (None if it reported none).

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one; or command is empty.

TypeError

command is a single string (or bytes) instead of a sequence of strings, or contains a non-string item.

KubexApiError

the WebSocket handshake was rejected; the subclass matches the HTTP status (e.g. NotFound for a missing pod, BadRequest for an unknown container, Forbidden).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the WebSocket handshake or the command did not finish within request_timeout.

KubexClientException

the WebSocket handshake failed for another reason, or the connection closed abnormally.

ConfigurationError

credentials could not be obtained, or the httpx client is used without the httpx-ws extra installed.

Source code in kubex/api/_exec.py
async def run(
    self,
    name: str,
    *,
    command: Sequence[str],
    container: str | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
    stdin: bytes | None = None,
    stdout: bool = True,
    stderr: bool = True,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ExecResult:
    """Run a command and collect stdout/stderr until the channel closes.

    .. warning::

       **Experimental.** This WebSocket-based API is still under active
       development and may change in future releases without notice.

    Unlike :meth:`stream`, the ``request_timeout`` bound (when provided)
    applies to both the handshake (via the per-call HTTP timeout
    propagated to the WebSocket upgrade) and the post-handshake command
    execution + status collection (via a separate wall-clock cancel scope
    that does not envelope teardown — see below). The wall-clock bound is
    derived from ``Timeout.total`` if set, otherwise ``Timeout.read``
    (read's strict per-byte-inactivity semantics do not map cleanly onto
    a long-lived WebSocket session, so it is treated as a call-level
    upper bound here as a pragmatic approximation that prevents
    indefinite hangs). ``Ellipsis`` defers to the client default for the
    handshake without imposing an additional wall-clock bound; an
    explicit ``None`` disables timeouts entirely.

    ``stdin`` is sent in frames of at most 32 KiB and then half-closed. A
    failure while sending it (e.g. the command exited without reading
    all of it) is logged, not raised: the result reflects what the
    server reported. Use :meth:`ExecResult.raise_for_status` to turn a
    non-successful status into an exception.

    Args:
        name: The name of the Pod to run the command in.
        command: The command and its arguments, e.g. ``["cat", "/etc/hostname"]``.
            Must be a non-empty sequence of strings, not a single string.
        container: The container to run the command in. Required when the Pod
            has more than one container.
        namespace: The namespace of the Pod. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        stdin: Bytes to send to the command's stdin, which is then closed.
            ``None`` (the default) does not open a stdin channel at all;
            ``b""`` opens it and closes it right away.
        stdout: Capture stdout.
        stderr: Capture stderr.
        request_timeout: Timeout override for this call, bounding both the
            handshake and the command's run; see above. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to
            disable timeouts entirely. Omit to use the client default for the
            handshake only.

    Returns:
        ExecResult: the captured ``stdout`` and ``stderr`` bytes and the
            ``status`` the server reported (``None`` if it reported none).

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one; or ``command`` is empty.
        TypeError: ``command`` is a single string (or bytes) instead of a
            sequence of strings, or contains a non-string item.
        KubexApiError: the WebSocket handshake was rejected; the subclass matches
            the HTTP status (e.g. ``NotFound`` for a missing pod, ``BadRequest``
            for an unknown container, ``Forbidden``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the WebSocket handshake or the command did not finish
            within ``request_timeout``.
        KubexClientException: the WebSocket handshake failed for another reason,
            or the connection closed abnormally.
        ConfigurationError: credentials could not be obtained, or the httpx
            client is used without the ``httpx-ws`` extra installed.
    """
    # Resolve the wall-clock bound for the post-handshake portion.
    # ``Ellipsis`` and a ``Timeout`` whose ``total`` and ``read`` are
    # both unset leave ``delay`` as ``None`` — ``anyio.fail_after(None)``
    # is a no-op cancel scope, so the only bound on the call in those
    # cases is whatever the handshake timeout enforces (set via
    # ``request_timeout`` propagation below).
    delay: float | None = None
    if request_timeout is not Ellipsis:
        coerced: Timeout | None = Timeout.coerce(request_timeout)
        if coerced is not None:
            delay = coerced.total if coerced.total is not None else coerced.read

    # The handshake is bounded by ``request_timeout`` propagation into
    # the per-backend WebSocket upgrade (see ``HttpxClient`` /
    # ``AioHttpClient``). The wall-clock ``fail_after`` below covers
    # only the post-handshake portion — keeping it *inside* the
    # ``async with session`` block ensures ``StreamSession.__aexit__``
    # (and the underlying ``connection.close()``) runs in an
    # un-cancelled scope so the HTTP/WebSocket transport is always
    # released, even when the deadline fires mid-call.
    session = await self._open_session(
        name,
        command=command,
        container=container,
        namespace=namespace,
        stdin=stdin is not None,
        stdout=stdout,
        stderr=stderr,
        tty=False,
        request_timeout=request_timeout,
    )
    stdout_buf = bytearray()
    stderr_buf = bytearray()
    status: Status | None = None
    async with session:

        async def _drain(
            stream: MemoryObjectReceiveStream[bytes], buf: bytearray
        ) -> None:
            async for chunk in stream:
                buf.extend(chunk)

        async def _write_stdin(data: bytes) -> None:
            # Like client-go, a failed stdin copy does not decide the
            # outcome: the command may have exited without reading all
            # of its input, and the read side still reports its status.
            # A broken connection surfaces there as well.
            try:
                await session.stdin.write(data)
                await session.close_stdin()
            except Exception as exc:
                _logger.debug("exec stdin write failed: %r", exc)

        # ``anyio.fail_after`` raises a bare ``TimeoutError`` at scope
        # exit when the deadline fires. The exec layer normalises every
        # other WebSocket-level failure to ``KubexClientException``
        # (see ``_resolve_protocol`` and the per-backend handshake
        # handlers), so convert here too — callers that
        # ``except KubexClientException`` for exec errors must observe
        # a timed-out ``run()`` consistently.
        try:
            with anyio.fail_after(delay):
                async with anyio.create_task_group() as tg:
                    if stdin is not None:
                        tg.start_soon(_write_stdin, stdin)
                    # Both channels are drained concurrently: the read
                    # loop waits for a full channel, so draining only one
                    # could stall the session.
                    async with anyio.create_task_group() as readers:
                        readers.start_soon(_drain, session.stdout, stdout_buf)
                        readers.start_soon(_drain, session.stderr, stderr_buf)
                    status = await session.wait_for_status()
                    # The command has finished; unsent stdin is moot.
                    tg.cancel_scope.cancel()
        except TimeoutError as exc:
            raise KubexTimeoutError(
                f"exec call exceeded {delay}s wall-clock bound"
            ) from exc
        except BaseExceptionGroup as eg:
            # anyio 4 wraps exceptions raised by tasks in a task group
            # in a ``BaseExceptionGroup`` even when only a single task
            # failed. Unwrap a single-exception group so callers that
            # catch ``KubexClientException`` (the documented exec
            # exception type) observe failures directly instead of
            # having to reach into an exception group.
            if len(eg.exceptions) == 1:
                raise eg.exceptions[0] from None
            raise
    return ExecResult(
        stdout=bytes(stdout_buf), stderr=bytes(stderr_buf), status=status
    )

stream async

stream(
    name: str,
    *,
    command: Sequence[str],
    container: str | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
    stdin: bool = False,
    stdout: bool = True,
    stderr: bool = True,
    tty: bool = False,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[StreamSession]

Open a bidirectional exec session as an async context manager.

.. warning::

Experimental. This WebSocket-based API is still under active development and may change in future releases without notice.

Output is never dropped: a channel whose consumer falls behind pauses the whole session (backpressure). Drain every enabled output channel concurrently, or disable the ones you don't need (e.g. stderr=False).

Leaving the async with block closes the session, even while the command is still running.

Parameters:

Name Type Description Default
name str

The name of the Pod to run the command in.

required
command Sequence[str]

The command and its arguments, e.g. ["sh", "-c", "ls"]. Must be a non-empty sequence of strings, not a single string.

required
container str | None

The container to run the command in. Required when the Pod has more than one container.

None
namespace ApiNamespaceTypes

The namespace of the Pod. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
stdin bool

Open the stdin channel, for writing with session.stdin.

False
stdout bool

Open the stdout channel.

True
stderr bool

Open the stderr channel. Ignored with tty=True.

True
tty bool

Allocate a pseudo-terminal. The kubelet then merges stderr into stdout, so session.stderr closes immediately.

False
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for the WebSocket handshake. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely. Omit to use the client default. It does not bound the session itself.

Ellipsis

Yields:

Name Type Description
StreamSession AsyncIterator[StreamSession]

the open session, with stdin, stdout, stderr, resize(), close_stdin() and wait_for_status().

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one; or command is empty.

TypeError

command is a single string (or bytes) instead of a sequence of strings, or contains a non-string item.

KubexApiError

the WebSocket handshake was rejected; the subclass matches the HTTP status (e.g. NotFound for a missing pod, BadRequest for an unknown container, Forbidden).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the WebSocket handshake timed out.

KubexClientException

the WebSocket handshake failed for another reason, or the connection closed abnormally.

ConfigurationError

credentials could not be obtained, or the httpx client is used without the httpx-ws extra installed.

Source code in kubex/api/_exec.py
@asynccontextmanager
async def stream(
    self,
    name: str,
    *,
    command: Sequence[str],
    container: str | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
    stdin: bool = False,
    stdout: bool = True,
    stderr: bool = True,
    tty: bool = False,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[StreamSession]:
    """Open a bidirectional exec session as an async context manager.

    .. warning::

       **Experimental.** This WebSocket-based API is still under active
       development and may change in future releases without notice.

    Output is never dropped: a channel whose consumer falls behind pauses
    the whole session (backpressure). Drain every enabled output channel
    concurrently, or disable the ones you don't need (e.g.
    ``stderr=False``).

    Leaving the ``async with`` block closes the session, even while the
    command is still running.

    Args:
        name: The name of the Pod to run the command in.
        command: The command and its arguments, e.g. ``["sh", "-c", "ls"]``.
            Must be a non-empty sequence of strings, not a single string.
        container: The container to run the command in. Required when the Pod
            has more than one container.
        namespace: The namespace of the Pod. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        stdin: Open the stdin channel, for writing with ``session.stdin``.
        stdout: Open the stdout channel.
        stderr: Open the stderr channel. Ignored with ``tty=True``.
        tty: Allocate a pseudo-terminal. The kubelet then merges stderr into
            stdout, so ``session.stderr`` closes immediately.
        request_timeout: HTTP-level timeout override for the WebSocket
            handshake. A number is interpreted as the total timeout in
            seconds. Pass ``None`` to disable timeouts entirely. Omit to use
            the client default. It does not bound the session itself.

    Yields:
        StreamSession: the open session, with ``stdin``, ``stdout``,
            ``stderr``, ``resize()``, ``close_stdin()`` and
            ``wait_for_status()``.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one; or ``command`` is empty.
        TypeError: ``command`` is a single string (or bytes) instead of a
            sequence of strings, or contains a non-string item.
        KubexApiError: the WebSocket handshake was rejected; the subclass matches
            the HTTP status (e.g. ``NotFound`` for a missing pod, ``BadRequest``
            for an unknown container, ``Forbidden``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the WebSocket handshake timed out.
        KubexClientException: the WebSocket handshake failed for another reason,
            or the connection closed abnormally.
        ConfigurationError: credentials could not be obtained, or the httpx
            client is used without the ``httpx-ws`` extra installed.
    """
    session = await self._open_session(
        name,
        command=command,
        container=container,
        namespace=namespace,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        tty=tty,
        request_timeout=request_timeout,
    )
    async with session:
        yield session

ExecError

ExecError(message: str, result: ExecResult)

Bases: KubexClientException

Raised by :meth:ExecResult.raise_for_status when a command did not succeed.

The message is the server's Status.message when there is one; the full result (output, status, exit_code) is available as result.

Source code in kubex/api/_exec.py
def __init__(self, message: str, result: ExecResult) -> None:
    super().__init__(message)
    self.result = result

exit_code property

exit_code: int | None

The failed command's exit code, or None; see :attr:ExecResult.exit_code.

status property

status: Status | None

The failed command's Status, or None if none was reported.

ExecResult dataclass

ExecResult(
    stdout: bytes,
    stderr: bytes,
    status: Status | None = None,
)

Result of a one-shot ExecAccessor.run call.

exit_code property

exit_code: int | None

Parse the exit code from status.

Returns 0 for a Success status, the integer parsed from status.details.causes (where reason == "ExitCode") for a non-zero exit, or None when status is missing or carries no recognisable exit information. Note that None does not imply success — for failures without a recognisable exit code (e.g. the container could not start), inspect status directly, or call :meth:raise_for_status.

raise_for_status

raise_for_status() -> Self

Raise :class:ExecError unless the command reported Success.

Covers non-zero exits as well as failures without an exit code (e.g. the binary does not exist) and a missing status. Returns self so it can be chained: (await api.exec.run(...)).raise_for_status().

Returns:

Name Type Description
Self Self

this result, unchanged, when the status is Success.

Raises:

Type Description
ExecError

the status is missing or is not Success. Its message is the server's Status.message (or reason) when there is one.

Source code in kubex/api/_exec.py
def raise_for_status(self) -> Self:
    """Raise :class:`ExecError` unless the command reported ``Success``.

    Covers non-zero exits as well as failures without an exit code (e.g.
    the binary does not exist) and a missing status. Returns ``self`` so
    it can be chained: ``(await api.exec.run(...)).raise_for_status()``.

    Returns:
        Self: this result, unchanged, when the status is ``Success``.

    Raises:
        ExecError: the status is missing or is not ``Success``. Its message is
            the server's ``Status.message`` (or ``reason``) when there is one.
    """
    status = self.status
    if status is not None and status.status == "Success":
        return self
    if status is None:
        message = "exec finished without reporting a status"
    else:
        message = status.message or status.reason or "exec failed"
    raise ExecError(message, self)

Attach subresource

kubex.api._attach

AttachAccessor

AttachAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
    *,
    channel_protocols: tuple[
        ChannelProtocol, ...
    ] = DEFAULT_PROTOCOLS,
)

Bases: Generic[ResourceType]

Accessor for the Pod attach subresource.

.. warning::

Experimental. The WebSocket-based subresources (exec, attach, portforward) are still under active development and their API may change in future releases without notice.

Source code in kubex/api/_attach.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
    *,
    channel_protocols: tuple[ChannelProtocol, ...] = DEFAULT_PROTOCOLS,
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type
    self._channel_protocols = channel_protocols

stream async

stream(
    name: str,
    *,
    container: str | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
    stdin: bool = False,
    stdout: bool = True,
    stderr: bool = True,
    tty: bool = False,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[StreamSession]

Open a bidirectional attach session as an async context manager.

.. warning::

Experimental. This WebSocket-based API is still under active development and may change in future releases without notice.

Output is never dropped: a channel whose consumer falls behind pauses the whole session (backpressure). Drain every enabled output channel concurrently, or disable the ones you don't need (e.g. stderr=False).

Attaches to the container's existing main process; no new command is started. Leaving the async with block closes the session.

Parameters:

Name Type Description Default
name str

The name of the Pod to attach to.

required
container str | None

The container to attach to. Required when the Pod has more than one container.

None
namespace ApiNamespaceTypes

The namespace of the Pod. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
stdin bool

Attach to the process's stdin, for writing with session.stdin.

False
stdout bool

Attach to the process's stdout.

True
stderr bool

Attach to the process's stderr. Ignored with tty=True.

True
tty bool

Attach as a terminal. The kubelet then merges stderr into stdout, so session.stderr closes immediately.

False
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for the WebSocket handshake. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely. Omit to use the client default. It does not bound the session itself.

Ellipsis

Yields:

Name Type Description
StreamSession AsyncIterator[StreamSession]

the open session, with stdin, stdout, stderr, resize(), close_stdin() and wait_for_status().

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one.

KubexApiError

the WebSocket handshake was rejected; the subclass matches the HTTP status (e.g. NotFound for a missing pod, BadRequest for an unknown container, Forbidden).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the WebSocket handshake timed out.

KubexClientException

the WebSocket handshake failed for another reason, or the connection closed abnormally.

ConfigurationError

credentials could not be obtained, or the httpx client is used without the httpx-ws extra installed.

Source code in kubex/api/_attach.py
@asynccontextmanager
async def stream(
    self,
    name: str,
    *,
    container: str | None = None,
    namespace: ApiNamespaceTypes = Ellipsis,
    stdin: bool = False,
    stdout: bool = True,
    stderr: bool = True,
    tty: bool = False,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[StreamSession]:
    """Open a bidirectional attach session as an async context manager.

    .. warning::

       **Experimental.** This WebSocket-based API is still under active
       development and may change in future releases without notice.

    Output is never dropped: a channel whose consumer falls behind pauses
    the whole session (backpressure). Drain every enabled output channel
    concurrently, or disable the ones you don't need (e.g.
    ``stderr=False``).

    Attaches to the container's existing main process; no new command is
    started. Leaving the ``async with`` block closes the session.

    Args:
        name: The name of the Pod to attach to.
        container: The container to attach to. Required when the Pod has more
            than one container.
        namespace: The namespace of the Pod. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        stdin: Attach to the process's stdin, for writing with ``session.stdin``.
        stdout: Attach to the process's stdout.
        stderr: Attach to the process's stderr. Ignored with ``tty=True``.
        tty: Attach as a terminal. The kubelet then merges stderr into stdout,
            so ``session.stderr`` closes immediately.
        request_timeout: HTTP-level timeout override for the WebSocket
            handshake. A number is interpreted as the total timeout in
            seconds. Pass ``None`` to disable timeouts entirely. Omit to use
            the client default. It does not bound the session itself.

    Yields:
        StreamSession: the open session, with ``stdin``, ``stdout``,
            ``stderr``, ``resize()``, ``close_stdin()`` and
            ``wait_for_status()``.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one.
        KubexApiError: the WebSocket handshake was rejected; the subclass matches
            the HTTP status (e.g. ``NotFound`` for a missing pod, ``BadRequest``
            for an unknown container, ``Forbidden``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the WebSocket handshake timed out.
        KubexClientException: the WebSocket handshake failed for another reason,
            or the connection closed abnormally.
        ConfigurationError: credentials could not be obtained, or the httpx
            client is used without the ``httpx-ws`` extra installed.
    """
    session = await self._open_session(
        name,
        container=container,
        namespace=namespace,
        stdin=stdin,
        stdout=stdout,
        stderr=stderr,
        tty=tty,
        request_timeout=request_timeout,
    )
    async with session:
        yield session

Portforward subresource

kubex.api._portforward

PortForwardStream

PortForwardStream(
    session: PortForwardSession,
    port: int,
    data_channel_id: int,
    recv_stream: MemoryObjectReceiveStream[bytes],
)

Bases: ByteStream

Per-port bidirectional byte stream for the Kubernetes portforward subresource.

Wraps a PortForwardSession's data channel for a single port and implements anyio.abc.ByteStream so it integrates naturally with anyio byte-stream consumers.

Outbound send() encodes the payload as a channel frame addressed to the port's data channel. Inbound receive() reads from the session's per-port memory stream, buffering excess bytes to satisfy max_bytes slicing.

aclose() half-closes the data channel (idempotent via the underlying session helper) and prevents further send() calls. send_eof() performs the same half-close without locking out receives. On the v4 portforward subprotocol — which the kubelet requires — half-close is a local-only state change; the kubelet ignores wire CHANNEL_CLOSE frames on v4 and tears down the channel only when the session WebSocket closes.

Source code in kubex/api/_portforward.py
def __init__(
    self,
    session: PortForwardSession,
    port: int,
    data_channel_id: int,
    recv_stream: MemoryObjectReceiveStream[bytes],
) -> None:
    self._session = session
    self._port = port
    self._data_channel_id = data_channel_id
    self._recv_stream = recv_stream
    self._buffer = b""
    self._send_closed = False
    # Keeps the frames of one ``send()`` contiguous and orders them
    # against ``send_eof()`` / ``aclose()``.
    self._send_lock = anyio.Lock()

aclose async

aclose() -> None

Close both directions of the stream.

The sending side is closed as by send_eof(). On the receiving side, receive() raises anyio.EndOfStream once any bytes left over from a partly read frame are returned, and data that arrives for this port afterwards is discarded, so an unread port no longer stalls the others. The session and its other ports stay open.

Source code in kubex/api/_portforward.py
async def aclose(self) -> None:
    """Close both directions of the stream.

    The sending side is closed as by ``send_eof()``. On the receiving side,
    ``receive()`` raises ``anyio.EndOfStream`` once any bytes left over from a
    partly read frame are returned, and data that arrives for this port
    afterwards is discarded, so an unread port no longer stalls the others.
    The session and its other ports stay open.
    """
    async with self._send_lock:
        self._send_closed = True
    try:
        await self._session.close_port_data(self._port)
    finally:
        self._recv_stream.close()

receive async

receive(max_bytes: int = 65536) -> bytes

Receive bytes from the remote port, waiting until some arrive.

A frame larger than max_bytes is returned over several calls.

Parameters:

Name Type Description Default
max_bytes int

The maximum number of bytes to return.

65536

Returns:

Name Type Description
bytes bytes

between 1 and max_bytes bytes received from the pod.

Raises:

Type Description
ValueError

max_bytes is not positive.

EndOfStream

no more data will arrive: the kubelet closed the port's data channel, the session ended, or this stream was closed with aclose().

Source code in kubex/api/_portforward.py
async def receive(self, max_bytes: int = 65536) -> bytes:
    """Receive bytes from the remote port, waiting until some arrive.

    A frame larger than ``max_bytes`` is returned over several calls.

    Args:
        max_bytes: The maximum number of bytes to return.

    Returns:
        bytes: between 1 and ``max_bytes`` bytes received from the pod.

    Raises:
        ValueError: ``max_bytes`` is not positive.
        anyio.EndOfStream: no more data will arrive: the kubelet closed the
            port's data channel, the session ended, or this stream was closed
            with ``aclose()``.
    """
    if max_bytes <= 0:
        raise ValueError(f"max_bytes must be positive, got {max_bytes}")
    while not self._buffer:
        try:
            self._buffer = await self._recv_stream.receive()
        except (anyio.ClosedResourceError, anyio.EndOfStream):
            raise anyio.EndOfStream()
    data = self._buffer[:max_bytes]
    self._buffer = self._buffer[max_bytes:]
    return data

send async

send(item: bytes) -> None

Send item to the remote port, split into frames of at most 32 KiB.

Parameters:

Name Type Description Default
item bytes

The bytes to send.

required

Raises:

Type Description
ClosedResourceError

send_eof() or aclose() was called.

KubexClientException

the session has already ended.

Source code in kubex/api/_portforward.py
async def send(self, item: bytes) -> None:
    """Send ``item`` to the remote port, split into frames of at most 32 KiB.

    Args:
        item: The bytes to send.

    Raises:
        anyio.ClosedResourceError: ``send_eof()`` or ``aclose()`` was called.
        KubexClientException: the session has already ended.
    """
    # The closed-flag check happens under the same lock that
    # send_eof()/aclose() take, so no data frame can follow a half-close.
    async with self._send_lock:
        if self._send_closed:
            raise anyio.ClosedResourceError("stream send side is closed")
        await self._session._send_data(self._data_channel_id, item)

send_eof async

send_eof() -> None

Close the sending side of the stream; receive() keeps working.

Later send() calls raise anyio.ClosedResourceError; calling this again is a no-op. On the v4 portforward protocol (the only one the kubelet supports) nothing is sent on the wire: the pod is not told about the EOF and only sees the connection end when the session's WebSocket closes.

Source code in kubex/api/_portforward.py
async def send_eof(self) -> None:
    """Close the sending side of the stream; ``receive()`` keeps working.

    Later ``send()`` calls raise ``anyio.ClosedResourceError``; calling this
    again is a no-op. On the v4 portforward protocol (the only one the
    kubelet supports) nothing is sent on the wire: the pod is not told about
    the EOF and only sees the connection end when the session's WebSocket
    closes.
    """
    async with self._send_lock:
        self._send_closed = True
    await self._session.close_port_data(self._port)

PortForwarder

PortForwarder(session: PortForwardSession)

Holds an active portforward session and exposes per-port streams and errors.

streams[port] is a PortForwardStream (anyio.abc.ByteStream) for sending and receiving raw bytes to/from the remote port. errors[port] is an async iterator of error-text strings sent by the kubelet on the error channel for that port.

All ports share one WebSocket and inbound data is never dropped: a port whose stream (or error iterator) is not read stalls every port once its queue is full. Read each forwarded port, or aclose() its stream.

Source code in kubex/api/_portforward.py
def __init__(self, session: PortForwardSession) -> None:
    self._session = session

errors property

errors: Mapping[int, MemoryObjectReceiveStream[str]]

Per-port async iterators of kubelet error messages, keyed by remote port.

port_data_truncated property

port_data_truncated: Mapping[int, bool]

Deprecated: always False for every port (data is no longer dropped).

port_error_truncated property

port_error_truncated: Mapping[int, bool]

Deprecated: always False for every port (errors are no longer dropped).

streams property

streams: Mapping[int, PortForwardStream]

Per-port byte streams (PortForwardStream), keyed by remote port.

PortforwardAccessor

PortforwardAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
    channel_protocols: tuple[
        ChannelProtocol, ...
    ] = PORTFORWARD_PROTOCOLS,
)

Bases: Generic[ResourceType]

Accessor for the Pod portforward subresource.

.. warning::

Experimental. The WebSocket-based subresources (exec, attach, portforward) are still under active development and their API may change in future releases without notice.

Source code in kubex/api/_portforward.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
    channel_protocols: tuple[ChannelProtocol, ...] = PORTFORWARD_PROTOCOLS,
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type
    self._channel_protocols = channel_protocols

forward async

forward(
    name: str,
    *,
    ports: Sequence[int],
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[PortForwarder]

Open portforward streams to the given ports as an async context manager.

.. warning::

Experimental. This WebSocket-based API is still under active development and may change in future releases without notice.

This is the low-level entry point: a single WebSocket multiplexes all requested ports, and the caller drives I/O directly in Python via per-port anyio.abc.ByteStream objects. No sockets are bound on the host — bytes never leave the process. Use this when your own code speaks to the pod (custom protocols, embedded clients, tests).

For the kubectl-style mode where external processes connect through a real local TCP port, use :meth:listen instead (which is built on top of this method).

Inbound data is never dropped; since the ports share one WebSocket, a port that is not read stalls all ports once its queue fills. Read every forwarded port (or aclose() the ones you don't need).

Parameters:

Name Type Description Default
name str

The name of the pod.

required
ports Sequence[int]

The pod ports to forward: 1 to 127 unique ports in 1..65535. Each becomes a key of streams and errors.

required
namespace ApiNamespaceTypes

The namespace of the pod. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for the WebSocket handshake. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely. Omit to use the client default. It does not bound the session itself.

Ellipsis

Yields:

Name Type Description
PortForwarder AsyncIterator[PortForwarder]

the per-port byte streams (pf.streams[port]) and error iterators (pf.errors[port]). The session's WebSocket is closed when the async with block exits.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one; or ports is empty, has duplicates or more than 127 entries, or a port is outside 1..65535.

TypeError

a port is not an int.

KubexApiError

the WebSocket handshake was rejected; the subclass matches the HTTP status (e.g. NotFound for a missing pod, Forbidden).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the WebSocket handshake timed out.

KubexClientException

the WebSocket handshake failed for another reason, or the connection closed abnormally.

ConfigurationError

credentials could not be obtained, or the httpx client is used without the httpx-ws extra installed.

Source code in kubex/api/_portforward.py
@asynccontextmanager
async def forward(
    self,
    name: str,
    *,
    ports: Sequence[int],
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[PortForwarder]:
    """Open portforward streams to the given ports as an async context manager.

    .. warning::

       **Experimental.** This WebSocket-based API is still under active
       development and may change in future releases without notice.

    This is the **low-level** entry point: a single WebSocket multiplexes
    all requested ports, and the caller drives I/O directly in Python via
    per-port ``anyio.abc.ByteStream`` objects. No sockets are bound on the
    host — bytes never leave the process. Use this when your own code
    speaks to the pod (custom protocols, embedded clients, tests).

    For the kubectl-style mode where external processes connect through
    a real local TCP port, use :meth:`listen` instead (which is built on
    top of this method).

    Inbound data is never dropped; since the ports share one WebSocket, a
    port that is not read stalls all ports once its queue fills. Read
    every forwarded port (or ``aclose()`` the ones you don't need).

    Args:
        name: The name of the pod.
        ports: The pod ports to forward: 1 to 127 unique ports in 1..65535.
            Each becomes a key of ``streams`` and ``errors``.
        namespace: The namespace of the pod. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        request_timeout: HTTP-level timeout override for the WebSocket
            handshake. A number is interpreted as the total timeout in
            seconds. Pass ``None`` to disable timeouts entirely. Omit to use
            the client default. It does not bound the session itself.

    Yields:
        PortForwarder: the per-port byte streams (``pf.streams[port]``) and
            error iterators (``pf.errors[port]``). The session's WebSocket is
            closed when the ``async with`` block exits.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one; or ``ports`` is empty,
            has duplicates or more than 127 entries, or a port is outside
            1..65535.
        TypeError: a port is not an ``int``.
        KubexApiError: the WebSocket handshake was rejected; the subclass matches
            the HTTP status (e.g. ``NotFound`` for a missing pod, ``Forbidden``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the WebSocket handshake timed out.
        KubexClientException: the WebSocket handshake failed for another reason,
            or the connection closed abnormally.
        ConfigurationError: credentials could not be obtained, or the httpx
            client is used without the ``httpx-ws`` extra installed.
    """
    session = await self._open_session(
        name,
        ports=ports,
        namespace=namespace,
        request_timeout=request_timeout,
    )
    async with session:
        yield PortForwarder(session)

listen async

listen(
    name: str,
    *,
    port_map: Mapping[int, int],
    local_host: str = "127.0.0.1",
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[None]

Open local TCP listeners and forward bytes bidirectionally to remote ports.

.. warning::

Experimental. This WebSocket-based API is still under active development and may change in future releases without notice.

This is the high-level, kubectl-style entry point: real OS sockets are bound on local_host:local_port so that any process on the host (curl, psql, a browser, …) can connect to the pod through a local port. Each accepted local connection opens its own portforward WebSocket session bound to that single remote port — one session per connection, matching kubectl port-forward semantics. The method itself yields None; you don't drive I/O through it.

For the low-level mode where your own Python code reads/writes bytes directly without binding any sockets, use :meth:forward instead (which this method is built on top of).

When the remote side finishes (or the kubelet reports an error), the local connection is closed; a local half-close (EOF) keeps the connection open until the remote response is complete. The v4 protocol cannot pass that EOF to the pod, so after a local client disconnects its connection stays open until the pod closes it or sends more data. Failures on individual connections (including a rejected WebSocket handshake) are logged to the kubex.portforward logger rather than raised.

Parameters:

Name Type Description Default
name str

The name of the pod.

required
port_map Mapping[int, int]

Maps each remote port (on the pod) to the local port to listen on. Example: {80: 18080} opens a local listener on port 18080 that forwards to the pod's port 80.

required
local_host str

The local address the listeners bind to. The default, 127.0.0.1, only accepts connections from this host.

'127.0.0.1'
namespace ApiNamespaceTypes

The namespace of the pod. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for the WebSocket handshake of each accepted connection. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely. Omit to use the client default. It does not bound the connections themselves.

Ellipsis

Yields:

Name Type Description
None AsyncIterator[None]

the listeners stay open while the async with block runs; leaving it closes them and tears down open connections.

Raises:

Type Description
ValueError

port_map is empty, a port is outside 1..65535, or two remote ports map to the same local port.

TypeError

a port is not an int.

Source code in kubex/api/_portforward.py
@asynccontextmanager
async def listen(
    self,
    name: str,
    *,
    port_map: Mapping[int, int],
    local_host: str = "127.0.0.1",
    namespace: ApiNamespaceTypes = Ellipsis,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncIterator[None]:
    """Open local TCP listeners and forward bytes bidirectionally to remote ports.

    .. warning::

       **Experimental.** This WebSocket-based API is still under active
       development and may change in future releases without notice.

    This is the **high-level**, kubectl-style entry point: real OS sockets
    are bound on ``local_host:local_port`` so that any process on the host
    (``curl``, ``psql``, a browser, …) can connect to the pod through a
    local port. Each accepted local connection opens its own portforward
    WebSocket session bound to that single remote port — one session per
    connection, matching ``kubectl port-forward`` semantics. The method
    itself yields ``None``; you don't drive I/O through it.

    For the low-level mode where your own Python code reads/writes bytes
    directly without binding any sockets, use :meth:`forward` instead
    (which this method is built on top of).

    When the remote side finishes (or the kubelet reports an error), the
    local connection is closed; a local half-close (EOF) keeps the
    connection open until the remote response is complete. The v4
    protocol cannot pass that EOF to the pod, so after a local client
    disconnects its connection stays open until the pod closes it or
    sends more data. Failures on individual connections (including a
    rejected WebSocket handshake) are logged to the ``kubex.portforward``
    logger rather than raised.

    Args:
        name: The name of the pod.
        port_map: Maps each **remote port** (on the pod) to the **local port**
            to listen on. Example: ``{80: 18080}`` opens a local listener on
            port 18080 that forwards to the pod's port 80.
        local_host: The local address the listeners bind to. The default,
            ``127.0.0.1``, only accepts connections from this host.
        namespace: The namespace of the pod. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        request_timeout: HTTP-level timeout override for the WebSocket
            handshake of each accepted connection. A number is interpreted as
            the total timeout in seconds. Pass ``None`` to disable timeouts
            entirely. Omit to use the client default. It does not bound the
            connections themselves.

    Yields:
        None: the listeners stay open while the ``async with`` block runs;
            leaving it closes them and tears down open connections.

    Raises:
        ValueError: ``port_map`` is empty, a port is outside 1..65535, or two
            remote ports map to the same local port.
        TypeError: a port is not an ``int``.
    """
    if not port_map:
        raise ValueError("port_map must contain at least one entry")
    # Validate ports up front so a config error fails at context entry
    # instead of being deferred to the first incoming connection where
    # it would surface as a swallowed log line. Booleans are rejected
    # explicitly because ``bool`` is an ``int`` subclass — without this,
    # ``port_map={80: False}`` would silently bind port 0 (ephemeral),
    # which the caller has no way to discover since ``listen()`` yields
    # ``None``.
    for remote_port, local_port in port_map.items():
        if isinstance(remote_port, bool) or not isinstance(remote_port, int):
            raise TypeError(
                f"remote port must be int, got {type(remote_port).__name__}"
            )
        if not 1 <= remote_port <= 65535:
            raise ValueError(f"remote port {remote_port} out of range 1..65535")
        if isinstance(local_port, bool) or not isinstance(local_port, int):
            raise TypeError(
                f"local port must be int, got {type(local_port).__name__}"
            )
        if not 1 <= local_port <= 65535:
            raise ValueError(f"local port {local_port} out of range 1..65535")
    local_ports = list(port_map.values())
    if len(set(local_ports)) != len(local_ports):
        raise ValueError(f"duplicate local ports in port_map: {local_ports}")
    async with anyio.create_task_group() as tg:
        for remote_port, local_port in port_map.items():
            await tg.start(
                self._serve_port,
                name,
                remote_port,
                local_port,
                local_host,
                namespace,
                request_timeout,
            )
        try:
            yield
        finally:
            tg.cancel_scope.cancel()

Metadata accessor

kubex.api._metadata

MetadataAccessor

MetadataAccessor(
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
)

Bases: Generic[ResourceType]

Accessor for metadata subresource operations.

Source code in kubex/api/_metadata.py
def __init__(
    self,
    client: BaseClient,
    request_builder: RequestBuilder,
    namespace: NamespaceTypes,
    scope: Scope,
    resource_type: Type[ResourceType],
) -> None:
    self._client = client
    self._request_builder = request_builder
    self._namespace = namespace
    self._scope = scope
    self._resource_type = resource_type

get async

get(
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> PartialObjectMetadata

Read metadata of the specified resource.

Parameters:

Name Type Description Default
name str

The name of the resource to read.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to read. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
resource_version ResourceVersionTypes

The resource version to read. If not provided, the current resource version will be read. For details look at Resource Version Semantics documentation.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
PartialObjectMetadata PartialObjectMetadata

the resource's api_version, kind and metadata, without its spec or status.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, or a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one.

NotFound

the resource does not exist.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_metadata.py
async def get(
    self,
    name: str,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> PartialObjectMetadata:
    """Read metadata of the specified resource.

    Args:
        name: The name of the resource to read.
        namespace: The namespace of the namespaced resource to read. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        resource_version: The resource version to read. If not provided,
            the current resource version will be read. For details look at
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list).
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        PartialObjectMetadata: the resource's ``api_version``, ``kind`` and
            ``metadata``, without its spec or status.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            or a namespace that is missing for a namespace-scoped resource or
            given for a cluster-scoped one.
        NotFound: the resource does not exist.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = GetOptions(resource_version=resource_version)
    request = self._request_builder.get_metadata(
        name, _namespace, options=options, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return PartialObjectMetadata.model_validate_json(response.content)

list async

list(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ListEntity[PartialObjectMetadata]

List metadata of resources.

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace of the namespaced resources to list. If not provided, the namespace provided when creating the API will be used. Pass None to list across all namespaces. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
label_selector str | None

A selector to restrict the list of returned objects by their labels. For details look at Label Selectors documentation.

None
field_selector str | None

A selector to restrict the list of returned objects by their fields. For details look at Field Selectors documentation.

None
timeout_seconds int | None

Server-side timeout (in seconds) for the list/watch call; sent as the Kubernetes timeoutSeconds query parameter. For an HTTP client-side timeout, use request_timeout.

None
limit int | None

The maximum number of items to return. If more items match, the returned list's metadata.continue_ holds a token for the next page.

None
continue_token str | None

The metadata.continue_ token from the previous page, to fetch the next one. Pass the same filters as for that page.

None
version_match VersionMatchTypes

How the API server should interpret resource_version; sent as the Kubernetes resourceVersionMatch query parameter. See Resource Version Semantics documentation.

None
resource_version ResourceVersionTypes

The resource version to list. If not provided, the current resource version will be listed. For details look at Resource Version Semantics documentation.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Type Description
ListEntity[PartialObjectMetadata]

ListEntity[PartialObjectMetadata]: the metadata of the matching resources, with the list's metadata (resource_version, continue_).

Raises:

Type Description
ValueError

an argument is invalid, e.g. a namespace given for a cluster-scoped resource, or an unknown option value (e.g. for version_match).

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_metadata.py
async def list(
    self,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    timeout_seconds: int | None = None,
    limit: int | None = None,
    continue_token: str | None = None,
    version_match: VersionMatchTypes = None,
    resource_version: ResourceVersionTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> ListEntity[PartialObjectMetadata]:
    """List metadata of resources.

    Args:
        namespace: The namespace of the namespaced resources to list. If not provided,
            the namespace provided when creating the API will be used.
            Pass ``None`` to list across all namespaces.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        label_selector: A selector to restrict the list of returned objects by their labels.
            For details look at [Label Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors).
        field_selector: A selector to restrict the list of returned objects by their fields.
            For details look at [Field Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/).
        timeout_seconds: Server-side timeout (in seconds) for the list/watch call;
            sent as the Kubernetes ``timeoutSeconds`` query parameter. For an
            HTTP client-side timeout, use ``request_timeout``.
        limit: The maximum number of items to return. If more items match, the
            returned list's ``metadata.continue_`` holds a token for the next page.
        continue_token: The ``metadata.continue_`` token from the previous page,
            to fetch the next one. Pass the same filters as for that page.
        version_match: How the API server should interpret ``resource_version``; sent
            as the Kubernetes ``resourceVersionMatch`` query parameter. See
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list).
        resource_version: The resource version to list. If not provided,
            the current resource version will be listed. For details look at
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-get-and-list).
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        ListEntity[PartialObjectMetadata]: the metadata of the matching resources,
            with the list's ``metadata`` (``resource_version``, ``continue_``).

    Raises:
        ValueError: an argument is invalid, e.g. a namespace given for a
            cluster-scoped resource, or an unknown option value (e.g. for
            ``version_match``).
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_optional_namespace(namespace, self._namespace, self._scope)
    options = ListOptions(
        label_selector=label_selector,
        field_selector=field_selector,
        timeout_seconds=timeout_seconds,
        limit=limit,
        continue_token=continue_token,
        version_match=version_match,
        resource_version=resource_version,
    )
    request = self._request_builder.list_metadata(
        _namespace, options, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    model = PartialObjectMetadata.__RESOURCE_CONFIG__.list_model
    return model.model_validate_json(response.content)

patch async

patch(
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> PartialObjectMetadata

Patch metadata of the specified resource.

The patch is applied to the resource itself; only the response is reduced to its metadata.

Parameters:

Name Type Description Default
name str

The name of the resource to patch.

required
patch Patch

The patch to send, typically changing labels or annotations: ApplyPatch (server-side apply), MergePatch, StrategicMergePatch or JsonPatch. Its type sets the request's Content-Type. An ApplyPatch body is sent with the target resource's apiVersion and kind.

required
namespace ApiNamespaceTypes

The namespace of the namespaced resource to patch. If not provided, the namespace provided when creating the API will be used. The namespace is required for namespaced resources. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
dry_run DryRunTypes

Validate the request without persisting anything (True, "All" or DryRun.ALL).

None
field_manager str | None

The field manager name recorded in managedFields as the owner of the fields this patch sets. Required for ApplyPatch.

None
force bool | None

Take over fields currently owned by another field manager instead of failing with 409 Conflict. Only valid with ApplyPatch.

None
field_validation FieldValidationTypes

How the API server handles unknown or duplicate fields in the patch: "Strict" (reject the request), "Warn" (accept it with a warning; the server default) or "Ignore" (drop them silently). Also accepts the FieldValidation enum.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client default.

Ellipsis

Returns:

Name Type Description
PartialObjectMetadata PartialObjectMetadata

the patched resource's api_version, kind and metadata.

Raises:

Type Description
ValueError

an argument is invalid, e.g. an empty or malformed name, a namespace that is missing for a namespace-scoped resource or given for a cluster-scoped one, or an unknown option value (e.g. for dry_run).

NotFound

the resource does not exist (an ApplyPatch creates it instead).

Conflict

an ApplyPatch conflicts with fields owned by another field manager and force is not set.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached.

KubexTimeoutError

the request timed out on the client side.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_metadata.py
async def patch(
    self,
    name: str,
    patch: Patch,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    dry_run: DryRunTypes = None,
    field_manager: str | None = None,
    force: bool | None = None,
    field_validation: FieldValidationTypes = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> PartialObjectMetadata:
    """Patch metadata of the specified resource.

    The patch is applied to the resource itself; only the response is reduced
    to its metadata.

    Args:
        name: The name of the resource to patch.
        patch: The patch to send, typically changing labels or annotations:
            ``ApplyPatch`` (server-side apply), ``MergePatch``,
            ``StrategicMergePatch`` or ``JsonPatch``. Its type sets the request's
            ``Content-Type``. An ``ApplyPatch`` body is sent with the target
            resource's ``apiVersion`` and ``kind``.
        namespace: The namespace of the namespaced resource to patch. If not provided,
            the namespace provided when creating the API will be used.
            The namespace is required for namespaced resources.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        dry_run: Validate the request without persisting anything (``True``,
            ``"All"`` or ``DryRun.ALL``).
        field_manager: The field manager name recorded in ``managedFields`` as
            the owner of the fields this patch sets. Required for ``ApplyPatch``.
        force: Take over fields currently owned by another field manager instead
            of failing with ``409 Conflict``. Only valid with ``ApplyPatch``.
        field_validation: How the API server handles unknown or duplicate fields in
            the patch: ``"Strict"`` (reject the request), ``"Warn"`` (accept it
            with a warning; the server default) or ``"Ignore"`` (drop them
            silently). Also accepts the ``FieldValidation`` enum.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client default.

    Returns:
        PartialObjectMetadata: the patched resource's ``api_version``, ``kind``
            and ``metadata``.

    Raises:
        ValueError: an argument is invalid, e.g. an empty or malformed ``name``,
            a namespace that is missing for a namespace-scoped resource or given
            for a cluster-scoped one, or an unknown option value (e.g. for
            ``dry_run``).
        NotFound: the resource does not exist (an ``ApplyPatch`` creates it
            instead).
        Conflict: an ``ApplyPatch`` conflicts with fields owned by another field
            manager and ``force`` is not set.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached.
        KubexTimeoutError: the request timed out on the client side.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_required_namespace(namespace, self._namespace, self._scope)
    options = PatchOptions(
        dry_run=dry_run,
        field_manager=field_manager,
        force=force,
        field_validation=field_validation,
    )
    request = self._request_builder.patch_metadata(
        name, _namespace, options, patch, request_timeout=request_timeout
    )
    response = await self._client.request(request)
    return PartialObjectMetadata.model_validate_json(response.content)

watch async

watch(
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    allow_bookmarks: bool | None = None,
    send_initial_events: bool | None = None,
    resource_version: ResourceVersionTypes = None,
    timeout_seconds: int | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncGenerator[
    WatchEvent[PartialObjectMetadata], None
]

Watch for metadata changes of resources.

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace to watch. If not provided, the namespace provided when creating the API will be used. Pass None to watch all namespaces. If namespace is provided for cluster-scoped resources, an error will be raised.

Ellipsis
label_selector str | None

Only watch resources whose labels match this selector. For details look at Label Selectors documentation.

None
field_selector str | None

Only watch resources whose fields match this selector. For details look at Field Selectors documentation.

None
allow_bookmarks bool | None

Request periodic BOOKMARK events carrying a fresh resourceVersion. Defaults to True when send_initial_events is True (the server requires it); passing False together with send_initial_events=True raises ValueError.

None
send_initial_events bool | None

Start the stream with synthetic ADDED events for the current state, followed by a bookmark annotated with k8s.io/initial-events-end.

None
resource_version ResourceVersionTypes

Only deliver changes made after this resource version, e.g. the list metadata.resource_version from a previous list(). If not provided, the stream starts with synthetic ADDED events for every existing resource and then follows changes. For details look at Resource Version Semantics documentation.

None
timeout_seconds int | None

Server-side timeout (in seconds); the server ends the stream cleanly after it.

None
request_timeout ApiRequestTimeoutTypes

HTTP-level timeout override for this call. A number is interpreted as the total timeout in seconds. Pass None to disable timeouts entirely for this call. Omit to use the client's default for streams, which does not cut off an idle watch. An explicit short read/total timeout will terminate a quiet stream.

Ellipsis

Yields:

Type Description
AsyncGenerator[WatchEvent[PartialObjectMetadata], None]

WatchEvent[PartialObjectMetadata]: one event per change, with its type (ADDED, MODIFIED, DELETED or BOOKMARK) and object (the resource's metadata, or a Bookmark for BOOKMARK events). ERROR events are raised as exceptions instead.

Raises:

Type Description
ValueError

an argument is invalid, e.g. a namespace given for a cluster-scoped resource, or allow_bookmarks=False together with send_initial_events=True.

Gone

the requested resource_version is too old (HTTP 410), either on connect or as an ERROR event mid-stream; re-list and watch again from the new resourceVersion.

KubexApiError

the API server rejected the request; the subclass matches the HTTP status (e.g. Forbidden, UnprocessableEntity).

KubexConnectionError

the API server could not be reached, or the connection broke mid-stream.

KubexTimeoutError

the request timed out on the client side, including mid-stream.

ConfigurationError

credentials could not be obtained, e.g. an exec plugin or OIDC token refresh failed.

Source code in kubex/api/_metadata.py
async def watch(
    self,
    *,
    namespace: ApiNamespaceTypes = Ellipsis,
    label_selector: str | None = None,
    field_selector: str | None = None,
    allow_bookmarks: bool | None = None,
    send_initial_events: bool | None = None,
    resource_version: ResourceVersionTypes = None,
    timeout_seconds: int | None = None,
    request_timeout: ApiRequestTimeoutTypes = Ellipsis,
) -> AsyncGenerator[
    WatchEvent[PartialObjectMetadata],
    None,
]:
    """Watch for metadata changes of resources.

    Args:
        namespace: The namespace to watch. If not provided,
            the namespace provided when creating the API will be used.
            Pass ``None`` to watch all namespaces.
            If namespace is provided for cluster-scoped resources, an error will be raised.
        label_selector: Only watch resources whose labels match this selector.
            For details look at [Label Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors).
        field_selector: Only watch resources whose fields match this selector.
            For details look at [Field Selectors documentation](https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/).
        allow_bookmarks: Request periodic ``BOOKMARK`` events carrying a fresh
            ``resourceVersion``. Defaults to ``True`` when ``send_initial_events``
            is ``True`` (the server requires it); passing ``False`` together with
            ``send_initial_events=True`` raises ``ValueError``.
        send_initial_events: Start the stream with synthetic ``ADDED`` events for
            the current state, followed by a bookmark annotated with
            ``k8s.io/initial-events-end``.
        resource_version: Only deliver changes made after this resource version,
            e.g. the list ``metadata.resource_version`` from a previous
            ``list()``. If not provided, the stream starts with synthetic
            ``ADDED`` events for every existing resource and then follows
            changes. For details look at
            [Resource Version Semantics documentation](https://kubernetes.io/docs/reference/using-api/api-concepts/#semantics-for-watch).
        timeout_seconds: Server-side timeout (in seconds); the server ends the
            stream cleanly after it.
        request_timeout: HTTP-level timeout override for this call. A number is
            interpreted as the total timeout in seconds. Pass ``None`` to disable
            timeouts entirely for this call. Omit to use the client's default
            for streams, which does not cut off an idle watch. An explicit
            short read/total timeout will terminate a quiet stream.

    Yields:
        WatchEvent[PartialObjectMetadata]: one event per change, with its ``type``
            (``ADDED``, ``MODIFIED``, ``DELETED`` or ``BOOKMARK``) and ``object``
            (the resource's metadata, or a ``Bookmark`` for ``BOOKMARK`` events).
            ``ERROR`` events are raised as exceptions instead.

    Raises:
        ValueError: an argument is invalid, e.g. a namespace given for a
            cluster-scoped resource, or ``allow_bookmarks=False`` together
            with ``send_initial_events=True``.
        Gone: the requested ``resource_version`` is too old (HTTP 410), either
            on connect or as an ``ERROR`` event mid-stream; re-list and watch
            again from the new ``resourceVersion``.
        KubexApiError: the API server rejected the request; the subclass
            matches the HTTP status (e.g. ``Forbidden``, ``UnprocessableEntity``).
        KubexConnectionError: the API server could not be reached, or the
            connection broke mid-stream.
        KubexTimeoutError: the request timed out on the client side, including
            mid-stream.
        ConfigurationError: credentials could not be obtained, e.g. an exec
            plugin or OIDC token refresh failed.
    """
    _namespace = ensure_optional_namespace(namespace, self._namespace, self._scope)
    options = WatchOptions(
        label_selector=label_selector,
        field_selector=field_selector,
        allow_bookmarks=allow_bookmarks,
        send_initial_events=send_initial_events,
        timeout_seconds=timeout_seconds,
        resource_version=resource_version,
    )
    request = self._request_builder.watch_metadata(
        _namespace,
        options,
        request_timeout=request_timeout,
    )
    async for line in self._client.stream_lines(request):
        yield WatchEvent(PartialObjectMetadata, json.loads(line))

Stream session

kubex.api._stream_session

StreamSession

StreamSession(
    connection: WebSocketConnection,
    protocol: ChannelProtocol,
    *,
    stdin: bool = False,
    stdout: bool = True,
    stderr: bool = True,
    tty: bool = False,
    buffer_size: float = _DEFAULT_CHANNEL_BUFFER,
)

Bases: _BaseChannelSession

Multiplexes Kubernetes channel-protocol streams over a single :class:WebSocketConnection.

The session owns a background read loop that decodes incoming binary frames and dispatches their payloads to per-channel queues. Outgoing writes (stdin, resize, close_stdin) share a lock so concurrent callers do not interleave bytes on the underlying WebSocket.

Inbound data is never dropped: when stdout or stderr has buffer_size undelivered frames, the read loop waits for the consumer, which also holds back every other channel (including the status). Drain each enabled channel concurrently, disable the ones you don't need (stderr=False), or close a receive stream (session.stderr.close()) to discard it. Leaving the async with block always tears the session down promptly, even while the read loop is waiting.

Used by both the exec and attach subresource accessors.

Source code in kubex/api/_stream_session.py
def __init__(
    self,
    connection: WebSocketConnection,
    protocol: ChannelProtocol,
    *,
    stdin: bool = False,
    stdout: bool = True,
    stderr: bool = True,
    tty: bool = False,
    buffer_size: float = _DEFAULT_CHANNEL_BUFFER,
) -> None:
    super().__init__(connection, protocol)
    send_out, recv_out = anyio.create_memory_object_stream[bytes](
        max_buffer_size=buffer_size
    )
    send_err, recv_err = anyio.create_memory_object_stream[bytes](
        max_buffer_size=buffer_size
    )
    self._stdout_send: MemoryObjectSendStream[bytes] = send_out
    self._stdout_recv: MemoryObjectReceiveStream[bytes] = recv_out
    self._stderr_send: MemoryObjectSendStream[bytes] = send_err
    self._stderr_recv: MemoryObjectReceiveStream[bytes] = recv_err
    # Channels the kubelet will not open are closed locally up-front so
    # consumers iterating over ``stdout`` / ``stderr`` see an immediate
    # end-of-stream instead of blocking until socket teardown. The
    # kubelet merges stderr into stdout when ``tty=True`` and never
    # opens the dedicated stderr channel.
    self._stdout_open = stdout
    self._stderr_open = stderr and not tty
    if not self._stdout_open:
        self._stdout_send.close()
    if not self._stderr_open:
        self._stderr_send.close()
    self._status: Status | None = None
    self._status_event = anyio.Event()
    # Error-channel bytes collected until they form a complete Status
    # document (or the connection closes).
    self._error_buf = bytearray()
    self._stdin_enabled = stdin
    # When stdin is not enabled the channel was never opened, so writes
    # must fail locally and ``close_stdin`` must be a no-op (no CLOSE
    # frame on the wire for a channel that does not exist).
    self._stdin_closed = not stdin
    # Serialises stdin writes and the stdin half-close so one write's
    # frames stay contiguous; resize frames may still go in between.
    self._stdin_lock = anyio.Lock()
    self._stdin = _StdinWriter(self)

stderr property

stderr: MemoryObjectReceiveStream[bytes]

Stderr chunks as an async iterator; ends at once if disabled or with tty=True.

stderr_truncated property

stderr_truncated: bool

Deprecated: always False. See :attr:stdout_truncated.

stdin property

stdin: _StdinWriter

Writer for stdin: await stdin.write(data), await stdin.close().

write() sends the data in frames of at most 32 KiB and raises RuntimeError if stdin was not enabled or is already closed.

stdout property

stdout: MemoryObjectReceiveStream[bytes]

Stdout chunks as an async iterator; ends when the channel closes.

stdout_truncated property

stdout_truncated: bool

Deprecated: always False.

Output is no longer dropped when a consumer falls behind (the session applies backpressure instead), so there is nothing to report.

close_stdin async

close_stdin() -> None

Half-close stdin, signalling end-of-input to the process.

Idempotent, and a no-op when stdin was not enabled.

Raises:

Type Description
KubexClientException

stdin is still open but the session has already ended.

Source code in kubex/api/_stream_session.py
async def close_stdin(self) -> None:
    """Half-close stdin, signalling end-of-input to the process.

    Idempotent, and a no-op when stdin was not enabled.

    Raises:
        KubexClientException: stdin is still open but the session has
            already ended.
    """
    # Holding the stdin lock makes the check-then-send atomic with
    # respect to concurrent stdin writes, so no stdin frame can follow
    # the half-close on the wire. The flag is only set after the send
    # succeeds so a transient send failure leaves stdin open for retry.
    async with self._stdin_lock:
        if self._stdin_closed:
            return
        await self._send_frame(CHANNEL_CLOSE, bytes([CHANNEL_STDIN]))
        self._stdin_closed = True

resize async

resize(*, width: int, height: int) -> None

Send a terminal resize event.

Parameters:

Name Type Description Default
width int

The new terminal width in columns; must be positive.

required
height int

The new terminal height in rows; must be positive.

required

Raises:

Type Description
ValueError

width or height is not positive.

KubexClientException

the session has already ended.

Source code in kubex/api/_stream_session.py
async def resize(self, *, width: int, height: int) -> None:
    """Send a terminal resize event.

    Args:
        width: The new terminal width in columns; must be positive.
        height: The new terminal height in rows; must be positive.

    Raises:
        ValueError: ``width`` or ``height`` is not positive.
        KubexClientException: the session has already ended.
    """
    if width <= 0 or height <= 0:
        raise ValueError(
            f"resize requires positive width and height, got "
            f"width={width}, height={height}"
        )
    payload = json.dumps(
        {"Width": width, "Height": height}, separators=(",", ":")
    ).encode("utf-8")
    await self._send_frame(CHANNEL_RESIZE, payload)

wait_for_status async

wait_for_status() -> Status | None

Wait for the terminal Status from the error channel.

Resolves once a complete Status document has arrived, or when the connection closes; None means the server closed without sending one. The status only arrives after earlier frames have been delivered, so keep draining enabled output channels while waiting.

Returns:

Type Description
Status | None

Status | None: the reported Status; error-channel text that is not a valid Status becomes a Failure Status carrying it. None if the connection closed without any error-channel data.

Source code in kubex/api/_stream_session.py
async def wait_for_status(self) -> Status | None:
    """Wait for the terminal Status from the error channel.

    Resolves once a complete Status document has arrived, or when the
    connection closes; ``None`` means the server closed without sending
    one. The status only arrives after earlier frames have been
    delivered, so keep draining enabled output channels while waiting.

    Returns:
        Status | None: the reported ``Status``; error-channel text that is not
            a valid Status becomes a ``Failure`` Status carrying it. ``None``
            if the connection closed without any error-channel data.
    """
    await self._status_event.wait()
    return self._status

Portforward session

kubex.api._portforward_session

PortForwardSession

PortForwardSession(
    connection: WebSocketConnection,
    protocol: ChannelProtocol,
    ports: Sequence[int],
    *,
    buffer_size: float = _DEFAULT_CHANNEL_BUFFER,
)

Bases: _BaseChannelSession

Port-aware WebSocket channel multiplexer for the Kubernetes portforward subresource.

Inherits lifecycle management (write lock, exit stack, task group) from _BaseChannelSession. Each port gets a data MemoryObjectStream[bytes] and an error MemoryObjectStream[str]. The first frame on each channel carries a 2-byte little-endian port-number prefix which is stripped and validated; subsequent frames are routed as raw bytes (data) or UTF-8 text (error) without any prefix.

When a port's data (or error) queue holds buffer_size undelivered frames the read loop waits for the consumer instead of dropping data. Backpressure therefore reaches the remote side, but all ports share one WebSocket: a port nobody reads stalls the others too (as with kubectl port-forward). Read every forwarded port, or aclose() the streams you don't need.

Source code in kubex/api/_portforward_session.py
def __init__(
    self,
    connection: WebSocketConnection,
    protocol: ChannelProtocol,
    ports: Sequence[int],
    *,
    buffer_size: float = _DEFAULT_CHANNEL_BUFFER,
) -> None:
    super().__init__(connection, protocol)
    self._ports: tuple[int, ...] = tuple(ports)

    # Channel-id → port lookup tables (built once, queried in _read_loop)
    self._data_ch_to_port: dict[int, int] = {}
    self._error_ch_to_port: dict[int, int] = {}

    # Per-port memory streams (keyed by port number)
    self._streams_send: dict[int, MemoryObjectSendStream[bytes]] = {}
    self._streams_recv: dict[int, MemoryObjectReceiveStream[bytes]] = {}
    self._errors_send: dict[int, MemoryObjectSendStream[str]] = {}
    self._errors_recv: dict[int, MemoryObjectReceiveStream[str]] = {}

    # Per-port PortForwardStream objects exposing the anyio.abc.ByteStream API.
    self._streams: dict[int, PortForwardStream] = {}

    # Whether each port's data / error channel is still accepting inbound frames.
    self._data_open: dict[int, bool] = {}
    self._error_open: dict[int, bool] = {}

    # Channels whose first frame (port prefix) has already been consumed.
    self._data_first_seen: set[int] = set()
    self._error_first_seen: set[int] = set()

    from kubex.api._portforward import PortForwardStream as _PortForwardStream

    for i, port in enumerate(self._ports):
        dc = data_channel_for_port_index(i)
        ec = error_channel_for_port_index(i)
        self._data_ch_to_port[dc] = port
        self._error_ch_to_port[ec] = port

        send_d, recv_d = anyio.create_memory_object_stream[bytes](
            max_buffer_size=buffer_size
        )
        send_e, recv_e = anyio.create_memory_object_stream[str](
            max_buffer_size=buffer_size
        )
        self._streams_send[port] = send_d
        self._streams_recv[port] = recv_d
        self._errors_send[port] = send_e
        self._errors_recv[port] = recv_e
        self._streams[port] = _PortForwardStream(self, port, dc, recv_d)
        self._data_open[port] = True
        self._error_open[port] = True

close_port_data async

close_port_data(port: int) -> None

Half-close the data channel of port.

Idempotent: a second call for the same port is a no-op. On protocols that support it (v5) this sends protocol.encode(CHANNEL_CLOSE, bytes([data_channel_id])); on v4, the only protocol the kubelet registers for portforward, the channel is only marked closed locally, because the kubelet ignores close frames there.

Parameters:

Name Type Description Default
port int

A port forwarded by this session.

required

Raises:

Type Description
ValueError

port is not part of this session.

Source code in kubex/api/_portforward_session.py
async def close_port_data(self, port: int) -> None:
    """Half-close the data channel of ``port``.

    Idempotent: a second call for the same port is a no-op. On protocols
    that support it (v5) this sends
    ``protocol.encode(CHANNEL_CLOSE, bytes([data_channel_id]))``; on v4, the
    only protocol the kubelet registers for portforward, the channel is only
    marked closed locally, because the kubelet ignores close frames there.

    Args:
        port: A port forwarded by this session.

    Raises:
        ValueError: ``port`` is not part of this session.
    """
    if port not in self._ports:
        raise ValueError(
            f"port {port} is not part of this portforward session (ports={list(self._ports)})"
        )
    port_index = self._ports.index(port)
    dc = data_channel_for_port_index(port_index)
    await self._send_close_for_channel(dc)

Protocol helpers

kubex.api._protocol

ApiNamespaceTypes module-attribute

ApiNamespaceTypes = NamespaceTypes | EllipsisType

A per-call namespace argument: a namespace name, None (no namespace, or all namespaces for calls that allow it), or ... (omitted: use the Api default).

ApiRequestTimeoutTypes module-attribute

ApiRequestTimeoutTypes = TimeoutTypes | EllipsisType

A per-call HTTP timeout: a Timeout, a number of seconds, None (no timeout), or ... (omitted: use the client default).

ApiProtocol

Bases: Protocol[ResourceType]

The parts of Api that subresource descriptors read.

The descriptors' __get__ overloads match on ApiProtocol[T] to pick the accessor type for resource type T, or SubresourceNotAvailable when T lacks the matching marker interface.

CachedSubresourceDescriptor

Base for non-data descriptors that guard on a marker interface and cache the accessor.

SubresourceNotAvailable

Type of a subresource accessor whose resource type does not support it.

Type checkers see this for e.g. Api[Pod].scale: it has no attributes, so any call on it is a type error. At runtime the attribute access raises NotImplementedError instead.

ensure_optional_namespace

ensure_optional_namespace(
    namespace: ApiNamespaceTypes,
    default: NamespaceTypes,
    scope: Scope,
) -> NamespaceTypes

Resolve the namespace for a call that may span namespaces.

Used by list, watch and delete_collection.

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace passed to the call, or ... to use default.

required
default NamespaceTypes

The Api instance's namespace.

required
scope Scope

The resource's scope.

required

Returns:

Name Type Description
NamespaceTypes NamespaceTypes

the namespace to use, or None for all namespaces (always None for a cluster-scoped resource).

Raises:

Type Description
ValueError

a namespace resolves for a cluster-scoped resource.

Source code in kubex/api/_protocol.py
def ensure_optional_namespace(
    namespace: ApiNamespaceTypes,
    default: NamespaceTypes,
    scope: Scope,
) -> NamespaceTypes:
    """Resolve the namespace for a call that may span namespaces.

    Used by ``list``, ``watch`` and ``delete_collection``.

    Args:
        namespace: The namespace passed to the call, or ``...`` to use ``default``.
        default: The ``Api`` instance's namespace.
        scope: The resource's scope.

    Returns:
        NamespaceTypes: the namespace to use, or ``None`` for all namespaces (always
            ``None`` for a cluster-scoped resource).

    Raises:
        ValueError: a namespace resolves for a cluster-scoped resource.
    """
    _namespace = get_namespace(namespace, default)
    if scope == Scope.CLUSTER and _namespace is not None:
        raise ValueError("Namespace is not supported for cluster-scoped resources")
    return _namespace

ensure_required_namespace

ensure_required_namespace(
    namespace: ApiNamespaceTypes,
    default: NamespaceTypes,
    scope: Scope,
) -> NamespaceTypes

Resolve the namespace for a call that targets a single object.

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace passed to the call, or ... to use default.

required
default NamespaceTypes

The Api instance's namespace.

required
scope Scope

The resource's scope.

required

Returns:

Name Type Description
NamespaceTypes NamespaceTypes

the namespace to use; None for a cluster-scoped resource.

Raises:

Type Description
ValueError

no namespace resolves for a namespace-scoped resource, or one resolves for a cluster-scoped resource.

Source code in kubex/api/_protocol.py
def ensure_required_namespace(
    namespace: ApiNamespaceTypes,
    default: NamespaceTypes,
    scope: Scope,
) -> NamespaceTypes:
    """Resolve the namespace for a call that targets a single object.

    Args:
        namespace: The namespace passed to the call, or ``...`` to use ``default``.
        default: The ``Api`` instance's namespace.
        scope: The resource's scope.

    Returns:
        NamespaceTypes: the namespace to use; ``None`` for a cluster-scoped resource.

    Raises:
        ValueError: no namespace resolves for a namespace-scoped resource, or one
            resolves for a cluster-scoped resource.
    """
    _namespace = get_namespace(namespace, default)
    if _namespace is None and scope == Scope.NAMESPACE:
        raise ValueError("Namespace is required")
    if _namespace is not None and scope == Scope.CLUSTER:
        raise ValueError("Namespace is not supported for cluster-scoped resources")
    return _namespace

get_namespace

get_namespace(
    namespace: ApiNamespaceTypes, default: NamespaceTypes
) -> NamespaceTypes

Resolve a per-call namespace argument against the Api default.

Parameters:

Name Type Description Default
namespace ApiNamespaceTypes

The namespace passed to the call, or ... if it was omitted.

required
default NamespaceTypes

The Api instance's namespace.

required

Returns:

Name Type Description
NamespaceTypes NamespaceTypes

default if namespace was omitted, otherwise namespace (which may be None).

Source code in kubex/api/_protocol.py
def get_namespace(
    namespace: ApiNamespaceTypes, default: NamespaceTypes
) -> NamespaceTypes:
    """Resolve a per-call namespace argument against the ``Api`` default.

    Args:
        namespace: The namespace passed to the call, or ``...`` if it was omitted.
        default: The ``Api`` instance's namespace.

    Returns:
        NamespaceTypes: ``default`` if ``namespace`` was omitted, otherwise
            ``namespace`` (which may be ``None``).
    """
    if namespace is Ellipsis:
        return default
    return namespace