The Python Label Management SDK, dwn_label_management, adds, removes and lists labels from your own code. It uses the same labels you see in the Darwinium Portal.
To install the SDK and create a LabelClient, follow Python SDKs. The certificate needs the Edit Labels permission on the node you call.
The examples on this page use this client:
from dwn_label_management import LabelClient, LabelClientConfig
client = LabelClient(
LabelClientConfig(
node_name="<your node name>",
mtls_CA_file_path="/path/to/cachain.pem",
mtls_cert_file_path="/path/to/cert.pem",
mtls_key_file_path="/path/to/privkey.key",
)
)
Adding a label
Give the label's programmatic name and the identifier to label:
result = await client.add_label(
label_programmatic_name="account_takeover",
attributes=[
{"programmaticName": "identity['*'].username.username", "value": "suspicious_user_123"},
],
contexts=[],
notes="Flagged during manual review",
)
if result.success:
print(f"Added label {result.uuid}")
else:
print(f"Not added: {result.error}: {result.message}")
label_programmatic_nameis the label's programmatic name, as listed in Label Names and IDs. Listing label definitions lists them from code.attributesare the identifiers to label. Each has aprogrammaticNamefrom the Attribute Reference and avalue.contextsadd detail to the label. Pass an empty list for none. See Adding a label with contexts.notesis optional free text, such as why you added the label.
Labelling several identifiers
One label can cover several identifiers of the same person. Pass them all in attributes:
result = await client.add_label(
label_programmatic_name="account_takeover",
attributes=[
{"programmaticName": "identity['*'].email['*'].email", "value": "verified.customer@example.com"},
{"programmaticName": "identity['*'].name.first", "value": "John"},
{"programmaticName": "identity['*'].name.last", "value": "Smith"},
],
contexts=[],
notes="Verified through customer support",
)
Adding a label with contexts
Pass label contexts by their programmatic names:
result = await client.add_label(
label_programmatic_name="scripted_attack_fraud",
attributes=[
{"programmaticName": "identity['*'].login.login", "value": "bot_user_42"},
],
contexts=["finance", "reasonable"],
notes="Detected automated login pattern",
)
Each label type allows only some contexts. The SDK checks the label name and every context before it sends the request, and raises ValidationError if one isn't valid. To see which contexts a label allows, see Getting the valid contexts for a label.
Removing a label
Remove a label by its UUID. You get the UUID when you add the label, or from listing labels.
result = await client.remove_label(
label_uuid="dd2ee511ad094a9d86b0025422c78b58",
notes="Label no longer applicable: customer verified",
)
print(f"Removed: {result.removed_uuids}")
notes is required. The UUID may include hyphens or not.
Listing labels
get_labels returns one page of labels and the total number of labels. Pages are numbered from 0.
page_number = 0
labels = []
while True:
page = await client.get_labels(page=page_number, page_size=100)
labels.extend(page.labels)
if not page.labels or len(labels) >= page.total_count:
break
page_number += 1
print(f"Fetched {len(labels)} of {page.total_count} labels")
Each Label has its label_uuid, its label type ID label_id, the identifiers it covers, its contexts as context IDs, its metadata, and created_at and updated_at times.
To work with the labels in pandas:
import pandas as pd
labels_df = pd.DataFrame([label.model_dump() for label in labels])
Listing only some label types
Pass label type IDs to label_ids:
page = await client.get_labels(page=0, page_size=20, label_ids=[4040, 4050, 4070])
print(f"{page.total_count} labels of these types")
Filtering labels
filter_expr takes the same filter expressions as the Darwinium Portal:
page = await client.get_labels(
page=0,
page_size=20,
filter_expr="profiling.device.identifier in ('cc3ef45bdb344b57a9891a42ce65423e')",
)
Listing label definitions
get_all_label_definitions lists every label type you can add:
label_defs = await client.get_all_label_definitions()
for label_def in label_defs:
print(f"{label_def.programmatic_name} (ID {label_def.id}): {label_def.display_name}")
print(f" Category: {label_def.category_programmatic_name}")
print(f" Valid contexts: {len(label_def.valid_context_ids)}")
To look up one label type, use get_label_definition("account_takeover"). It returns None if the label type doesn't exist.
To group the label types by category:
from collections import defaultdict
by_category = defaultdict(list)
for label_def in label_defs:
by_category[label_def.category_programmatic_name].append(label_def.programmatic_name)
for category, names in sorted(by_category.items()):
print(f"{category}: {', '.join(names)}")
Listing contexts
get_all_contexts lists every label context:
contexts = await client.get_all_contexts()
for ctx in contexts:
print(f"{ctx.programmatic_name} (ID {ctx.id}): {ctx.display_name}, group {ctx.group}")
To group the contexts:
from collections import defaultdict
by_group = defaultdict(list)
for ctx in contexts:
by_group[ctx.group or "(no group)"].append(ctx.programmatic_name)
for group, names in sorted(by_group.items()):
print(f"{group}: {', '.join(names)}")
Getting the valid contexts for a label
from dwn_label_management import ValidationError
try:
valid_contexts = await client.get_valid_contexts_for_label("account_takeover")
for ctx in valid_contexts:
print(f"{ctx.programmatic_name} ({ctx.group})")
except ValidationError as e:
print(f"Unknown label type: {e}")
Converting between context names and IDs
Labels returned by get_labels list their contexts by ID. To convert between names and IDs:
ids = await client.resolve_context_names(["session_id", "device_fingerprint", "email", "probably"])
for name, ctx_id in ids.items():
print(f"{name} -> {ctx_id}")
names = await client.resolve_context_ids([200, 3050, 5020])
Unknown names and IDs map to None.
Handling errors
The SDK raises exceptions from dwn_label_management:
| Exception | Raised when |
|---|---|
ValidationError |
The request is invalid before it is sent: an unknown label type, a context the label doesn't allow, no attributes, or a malformed UUID. |
GraphQLError |
The API refused or failed the request. errors has the details. |
AuthenticationError |
The certificate, private key or CA chain couldn't be loaded, for example because the key password is wrong. |
ConfigurationError |
The client configuration is invalid, for example because a certificate file is missing. |
All of them are subclasses of LabelClientError:
from dwn_label_management import GraphQLError, LabelClientError, ValidationError
try:
result = await client.add_label(
label_programmatic_name="account_takeover",
attributes=[{"programmaticName": "identity['*'].email['*'].email", "value": "test@example.com"}],
contexts=[],
)
if not result.success:
print(f"Not added: {result.error}: {result.message}")
except ValidationError as e:
print(f"Invalid request: {e}")
except GraphQLError as e:
print(f"API error: {e}: {e.errors}")
except LabelClientError as e:
print(f"Error: {e}")