Web API#

The DataLab Web API provides a modern HTTP/JSON interface for external access to the DataLab workspace. It is the recommended integration path for new projects, especially for Jupyter notebooks and web-based tools.

Note

The Web API is available starting from DataLab 1.1. The required dependencies (FastAPI, Uvicorn, Pydantic) are included in the standard DataLab installation.

Overview#

The Web API enables:

  • Jupyter notebook integration via DataLab-Kernel

  • WASM/Pyodide compatibility (no XML-RPC dependency)

  • External tool integration (any HTTP client)

Unlike the XML-RPC interface, the Web API:

  • Uses JSON for metadata and NPZ for binary data (efficient large array transfer)

  • Provides bearer token authentication for security

  • Follows REST conventions with OpenAPI documentation

  • Works in browser environments (WASM/Pyodide)

Comparison with XML-RPC#

Feature

XML-RPC

Web API

Protocol

XML

JSON + Binary (NPZ)

WASM Support

❌

✅

Large Arrays

Slow (base64)

Fast (NPZ)

Authentication

None

Bearer Token

Standards

XML-RPC

REST + OpenAPI

Quick Start#

Enabling the Web API#

There are several ways to enable the Web API server:

  1. Via UI: File → Web API → Start Web API Server

  2. Via environment variable: Set DATALAB_WEBAPI_ENABLED=1 before starting DataLab

When started from the menu or from the status bar, DataLab displays the server URL and authentication token in a dialog. The status bar also shows the Web API port when the server is running: click it to display the connection information again.

The default port is 18080 (or the next available port if busy).

Auto-Discovery#

DataLab-Kernel can automatically discover and connect to a running DataLab instance without any manual configuration. When the Web API starts, DataLab writes connection information to a file that DataLab-Kernel reads automatically.

Just load the extension — no environment variables or explicit connection needed:

# In your notebook (JupyterLab, VS Code, etc.)
%load_ext datalab_kernel

# DataLab-Kernel automatically finds and connects to DataLab
workspace.list()  # Already connected!

The auto-discovery mechanism tries the following methods in order:

  1. Environment variables (DATALAB_WORKSPACE_URL, DATALAB_WORKSPACE_TOKEN)

  2. Connection file written by DataLab (native Python only)

  3. URL query parameters (JupyterLite: ?datalab_url=...&datalab_token=...)

  4. Well-known port probing (http://127.0.0.1:18080)

If discovery fails, DataLab-Kernel starts in standalone mode and you can connect later using workspace.connect().

Manual Connection (Legacy)#

If auto-discovery doesn’t work (e.g., running on a different machine), you can set environment variables before starting your notebook kernel:

export DATALAB_WORKSPACE_URL=http://127.0.0.1:18080
export DATALAB_WORKSPACE_TOKEN=<your-token>

Then, in a notebook using the DataLab-Kernel kernel (or after %load_ext datalab_kernel), use the workspace object which is already defined in the namespace:

# List objects in DataLab
workspace.list()

# Retrieve an object
signal = workspace.get("my_signal")

# Add a processed result back to DataLab
workspace.add("processed", result)

API Reference#

Base URL: http://127.0.0.1:<port>/api/v1

Status Endpoint (No Auth Required)#

Method

Endpoint

Description

GET

/status

Server status and version information

Object Operations (Auth Required)#

All endpoints below require the Authorization: Bearer <token> header, except for requests from the local machine while the localhost bypass is enabled (default, see Localhost Token Bypass).

Method

Endpoint

Description

GET

/objects

List all objects with metadata (JSON)

GET

/objects/{name}

Get object metadata (JSON)

DELETE

/objects/{name}

Delete an object

PATCH

/objects/{name}/metadata

Update object metadata

Binary Data Transfer (Auth Required)#

Method

Endpoint

Description

GET

/objects/{name}/data

Download object as NPZ archive (supports ?compress=false)

PUT

/objects/{name}/data

Create or replace an object from an NPZ archive (supports ?overwrite=true)

PUT

/objects/{name}

Update an existing object in-place from an NPZ archive, preserving its identity, group membership and position

The GET /objects/{name}/data endpoint streams an NPZ archive as application/x-npz. Pass ?compress=false to skip ZIP deflate compression when the client (e.g. a notebook) prefers a faster transfer at the cost of larger payloads. Object names containing non-ASCII characters are returned in the Content-Disposition header using the RFC 5987 filename* form.

The PUT /objects/{name}/data endpoint creates a new object with the given name, or returns 409 Conflict if it already exists. Pass ?overwrite=true to replace the existing object: the new object is added first, then the existing one is removed, so that the existing object is kept if the new one cannot be added. While the replacement is in progress, the workspace briefly contains both objects.

Computation (Auth Required)#

Method

Endpoint

Description

POST

/select

Select objects in a panel for subsequent computations

POST

/calc

Run a DataLab computation function on the current selection

Data Format#

Objects are transferred using NumPy’s NPZ format for efficiency. The format is implemented by Sigima (sigima.io.serialize_object_to_npz and sigima.io.deserialize_object_from_npz), so that Python clients can read and write these archives with the same code as DataLab.

SignalObj NPZ Structure#

my_signal.npz
├── x.npy          # X coordinates (float64)
├── y.npy          # Y data (float64)
├── dx.npy         # X uncertainties (optional)
├── dy.npy         # Y uncertainties (optional)
└── metadata.json  # Type ("signal"), title, labels, units,
                   # object metadata (optional)

ImageObj NPZ Structure#

my_image.npz
├── data.npy       # 2D image array (preserves dtype)
├── xcoords.npy    # X pixel centers (only for non-uniform coordinates)
├── ycoords.npy    # Y pixel centers (only for non-uniform coordinates)
└── metadata.json  # Type ("image"), title, labels, units,
                   # coordinates (x0, y0, dx, dy, is_uniform_coords),
                   # object metadata (optional)

In metadata.json, the type key ("signal" or "image") is required to read an archive. The optional obj_metadata key holds the metadata of the object (e.g. analysis results).

Authentication#

All API endpoints except /status require a Bearer token, unless the request comes from the local machine while the localhost bypass is enabled (default, see Localhost Token Bypass):

Authorization: Bearer <token>

The token is generated when the server starts and displayed in the connection dialog.

Environment Variables#

Variable

Description

Default

DATALAB_WEBAPI_HOST

Bind address

127.0.0.1

DATALAB_WEBAPI_PORT

Server port

18080 (or next available)

DATALAB_WEBAPI_TOKEN

Auth token

Generated

Security Model#

The Web API implements the following security measures:

  1. Localhost binding: By default, the server only accepts connections from the local machine (127.0.0.1).

  2. Token authentication: Every request (except status) must include a valid Bearer token, except for requests from the local machine while the localhost bypass is enabled, which is the default (see Localhost Token Bypass). With the default localhost binding, local clients therefore connect without a token until you disable this bypass.

  3. Explicit opt-in: Remote binding (0.0.0.0) requires explicit configuration.

Localhost Token Bypass#

By default, DataLab does not check the token of requests coming from the local machine (127.0.0.1 or ::1): local clients, such as DataLab-Kernel, connect without a token. This makes auto-discovery work seamlessly even when the connection file cannot be read (e.g., in JupyterLite or sandboxed environments).

To require the token for local requests too, disable the Web API localhost bypass option in the General tab of File → Settings…. The change applies the next time the Web API server starts.

Warning

While the Web API server is running with the localhost bypass enabled (default), any software running on your machine, including malicious software, and any web page open in your browser can access your data without a token. Disable the bypass if you do not control all applications running on your machine or if you browse untrusted websites while the server is running.

Warning

Exposing the API to the network allows anyone with the token to access your data. Use with caution on trusted networks only.

Architecture#

┌─────────────────────────────────────────┐
│           DataLab Main Window           │
│                 (Qt)                    │
├─────────────────────────────────────────┤
│            WebApiController             │
│         (Server Lifecycle)              │
├─────────────────────────────────────────┤
│            WorkspaceAdapter             │
│         (Thread-safe access)            │
├─────────────────────────────────────────┤
│          FastAPI + Uvicorn              │
│         (Separate thread)               │
└─────────────────────────────────────────┘
                  ↑
                  │ HTTP/JSON
                  ↓
┌─────────────────────────────────────────┐
│        DataLab-Kernel / Client          │
└─────────────────────────────────────────┘

The Web API runs in a separate thread from the Qt GUI. The WorkspaceAdapter ensures thread-safe access to DataLab objects by marshalling calls to the main thread using Qt’s signal/slot mechanism.

Installation#

The Web API dependencies are included in the standard DataLab installation:

  • FastAPI (web framework)

  • Uvicorn (ASGI server)

  • Pydantic (data validation)

No additional installation steps are required.

Programmatic Control#

The Web API can also be started and controlled programmatically via the XML-RPC interface, which is useful for automated workflows:

from datalab.control.remote import RemoteClient

proxy = RemoteClient()
proxy.connect()

# Start the Web API server
info = proxy.start_webapi_server()
print(f"URL: {info['url']}")
print(f"Token: {info['token']}")

# Check status
status = proxy.get_webapi_status()
print(f"Running: {status['running']}")

# Stop the server
proxy.stop_webapi_server()

See Also#