Skip to content

Python client quickstart

The official client is datalab-api. Use it rather than writing HTTP requests by hand. It handles login and file uploads, and keeps up with changes to the server.

This page covers the basics. The full reference is at api-docs.datalab-org.io, which also has an example notebook.

Install

pip install datalab-api

Connect

You need an API key in the DATALAB_API_KEY environment variable.

from datalab_api import DatalabClient

with DatalabClient("https://demo.datalab-org.io") as client:
    client.authenticate()

You can give the address of the web app. The client finds the matching API address for you.

Find out what your instance supports

info = client.get_info()          # version, identifier prefix and more
blocks = client.get_block_info()  # the data block types installed

List and fetch items

samples = client.get_items("samples")
cells = client.get_items("cells")

matches = client.search_items("LiFePO4")

item = client.get_item(item_id="jb-042")
item = client.get_item(refcode="grey:ABCDEF")

Results are plain Python dictionaries. Fields vary between instances, so use .get() rather than assuming a field exists.

Create an item

client.create_item(
    item_id="jb-043",
    item_type="samples",
    item_data={"name": "LiFePO4, ball-milled 2 h", "chemform": "LiFePO4"},
)

Leave out item_id to have one generated. To add the item to a collection, pass collection_id.

Update an item

client.update_item("jb-043", {"description": "Annealed at 600 C for 4 h."})

Attach a file and plot it

response = client.upload_file(item_id="jb-043", file_path="jb-043.xrdml")
file_id = response["file_id"]

client.create_data_block(item_id="jb-043", block_type="xrd", file_ids=file_id)

Use get_block_info() to find the block types your instance has.

Download files

client.get_item_files("jb-043")

This saves every file attached to the item into the current folder. It will not overwrite files that are already there.

Explore relationships

graph = client.get_item_graph(item_id="jb-043", as_networkx=True)

This needs the optional extra: pip install datalab-api[networkx].

Command line

The package also installs a datalab command for quick look-ups from a terminal. It is experimental and can only read data.