Metadata-Version: 2.5
Name: datalens-sdk
Version: 3.3.0
Summary: Python SDK for the DataLens API
Project-URL: Homepage, https://datalens.ru/
Project-URL: Documentation, https://github.com/datalens-tech/datalens-sdk#readme
Project-URL: Repository, https://github.com/datalens-tech/datalens-sdk
Project-URL: Issues, https://github.com/datalens-tech/datalens-sdk/issues
Project-URL: Changelog, https://github.com/datalens-tech/datalens-sdk/blob/main/CHANGELOG.md
Author-email: DataLens Team <datalens-opensource@yandex-team.ru>
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICES
Keywords: analytics,business-intelligence,datalens,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic<3,>=2
Requires-Dist: pyjwt[crypto]<3,>=2.10
Requires-Dist: typing-extensions>=4.13
Description-Content-Type: text/markdown

# DataLens Python SDK

[![CI](https://github.com/datalens-tech/datalens-sdk/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/datalens-tech/datalens-sdk/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/datalens-sdk.svg)](https://pypi.org/project/datalens-sdk/) [![Python](https://img.shields.io/pypi/pyversions/datalens-sdk.svg)](https://pypi.org/project/datalens-sdk/) [![License](https://img.shields.io/pypi/l/datalens-sdk.svg)](https://github.com/datalens-tech/datalens-sdk/blob/main/LICENSE)

`datalens-sdk` is the typed Python SDK for the [DataLens](https://datalens.ru/promo) API. It provides clients and
domain models for working with connections, datasets, charts, dashboards, collections, workbooks, folders, and
navigation in Yandex Cloud DataLens and DataLens Enterprise.

## Requirements

- Python 3.10 or newer
- A Yandex Cloud organization with DataLens enabled, or a DataLens Enterprise installation

## Project status

The `3.X` series is a beta release. The SDK is used in production, while its public API and coverage are still being
stabilized. Backward-incompatible API changes require a new major release.

## Installation

The package is available from PyPI:

```bash
pip install datalens-sdk
```

### Using the SDK with coding agents

Install the [`datalens-skills`](https://github.com/datalens-tech/datalens-skills)
plugin when using this SDK through Claude Code, Codex, OpenCode, or another
Agent Skills-compatible coding agent. Its root `datalens-sdk` skill selects a
safe project environment, installs or updates this package with explicit
version decisions, and then loads the version-matched instructions bundled in
the installed SDK. Do not install or invoke the bundled skill directly; follow
the plugin repository's installation instructions instead.

## Quick start

`DataLensClientYC` uses the active [`yc` CLI](https://yandex.cloud/en/docs/cli/quickstart) profile by default. Configure
the organization once; the SDK will then obtain and refresh IAM tokens automatically:

```bash
yc config set organization-id <organization-id>
```

Use clients as context managers so their HTTP connections are closed promptly:

```python
from datalens_sdk import DataLensClientYC

with DataLensClientYC() as client:
    dataset = client.get.dataset(by_id="<dataset-id>")
    print(dataset.name)
```

For DataLens Enterprise, provide the installation's API base URL:

```python
from datalens_sdk import DataLensClientEnterprise

with DataLensClientEnterprise(base_url="https://datalens.example.com") as client:
    workbook = client.get.workbook(by_id="<workbook-id>")
    print(workbook.name)
```

## Authentication

Yandex Cloud users can choose among the following providers:

- `YCIAMAuthProvider` uses a `yc` CLI profile and refreshes IAM tokens automatically. This is the default for `DataLensClientYC`; `DATALENS_YC_BIN`, `DATALENS_YC_PROFILE`, and `DATALENS_ORG_ID` configure its defaults, while explicit constructor arguments take precedence. Its CLI invocations share one configurable timeout value, which defaults to 30 seconds.
- `YCServiceAccountCredentialsAuthProvider` exchanges service-account credentials for refreshable IAM tokens.
- `StaticYCIAMAuthProvider` accepts an existing IAM token and organization ID.

```python
import os

from datalens_sdk import StaticYCIAMAuthProvider, DataLensClientYC

auth = StaticYCIAMAuthProvider(
    org_id=os.environ["DATALENS_ORG_ID"],
    token=os.environ["DATALENS_IAM_TOKEN"],
)

with DataLensClientYC(auth=auth) as client:
    dashboard = client.get.dashboard(by_id="<dashboard-id>")
```

Pass `auth=None` explicitly for access without authentication.
For Enterprise service accounts, sign and exchange credentials automatically:

```python
import os
from pathlib import Path

from datalens_sdk import DataLensClientEnterprise, EnterpriseServiceAccountCredentialsAuthProvider

base_url = os.environ["DATALENS_BASE_URL"]
auth = EnterpriseServiceAccountCredentialsAuthProvider(
    key_id="<private-key-id>",
    service_account_id="<service-account-id>",
    private_key=Path("/secure/path/private-key.pem").read_text(),
)

with DataLensClientEnterprise(base_url=base_url, auth=auth) as client:
    dashboard = client.get.dashboard(by_id="<dashboard-id>")
```

The provider signs a five-minute PS256 JWT, exchanges it for an Enterprise
access token, and refreshes the access token automatically before it expires.
Client JWT lifetimes are configurable up to the Enterprise limit of 10 minutes.

## Core concepts

The client groups operations by intent:

- `client.get` loads resources such as datasets, charts, and dashboards.
- `client.create` exposes typed builders. Configure a builder fluently and call `.build()` to send it.
- Returned resources provide operations such as `.move()`, `.rename()`, `.update`, and `.delete()`.
- `EntryLocation` identifies a destination path, workbook, or collection.

For example, create a workbook and use the returned object directly as a destination:

```python
from datalens_sdk import DataLensClientYC

with DataLensClientYC() as client:
    workbook = client.create.workbook(name="SDK workbook").build()
    dataset = client.create.dataset(name="SDK dataset", location=workbook).build()
```

Wizard-owned fields use immutable, GUID-bearing handles. Register each handle
once and reuse the same object in placeholders, filters, sorting, and
decorations:

```python
from datalens_sdk import WizardAggregatedMeasure, WizardHierarchy, WizardLocalField

dataset = client.get.dataset(by_id=dataset.id)
country = dataset.fields.by_name("Country")
city = dataset.fields.by_name("City")
customer = dataset.fields.by_name("Customer")

revenue_per_order = WizardLocalField.measure(
    guid="customer-revenue-per-order",
    title="Revenue per order",
    formula="SUM([Revenue]) / SUM([Orders])",
    cast="float",
)
unique_customers = WizardAggregatedMeasure(
    guid="customer-unique-customers",
    field=customer,
    aggregation="countunique",
    title="Unique customers",
)
geo = WizardHierarchy(guid="customer-country-city", title="Country → City", fields=[country, city])

chart = (
    client.create.wizard_chart.flat_table(name="Customer geography", location=workbook)
    .dataset(dataset)
    .add_local_field(revenue_per_order)
    .add_aggregated_measure(unique_customers)
    .add_hierarchy(geo)
    .columns([geo, revenue_per_order, unique_customers])
    .build()
)
```

The remembered handles remain valid after re-fetch because references resolve
by GUID. Without a saved handle, use an exact GUID through
`chart.fields.by_guid(...)`; `chart.fields` intentionally returns
`DatasetField` snapshots and does not reconstruct handles.

## Chart data

Read tables from a saved Wizard, QL, or Editor chart through either entrypoint:

```python
result = client.data.get_chart_data(
    chart_id="<saved-chart-id>",
    params={"region": ["East", "West"], "year": "2026"},
)
# Equivalent on an already loaded chart:
result = chart.get_chart_data(params={"region": ["East", "West"], "year": "2026"})
```

`ChartData` is a union of `WizardChartData`, `QLChartData`, and `EditorChartData`.
Narrow on `result.chart_type` to get the corresponding column type. Each item
in `result.results` is a `ChartDataTable` with an ordered `schema` and positional
`rows`. The SDK preserves multiple tables, duplicate column names, JSON cells,
and numeric strings without coercion.

Both methods execute by ID: the loaded revision and local edits are not sent,
and saved/published selection is unspecified. Revision selection is unsupported:
`revId` and `branch` in `params` raise `DataLensValidationError` before HTTP.
`tab` and `state` are also rejected because dashboard controls are not chart-data
parameters. Remove these names from `params`; a loaded draft or historical
revision does not pin the returned data. `dataset.get_dataset_data()` also
executes by ID. `chart.to_file(...)` exports the definition rather than these
tables. Runtime params are strings or sequences of strings; `None`
omits params and `{}` sends an empty object. There is no dataset default limit,
automatic pagination, or CSV/XLSX export. The example names `region` and
`year` assume that the chart reads those keys; see the [runtime parameter guidance](skills/datalens-sdk/references/parameters.md#runtime-chart-parameters)
for the keys each chart family uses.

The API is experimental. Pivot tables are unsupported, and Editor requires
`Editor.setRawData()`. Aggregate response limits are 100,000 rows, 100,000
cells, 1,000 tables, and 100,000 schema columns; a table can have 800 columns.
These limits apply simultaneously: if every row has two cells, the response
can contain at most 50,000 rows in total. The [Yandex Cloud limits page](https://yandex.cloud/ru/docs/datalens/concepts/limits#datalens-chart-data-limits)
separately documents chart display limits and Cloud API rate limits.
Exceeding a response limit raises an HTTP 422 API error without retry or local
truncation. Other transient read failures use the usual SDK retry policy.
Invalid arguments fail before HTTP with `DataLensValidationError`; malformed
responses raise `DTOValidationError` or `InvalidResponseError`.

When working through an agent, explicitly choose how returned data should be
handled before executing a query: show it, save it, keep it in a saved script
variable, or analyze it. Writing a query does not authorize running it or
inspecting rows. See the [chart-data reference](skills/datalens-sdk/references/chart-data.md)
for types, parameters, errors, and limits.

## Screenshots

Loaded charts and dashboards can be rendered on the server and saved as PNG
files. The picture holds the entity alone, without the DataLens navigation. A
dashboard screenshot captures the whole tab:

```python
dashboard = client.get.dashboard(by_id="<dashboard-id>")
screenshot = dashboard.screenshot(
    tab=dashboard.tabs[0].id,
    theme="dark",
    params={"Region": ["East", "West"]},
)
screenshot.save("dashboard.png")
```

`chart.screenshot()` and `dashboard.screenshot()` take keyword arguments only:

| Argument | Chart | Dashboard | Meaning |
| --- | --- | --- | --- |
| `width` | `1024` | `1280` | Viewport width in pixels, 1 through 6000 |
| `height` | `768` | not set | Viewport height in pixels, 1 through 6000 |
| `full_page` | n/a | on unless `height` is given | Capture the whole tab instead of the viewport |
| `tab` | n/a | first tab | Tab id from `dashboard.tabs` |
| `state` | n/a | not set | A `DashboardState`, or the hash of a saved selector state (the `state=` value of a dashboard link) |
| `theme` | page default | page default | `"light"` or `"dark"` |
| `show_title` | n/a | `True` | Keep the dashboard title |
| `show_tabs` | n/a | `True` | Keep the dashboard tab bar |
| `params` | optional | optional | Parameter values; a dashboard reads only parameters declared in its settings |
| `timeout` | `120` | `120` | Seconds for the call, including a wait for the rate limit |

The screenshot API is experimental and accepts 3 chart and 3 dashboard
screenshots per minute; the SDK waits out that limit when the wait fits in the
call's `timeout`. `screenshot.get_temp_s3_url()` renders the same picture again
and returns a temporary signed link to it.

## Dashboard states

A dashboard link with `state=<hash>` stores selector values, chart clicks, and
chosen chart tabs for one dashboard tab. Read it, change it, and get a new link:

```python
dashboard = client.get.dashboard(by_id="<dashboard-id>")
state = dashboard.get_state("<hash>", tab="<tab id from ?tab=>")
for selection in state.selections:
    print(selection.item_id, [(_.param, _.operation, _.values) for _ in selection.values])

new_state = state.edit().select("Region", ["East", "West"]).create()
print(new_state.url())
```

`get_state()` checks the state against the loaded revision; missing items,
selector members, chart tabs, and parameters become `state.issues` and one
warning, or an error with `strict=True`. `dashboard.new_state(tab)` and
`dashboard.create_state(tab, selections)` build a state from scratch;
`create()` rejects any problem before calling the API. `state.params_for(item)`
returns the parameters a widget receives, and `state.effects()` lists the
receivers of every source; `effects(resolve_charts=True)` reads the charts to
tell which of them use the parameters. `url()` uses `ui_base_url`, which is
`https://datalens.ru` for `DataLensClientYC` and must be passed to
`DataLensClientEnterprise`. See the
[dashboard state reference](skills/datalens-sdk/references/dashboard-state.md).

## Examples

Runnable Yandex Cloud examples are available in [`examples/`](examples/):

| Example | What it demonstrates |
| --- | --- |
| [`get_dataset.py`](examples/get_dataset.py) | Load and inspect a dataset |
| [`entry_revisions.py`](examples/entry_revisions.py) | Page through revision metadata and read a selected historical dataset |
| [`collection_workbook_lifecycle.py`](examples/collection_workbook_lifecycle.py) | Collection and workbook create, update, and read |
| [`clickhouse_dashboard.py`](examples/clickhouse_dashboard.py) | Create a ClickHouse connection, dataset, chart, and dashboard |

Inspect an example's configuration before running it:

```bash
python examples/clickhouse_dashboard.py --help
```

Resource-creating examples leave their output in place for inspection.

## Raw JSON artifacts

`to_file(parent)` writes a resource's exact server snapshot below an existing
parent directory. Artifacts require the resource name and id and use
`<sanitized name> [<sanitized id>]`; export does not synthesize missing
identity fields or mutate the resource model.

Raw JSON mutations live under `client.raw`; typed create and update builders
do not accept raw snapshots. Create from a response snapshot with
`client.raw.create.<resource>(response_snapshot=raw, name=..., location=...).build()`
or from an exported artifact directory with
`client.raw.create.<resource>.from_file(path, name=..., location=...).build()`.
Replace an existing resource with
`client.raw.replace.<resource>(target=..., response_snapshot=raw).execute(...)` or
`client.raw.replace.<resource>.from_file(path, target=...).execute(...)`.
Dataset, chart, and Dashboard replace can select `.mode("save")` or
`.mode("publish")` before `execute()`. Dashboard still requires an explicit
choice and accepts the compatible `execute(publish=bool)` form.
Raw replacement writes supplied content as a new revision; source and target
revision selectors are excluded from the write payload. Use `.mode("publish")`
to publish that content. Publishing an existing saved draft or historical
revision is the separate `publish_revision(rev_id=existing_revision_id)`
operation on Wizard, Editor, Dashboard, and HTML pages.
Replace overwrites the supported mutable content and is last-write-wins: it
does not fetch, merge, or check for concurrent changes. Each `build()` or
`execute()` call performs a new mutation and has no idempotency guarantee.

`Dashboard.to_file(parent, with_dependencies=True)` adds Charts and Datasets
discovered only through the relations API. It never calls `getEntries`;
relation wire types select the specialized Wizard, Editor, or QL getter, and
relation `workbookId` values are forwarded without forcing a branch or
revision. The resulting bundle therefore does not promise cross-resource
revision consistency.

The Dashboard, Charts, and Datasets are validated before the whole bundle is
published with one atomic no-replace rename. Connections are not included.
The `charts/` and `datasets/` directories are export-only:
`client.raw.create.dashboard.from_file(...)` and
`client.raw.replace.dashboard.from_file(...)` read only `dashboard.json` and
do not import or remap dependencies.

## Development

The project uses [Nox](https://nox.thea.codes/) for every development check:

```bash
pip install nox

nox -s check         # complete local PR gate, including every supported Python
nox                  # same checks as `nox -s check`
nox -s lint          # Ruff lint
nox -s format        # format Python and JSON and apply safe lint fixes
nox -s format-check  # check formatting without modifying files
nox -s typecheck     # strict mypy
nox -s dependency-lower-bounds  # verify the dependency versions declared as minimums
nox -s tests-3.13    # test with a specific supported interpreter
nox -s update-specs  # update the default public API specification
```

Pass installation names after `--` to update selected specifications:

```bash
nox -s update-specs -- yacloud
nox -s update-specs -- enterprise
```

While Enterprise uses the same API version with a restricted connector and
dataset-source catalog, update both specifications from YaCloud with:

```bash
nox -s update-specs -- --derive-enterprise
```

This downloads YaCloud once and derives Enterprise using the connector and
dataset-source names already enabled in `spec/enterprise.json`. Shared schemas
and routes come from that same download; new YaCloud catalog variants are not
enabled in Enterprise automatically. Missing enabled variants abort the update
before either file is written. The separate Enterprise endpoint is not used in
this mode.

Specification updates do not regenerate SDK sources. Review the specification diff, then run `nox -s generate`
and the complete `nox` gate.

## Maintainer release process

Every minor line is published from a protected `release/X.Y` branch. Production
tags have the canonical `vX.Y.Z` or `vX.Y.ZrcN` form and must point to a commit
on the matching release branch. Release-candidate numbering starts at `rc1`;
subsequent candidates increment `N`, and the final release drops the `rcN`
suffix. The publish workflow rejects a tag from any other branch, runs the
complete quality and Python-version matrix, builds and validates one wheel and
sdist, publishes those exact files, and attaches them to the GitHub Release.
Release-candidate GitHub Releases are marked as pre-releases.

To start a new minor line:

1. Open a release PR against `main` that sets the final or release-candidate
   version and adds its dated changelog section. Use the canonical PEP 440 form
   `X.Y.ZrcN`, never the SemVer-style `X.Y.Z-rc.N` form.
2. Merge the PR after every required check passes.
3. Create `release/X.Y` from that merge commit and wait for the release-branch
   CI run to pass.
4. Create and push an annotated `vX.Y.Z` or `vX.Y.ZrcN` tag at that commit.
5. Approve the `pypi` deployment, then verify the published metadata,
   provenance, hashes, installation, and a read-only call.

For a patch on an older line, fix the defect on `main` first when it still
applies there. Open a PR against `release/X.Y` using `git cherry-pick -x`,
adapt the change if that line has diverged, update the patch version and
changelog, and tag the merged release-branch commit. A fix that no longer
applies to `main` may target only the release branch with the reason recorded
in the PR.

TestPyPI is separate: manually run the `Publish` workflow from `main`. It
executes the same complete verification and build path but requires approval
of the `testpypi` environment and does not create a tag or GitHub Release.

Tags and published files are immutable. If a release is unusable, yank it
where supported and publish a new patch version. Repository rulesets,
deployment environments, and trusted publishers are configured outside the
source tree by repository administrators.

## Project policies

- Read [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
- Report vulnerabilities privately according to [SECURITY.md](SECURITY.md).
- Participation is governed by [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
- User-visible changes are recorded in [CHANGELOG.md](CHANGELOG.md).

For general project questions, use
[GitHub Issues](https://github.com/datalens-tech/datalens-sdk/issues).

## License

Licensed under the Apache License 2.0. See [LICENSE](LICENSE).
