Skip to main content

Documents

This page is for the practitioner who wants bound document objects and follow-on document helpers. All snippets below assume svi is an authenticated SVIClient.

Document lifecycle​

Every state transition is a single method call on the bound Document. The SDK keeps the document snapshot fresh on each call (use refresh() to force a re-read).

Before this example​

The values in this page are placeholders, not universal VI names. Before you adapt a snippet, use Discover your environment to find:

  • a real entity type name for "<your-entity-type>"
  • a real document id for "<your-document-id>"
  • the real field names behind placeholders like "<your-status-field>"

Fetch and update a document​

Use svi.documents when you know the entity type and document id:

document = svi.documents.get(
entity_type_name="<your-entity-type>",
document_id="<your-document-id>",
)
if document is not None:
document.update_fields(**{"<your-status-field>": "<your-updated-value>"})

get() returns None when no document has that id, so check the result before you use it. The returned object holds its own field snapshot and one manager attribute per related resource: comments, attachments, images, insights, workspaces, relationships, conditions, history, and children.

Read a field value with document.fields["<your-field>"] or document.get_field("<your-field>"). A field is not an attribute: document.<your-field> raises AttributeError, and a type checker flags it, so a typo fails early.

Ask the service for the current user's lock state with checkout_state():

if document is not None:
state = document.checkout_state()
print(state["is_checked_out_by_me"])
print(state["checkout_status"])

This reflects only whether the current authenticated user holds the document lock. It does not report whether another user has the document checked out. In a coroutine, use await document.checkout_state_async().

fetch_entity_type_mode() returns "MANAGED" or "SOURCE" for the document's entity type. It sends one GET the first time and answers from the cache after that. fetch_entity_type_mode_async() is the coroutine twin, and a ChildDocument has both.

Both are explicit calls rather than properties, because a property that sends a request blocks the event loop inside a coroutine and fires when a debugger lists an object's attributes.

Release a stale lock​

Every document write takes a lock, writes, and releases the lock, including when the write fails or the task is cancelled. Three cases still leave the lock behind: the process is killed, a second Ctrl-C lands during the release, or the event loop is torn down straight after a cancellation. The SDK logs a WARNING that names the document when it knows a release failed. A killed process logs nothing.

release_lock() clears a lock that your user holds:

document = client.documents.get(entity_type_name="<your-type>", document_id="<your-id>")
if document is not None and document.release_lock():
print("lock released")

It asks the service whether the current user holds the lock, and returns False without sending a release when the answer is no. release_lock(force=True) skips the question and sends the release. Both raise the usual sasvi.errors type when the service refuses. release_lock_async() is the coroutine twin, and an Alert has both methods. From a shell, use sasvi doc unlock TYPE ID --yes.

Two things are not verified on a tenant yet:

  • Lock expiry. The SAS API reference says a document lock times out after two hours or when the session ends, whichever comes first. The SDK has not confirmed that a lock left by a killed process goes away on that schedule.
  • Releasing a lock you do not own. The lock check reports only the current user's lock, so release_lock() returns False for a lock another user holds. Whether release_lock(force=True) from a different user, or from an administrator, is accepted or refused has not been tested. Expect an error and ask the lock's owner to release it, or wait for the expiry, until that is known.

Set document fields by type​

Use document.update({...}) when you already have a mapping, or document.update_fields(...) for a small number of explicit changes:

document.update({"<your-status-field>": "open"})
document.update_fields(**{"<your-priority-field>": "high"})

When a step that cannot be undone sits between the validation and the write, split the update. prepare_update reads the entity type, refuses an unknown or read-only field and a SOURCE type, and returns the patch without writing. apply_update takes the lock and writes it. The two calls cost the same requests as one update. WorkflowTask.complete uses them around its completion PUT. Both have _async twins.

operations = document.prepare_update({"<your-status-field>": "closed"})
# the step that cannot be undone goes here
document.apply_update(operations)

Before writing a field, inspect the entity-type metadata so you know the field's VI name, data type, logical data type, whether it is writable, whether it allows multiple selections, and whether it is constrained by reference data:

entity_type = svi.admin.entity_types.get(name=document.document_type)
field = entity_type.field("<your-field-name>") if entity_type is not None else None

if field is not None:
print(field.to_dict())
print(field.data_type)
print(field.logical_data_type)
print(field.allow_multiple_selections)
print(field.required)
print(field.writable)
print(field.constraining_list_name)

When a field is backed by reference data, you can inspect its valid codes before updating:

if field is not None:
options = field.resolve_reference_options()
print([(item.code, item.label) for item in options[:10]])

The handwritten document layer serializes several common Python values for you based on that field metadata. A value the field cannot take raises DocumentOperationError before anything is sent; the SDK never truth-tests, truncates or stores the repr() of a value to make it fit.

Field data_typeAccepted Python valuesSent asRefused
STRINGstr; int, float, Decimal, bool, UUID; date, datetimethe string; numbers and bool as their text; dates as ISOdict, bytes, set, other objects (encode first)
BOOLEANTrue, False, 0, 1; "true", "false", "yes", "no", "1", "0" (any case)true or falseevery other value, including other strings
INTEGER, LONG, SMALLINTint; a float or Decimal with no fractional part; an integer stringan integer2.5, "1.5", NaN, dates, mappings
FLOAT, DOUBLE, NUMERICint, float, Decimal, a numeric stringa float (a Decimal past about 15 significant digits loses precision)NaN, infinity, non-numeric strings, mappings
DATEdate, datetime, an ISO date stringYYYY-MM-DD; a datetime reduced to its calendar date in its own zoneanything else
TIMESTAMP, TIMESTAMP_WITH_TIME_ZONEdatetime, date, an ISO timestamp stringISO 8601; a naive datetime carries no zone; a date becomes midnightanything else
USER_GROUPUserRef, GroupRef, {"id": ..., "type": ...}, (id, type), or a list of themthe chooser stringother shapes (ValidationError)
REFERENCE_DATA, JSONpassed through as given, lists includedas givennothing

Strings on the numeric and date types are sent after a successful parse (" 7 " becomes 7); ISO date and timestamp strings are sent as given, unparsed.

String fields​

Use plain Python strings for normal text fields. Numbers, booleans, UUIDs and dates are converted to their text form. A dict, bytes, set or any other object is refused: encode a JSON-like value with json.dumps first, and a user or group reference with sasvi.values.serialize_user_group_value.

document.update_fields(**{
"investigation_name": "Review Required",
"investigation_summary": "Opened from the SDK guide example.",
})

Integer and decimal-like numeric fields​

Use Python numbers. The SDK coerces integer-like fields to int and decimal/float-like fields to float. A numeric string is parsed. An integer field refuses a value with a fractional part (2.0 is accepted, 2.5 is not) rather than truncating it, and a numeric field refuses NaN and infinity because JSON cannot carry them.

document.update_fields(**{
"transaction_count": 4,
"currency_amount": 1250.75,
})

Boolean fields​

Use True or False. For values that arrive as text (a CSV column, a configuration file), the strings "true", "false", "yes", "no", "1" and "0" are read in any case, and the integers 0 and 1 are accepted. Every other value, including the string "off" or an empty string, raises DocumentOperationError; a string is never truth-tested.

document.update_fields(**{"is_review_required": True})

Date fields​

Use datetime.date, datetime.datetime, or an ISO date string. The SDK serializes DATE fields as YYYY-MM-DD. A datetime is reduced to its calendar date in its own time zone: an aware 2026-05-13T23:30+05:00 is sent as 2026-05-13, not converted to UTC first. Convert it yourself when the UTC date is the one you mean.

import datetime as dt

document.update_fields(**{
"start_dt": dt.date(2026, 5, 13),
"end_dt": "2026-05-31",
})

Timestamp fields​

Use datetime.datetime, datetime.date, or an ISO timestamp string. The SDK serializes TIMESTAMP and TIMESTAMP_WITH_TIME_ZONE values to ISO format. A naive datetime is sent without a zone and the server decides which zone it is in; pass an aware datetime when that matters. A date is sent as midnight on that day, also without a zone.

import datetime as dt

document.update_fields(**{
"review_started_at": dt.datetime(2026, 5, 13, 14, 30, tzinfo=dt.timezone.utc),
"review_completed_at": "2026-05-13T15:00:00Z",
})

Reference data fields​

For REFERENCE_DATA fields, pass the reference-data code you want to store. Pass one code, not a list: on the Visual Investigator release this SDK is tested against, reference-data fields do not allow multiple selections (see Multi-select fields below), and the SDK rejects a list for a single-value field before anything is sent.

document.update_fields(priority_cd="medium")

For normal constrained reference-list fields, inspect the configured options from the entity field:

field = entity_type.field("priority_cd") if entity_type is not None else None
if field is not None:
options = field.resolve_reference_options()
print([(item.code, item.label) for item in options])

Cascading reference-data hierarchy fields expose their filter metadata on the field definition, but the hierarchy values themselves are not modeled as first-class SDK reference-list objects.

User and user group chooser fields​

For VI chooser fields the tenant reports as USER_GROUP in data_type or logical_data_type, use UserRef and GroupRef.

The SDK writes a UserRef, a GroupRef, or a list of them as the chooser string whatever type the tenant reports for the field. That matters for fields provisioned through the manifest tooling. The tenant stores those as plain STRING with no selection strategy, so the field metadata cannot tell them apart from text. Plain {"id": ..., "type": ...} dicts and (id, type) tuples convert only when the field reports USER_GROUP. On a STRING-reported field, encode them first with sasvi.values.serialize_user_group_value.

from sasvi import GroupRef, UserRef

document.update_fields(**{
"manager_review_owner": UserRef("sas"),
"manager_review_group": GroupRef("reviewers"),
})

For multi-select chooser fields, pass a list:

from sasvi import GroupRef, UserRef

document.update_fields(**{
"manager_review_watchers": [
UserRef("analyst"),
GroupRef("reviewers"),
]
})

The SDK also accepts the lower-level chooser shapes if you need them:

document.update_fields(**{
"manager_review_owner": {"id": "sas", "type": "user"},
"manager_review_group": ("reviewers", "group"),
})

Multi-select fields​

When a field's allow_multiple_selections is True, pass a list. The SDK coerces each item by the field's type and sends a list. A list for a single-value field of a scalar data type (STRING, BOOLEAN, the integer, decimal, date and timestamp types) raises DocumentOperationError before anything is sent. A JSON or REFERENCE_DATA field passes a list through as given, because a JSON field takes sequences as values.

On the Visual Investigator release this SDK is tested against, only user and group chooser fields allow multiple selections; the server refuses the setting on reference-data fields.

from sasvi import GroupRef, UserRef

document.update_fields(
investigation_owner=[UserRef("sas"), GroupRef("reviewers")],
)

Raw passthrough cases​

If the field metadata is missing or the data type is not one of the handwritten coercion cases, the SDK leaves your value largely as-is. In practice, the documented handwritten coercions cover:

  • STRING
  • BOOLEAN
  • DATE
  • TIMESTAMP
  • TIMESTAMP_WITH_TIME_ZONE
  • INTEGER
  • LONG
  • SMALLINT
  • FLOAT
  • DOUBLE
  • NUMERIC
  • JSON
  • REFERENCE_DATA
  • USER_GROUP via data_type or logical_data_type

If you are unsure how a field behaves, inspect its metadata first and then test with a small update against a safe document.

Bound document managers​

Once you have a bound Document, the object exposes manager-style helpers for the operations that usually follow retrieval.

Assume the examples below start from a bound document:

document = svi.documents.get(
entity_type_name="<your-entity-type>",
document_id="<your-document-id>",
)

Comments​

if document is not None:
document.comments.create(text="Reviewed by analyst", category="GENERAL")
comments = document.comments.list(limit=10)
print(comments)

The category is the only property of a comment the Data Hub lets you change afterwards; the text, author, and timestamps stay as written so the audit trail is accurate. categories() returns the categories in use with a count each:

if document is not None:
comment = document.comments.list(limit=1)[0]
moved = document.comments.update_category(comment_id=comment.id, category="TRIAGE")
print(moved.category, moved.author_name)
for entry in document.comments.categories():
print(entry.category, entry.count)

update_category raises DocumentNotFoundError when no comment has that id. Both helpers have _async twins.

Files​

Attachments are the general-purpose file helpers for upload, download, and metadata updates.

from pathlib import Path

sample_path = Path("sample.txt")
sample_path.write_text("Reviewed by analyst\n", encoding="utf-8")

if document is not None:
attachment = document.attachments.upload(
file=sample_path.read_bytes(),
name=sample_path.name,
)
downloaded = document.attachments.download(attachment_id=str(attachment.id))
Path("sample-downloaded.txt").write_bytes(downloaded)
document.attachments.delete(attachment_id=str(attachment.id))

Without category=, or with category="Attachment", an upload is filed under the Attachment category. Pass another of the entity type's file categories and the SDK attaches the file under it through the Data Hub files route; the attachments route would store it as Attachment whatever you passed. The service refuses a category the entity type does not declare. If it stores the file under a different category than the one you asked for, the upload raises DocumentOperationError; the file is still attached, so delete it with attachments.delete() before you retry.

attachments.list() and attachments.get() return every file of the Attachment category, whatever its content type, and every file of another category that is not an image. An image filed under a category is what VI's image gallery shows; images.list() returns it and attachments.list() does not.

A delete reads the file's ETag and sends it as If-Match. This applies to attachments.delete, images.delete, their async twins and a child's images.delete. When the file changed after that read, the service answers 412 and the delete raises DocumentConflictError with status_code=412. The SDK does not resend the delete without If-Match, so it never removes a file another writer just changed. Read the file again, decide, and retry. The delete goes out without If-Match only when the service gives no ETag for the file, and the SDK logs a WARNING when that happens.

Use the async variants when your application is already running an event loop:

from pathlib import Path


async def fetch_first_attachment(document):
attachments = await document.attachments.list_async()
if not attachments:
return None
downloaded = await document.attachments.download_async(attachment_id=str(attachments[0].id))
target = Path("async-download.bin")
target.write_bytes(downloaded)
return target

Large files​

Pass a path or an open binary file to upload and the SDK streams it in 256 KiB chunks. Use download_to or iter_bytes to read an attachment the same way. Memory use stays at a few chunks, whatever the file size.

from pathlib import Path

if document is not None:
attachment = document.attachments.upload(file=Path("evidence.zip"))

saved = document.attachments.download_to("evidence-copy.zip", attachment_id=str(attachment.id))

for chunk in document.attachments.iter_bytes(attachment_id=str(attachment.id)):
... # hash it, forward it, or write it somewhere else

download_to writes a temporary file with mode 0600 in the destination directory and moves it into place after the last byte. A failed download leaves an existing file untouched. A symlink at the destination is refused, and overwrite=False raises FileExistsError when the path is taken. The async twins are download_to_async and iter_bytes_async (async for).

The limits:

  • upload(file=bytes) and download() still hold the whole file in memory. Keep them for small files.
  • A streamed download counts against max_response_bytes (1 GiB by default) and raises ResponseTooLargeError past it. Raise the setting on the client to fetch a larger attachment.
  • An upload has no SDK-side size limit. The tenant's file service sets one.
  • An upload is a POST, which the default retry_methods leave out, so a connection that drops mid-body raises and nothing is resent. A path or a seekable file object can be sent again from the start, which the 401 re-authentication and the upload-folder retry below rely on. A stream that cannot seek is sent once.
  • A file object is sent from its current position. When the SDK cannot tell how many bytes are left (a pipe, a text-mode file), it sends the body chunked.
  • A streamed download is one request. It is not retried, and request_deadline_seconds does not bound it. The per-read timeout still applies.

An upload stores the file in the upload folder, then attaches it to the document. When the attach step does not finish, including on Ctrl-C or a cancelled task, the SDK deletes the stored file. When that delete fails too, the SDK logs a WARNING with the file id and raises the original error.

The SDK caches the URI of the upload folder. When the file service answers 404 or 409 to a cached URI, the SDK drops the entry, logs a WARNING, looks the folder up again and sends the upload once more. A second failure raises. An upload_folder_uri you pass yourself is never swapped. client.forget_upload_folders() still clears the cache by hand.

Images use the image-specific helper surface instead of the general attachment manager. Pass category= with one of the entity type's image categories (see Child fields and image categories for how to read them). VI's image gallery shows only images filed under an image category. Without category=, the image is stored as an ordinary attachment: images.list() returns it, but VI does not show it as an image.

from pathlib import Path

image_path = Path("photo.png") # Assume this file already exists locally.

if document is not None:
image = document.images.upload(
file=str(image_path),
name=image_path.name,
category="<your-image-category>",
)
print(image.category)
downloaded = document.images.download(attachment_id=str(image.id))
print(len(downloaded))
document.images.delete(attachment_id=str(image.id))

images.list() returns every file on the document whose content type is an image, whatever its category, so it includes images uploaded in VI. attachments.list() leaves out images filed under an image category; an image of the Attachment category appears in both lists. If the service stores an uploaded image under a different category than the one you asked for, the upload raises DocumentOperationError. The image is still attached at that point; delete it with images.delete() before you retry.

Insights​

Use insights when you want analyst notes and analyst-facing visualizations inside the document:

from sasvi.insights import InsightCell

if document is not None:
insight = document.insights.create(
name="Analyst Notes",
cells=[InsightCell.text("<p>Opened for review</p>")],
)
insight.cells.add_text(contents="<p>Second note</p>", width=6)
print(insight.to_markdown())

Add richer cells when the sheet needs more context:

if document is not None:
insight = document.insights.create(name="Review Sheet")
image_cell = insight.cells.add_image(
contents="/path/to/existing/image.png",
width=5,
)
table_cell = insight.cells.add_table_from_documents(
documents=[document],
columns=[
"_label",
"<your-score-field>",
("<your-related-field>", "Related field"),
],
width=6,
)
summary_cell = insight.cells.add_summary_from_documents(
documents=[document],
fields=["<your-score-field>", ("<your-related-field>", "Related field")],
width=6,
)
timeline_cell = insight.cells.add_timeline_from_documents(
documents=[document],
events=[
"<your-created-timestamp-field>",
("<your-updated-timestamp-field>", "Last updated"),
],
width=8,
)
network_cell = insight.cells.add_network_from_documents(
documents=[
{
"type": document.document_type,
"id": document.document_id,
"displayLabel": document.label,
},
{
"type": "<your-related-entity-type>",
"id": "<related-document-id>",
"displayLabel": "Related document",
},
],
links=[(document.document_id, "<related-document-id>")],
width=8,
)
print(image_cell.id, table_cell.id, summary_cell.id, timeline_cell.id, network_cell.id)

Bound insight.cells.add_image(...) materializes the source immediately. Pass an existing local path, bytes or a file-like object, an HTTP/data URL, or an existing uploaded document image path. If you want to build a raw image cell payload without runtime validation, use InsightCell.image(...) directly.

Map cells use explicit coordinate fields:

if document is not None:
insight = document.insights.create(name="Geo Sheet")
map_cell = insight.cells.add_map_from_documents(
documents=[
{
"type": "<your-location-entity-type>",
"id": "<your-location-document-id>",
"displayLabel": "Location",
"fieldValues": {"latitude": 35.8024, "longitude": -78.6522},
}
],
latitude_field="latitude",
longitude_field="longitude",
zoom=18,
)
print(map_cell.id)

Fetched cells are typed automatically:

from sasvi.documents import TableInsightCellHandle, TimelineInsightCellHandle

if document is not None:
insight = document.insights.get(insight_id=123)
if insight is not None:
for cell in insight.cells.list():
if isinstance(cell, TableInsightCellHandle):
print(cell.table_result)
elif isinstance(cell, TimelineInsightCellHandle):
print(cell.timeline_view_range)

Document-level event metadata is also available directly from a bound document:

if document is not None:
print([item.to_dict() for item in document.location_items()])
print([item.to_dict() for item in document.time_items()])
print([item.to_dict() for item in document.time_location_items()])

These three read the entity type's event configuration through a reader that SVIClient gives its client.documents. A DocumentCollection you build yourself has none unless you pass entity_event_metadata=, and the three methods then raise DocumentOperationError ("requires entity metadata support") before any request.

Move and remove cells when you want to update one part of the sheet without rewriting the whole payload:

if document is not None:
insight = document.insights.create(name="Triage Notes")
first = insight.cells.add_text(contents="<p>First</p>")
second = insight.cells.add_text(contents="<p>Second</p>")
moved = insight.cells.move(cell_id=second.id, position=0)
insight.cells.remove(cell_id=first.id)
print(moved.position)

Workspaces​

Use workspaces when you want a visual investigation canvas with nodes and links:

Node styling and custom labels are not stored

This Visual Investigator version does not store workspace node styling or custom node labels. The server accepts the write and drops those values. Tested against a live tenant on 2026-09-16. WorkspaceNode.style(...) and WorkspaceNode.update(...) read the node back after the write and log a WARNING that names each field the server did not keep. The SDK does not check a label= passed to nodes.add_document(...) for a new node, and the label will not survive a reload. The nodes on a workspace are stored, and so are the links you add between them with workspace.relationships.add(...).

if document is not None:
workspace = document.workspaces.create(name="Case Workspace")
node = workspace.nodes.add_document(
document,
label="Primary entity",
position=(10, 20),
)
workspace.layout.set({"mode": "grid"})
print(node.id)

Read the current layout before you replace it:

if document is not None:
workspace = document.workspaces.create(name="Layout Review")
current_layout = workspace.layout.get()
workspace.layout.set({"mode": "grid"})
print(current_layout)

Manage canvas relationships directly from the bound workspace:

if document is not None:
workspace = document.workspaces.create(name="Relationship Review")
node = workspace.nodes.add_document(document, label="Primary entity")
relationship = workspace.relationships.add(
source_id=node.id,
target_id=node.id,
label="Self reference",
)
print(workspace.relationships.list())
workspace.relationships.remove(relationship_id=relationship.id)

Every workspace edit is applied to the sheet as the service holds it when the SDK has the document lock, not to the copy the handle holds. Adding a node adds that node and its documents entry. Removing a node removes it, its edges and its documents entry. style(...), update(...) and layout.set(...) write only what you changed. A node or edge a colleague added in the meantime is kept. An edit of a node or edge that a colleague has deleted raises DocumentOperationError naming it, and nothing is written. Call workspace.refresh() and decide again.

Nodes can hydrate back to the bound document they represent:

if document is not None:
workspace = document.workspaces.create(name="Node Review")
node = workspace.nodes.add_document(document, label="Primary entity")
bound_document = node.document
print(bound_document.document_id if bound_document is not None else None)
workspace.nodes.remove(node_id=node.id)

Duplicate a workspace when you want to branch an existing analyst flow:

if document is not None:
workspace = document.workspaces.create(name="Original Workspace")
copy = workspace.duplicate(name="Original Workspace Copy")
print(copy.id)

Copy insights or workspaces from another document with copy_from. The source is a bound document or a (type, id) tuple; every id is checked to be a sheet of the right kind on the source before the copy is sent, and copying a document onto itself is refused:

source = svi.documents.get(entity_type_name="<your-entity-type>", document_id="<source-id>")
if document is not None and source is not None:
new_insights = document.insights.copy_from(
source, insight_ids=[item.id for item in source.insights.list()]
)
new_workspaces = document.workspaces.copy_from(
source, workspace_ids=[item.id for item in source.workspaces.list()]
)
print([item.name for item in new_insights], [item.name for item in new_workspaces])

Both return only the sheets the copy created, in tab order, and both have _async twins.

Relationships​

if document is not None:
relationships = document.relationships.list(limit=20)
print(relationships)

Create a relationship without building the raw RelationshipLink payload yourself:

if document is not None:
created = document.relationships.create(
("organisation", "<other-document-id>"),
relationship="supplier__organisation",
field_values={"role": "owner"},
)
print(created.id)

If there is exactly one valid relationship type between the two endpoint types, you can omit relationship=:

if document is not None:
created = document.relationships.create(("organisation", "<other-document-id>"))
print(created.relationship_type_name)

The same bound create(...) method also supports the raw relationship payload escape hatch:

if document is not None:
created = document.relationships.create(
body={
"@type": "DocumentLink",
"relationshipTypeName": "organisation",
"qualifiedTypeName": "supplier__organisation",
"fromObjectTypeName": "supplier",
"fromObjectId": "<from-id>",
"toObjectTypeName": "organisation",
"toObjectId": "<to-id>",
}
)
print(created.id)

Like workflows.start(...), the bound relationship helper uses one method name for both shapes: use either create(other, ...) or create(body=...), but do not mix them in the same call.

You can also discover or create relationships from the root document service:

choices = svi.documents.relationships.between(
from_document=("supplier", "<from-id>"),
to_document=("organisation", "<to-id>"),
)
print([item.qualified_name or item.name for item in choices])

created = svi.documents.relationships.create(
from_document=("supplier", "<from-id>"),
to_document=("organisation", "<to-id>"),
relationship="supplier__organisation",
)
print(created.id)

Links are addressed by id from then on. get returns None for an unknown id; update reads the link and its ETag, merges your changes, and sends the result back with If-Match, so an edit that races another writer fails with DocumentConflictError instead of overwriting it. Pass a RelationshipLinkUpdate, or the same three fields as keywords; None means "leave unchanged", and clearing a validity bound needs the raw body= form. Validity bounds only persist on relationship types that define a validity window; elsewhere the server accepts the PUT and drops them silently (live-verified), so read the link back when it matters.

from datetime import datetime, timezone

from sasvi.documents import RelationshipLinkUpdate

if document is not None:
link = document.relationships.get(relationship_link_id="<link-id>")
if link is not None:
print(
link.field_values_dict(), link.other_end(document.document_type, document.document_id)
)
edited = document.relationships.update(
relationship_link_id="<link-id>",
changes=RelationshipLinkUpdate(
field_values={"role": "reviewer"},
valid_to=datetime(2030, 1, 1, tzinfo=timezone.utc),
),
)
print(edited.valid_to)

Every link keeps a version history (field values per version) and an action history (who did what). Both are available on the bound manager, which first checks that the link touches the bound document, and on the root service:

if document is not None:
for version in document.relationships.versions(relationship_link_id="<link-id>"):
print(version.version, version.operation, version.created_by)
detail = document.relationships.version(relationship_link_id="<link-id>", version=2)
if detail is not None:
print([value.name for value in detail.changed_values])
for action in document.relationships.actions(
relationship_link_id="<link-id>", action_type="RELATIONSHIP_EDIT"
):
print(action.action_id, action.created_at)

versions = svi.documents.relationships.versions_all(relationship_link_id="<link-id>")
svi.documents.relationships.remove(relationship_link_id="<link-id>")

remove detaches the two documents and leaves both intact. The root service (between, for_types, create, get, update, versions, versions_all, version, actions, actions_all, action, remove) has an _async twin for every method; the bound manager mirrors them. There is no patch(): the generated PATCH binding for links is unusable (see the contributing notes on upstream spec issues), so edits go through the guarded PUT.

History​

A document keeps two trails. Versions are snapshots of its field values; actions are the audit log of what was done to it (edits, comments, files, links). Both page, and both have _all variants that walk every page.

if document is not None:
for version in document.history.versions(limit=10):
print(version.version_number, version.operation, version.created_by, version.created_at)

latest = document.history.versions()[0]
snapshot = document.history.version(version=latest.version, changed_only=True)
if snapshot is not None:
for value in snapshot.changed_values:
print(value.name, value.previous_value, "->", value.value)
print(document.history.version_items(version=latest.version))

for action in document.history.actions(action_type=["DOCUMENT_EDIT", "COMMENT_CREATE"]):
print(action.action_type, action.action, action.created_by)
detail = document.history.action(action_id=document.history.actions()[0].action_id)
if detail is not None:
print([item.kind for item in detail.items])

field = document.history.field("<your-field-name>", version=latest.version_number)
print(field.value if field is not None else None)

action_type accepts one value or a list of sasvi.types.ActionType; anything outside that closed set is rejected before the request is sent. version, action, and field return None when the version, action, or field does not exist.

Child documents expose versions, version, version_items, and field on child.history; the Data Hub keeps child versions per parent version, so child.history.version(version=...) takes the parent version (entry.parent_version on a listed child version). There is no child action history in the API.

Children​

if document is not None:
child_types = document.children.types()
print(child_types)

Child documents are stored inside the parent, so creating, updating or deleting one rewrites the parent document. The SDK takes the parent's edit lock, reads it, applies your change and writes it back with a precondition from that same read. An edit another writer commits while that is in flight is therefore either included or refused with DocumentConflictError, never silently overwritten. Catch DocumentConflictError and retry from a fresh handle.

If you already know the child type name, work through the typed child collection:

if document is not None:
children = document.children.of("<your-child-entity-type>")
child = children.create(field_values={"<your-child-field>": "<your-child-value>"})
print(child.child_id)

Reference-data fields take the item's code. For how to list the valid codes of a child field, see Child fields and image categories.

To create a child with images in one operation, pass images=. Each image needs the category name of one of the child type's image categories.

from sasvi.documents import ChildImageCreateInput

if document is not None:
child = document.children.of("<your-child-entity-type>").create(
field_values={"<your-child-field>": "<your-child-value>"},
images=[
ChildImageCreateInput(
file="front.png",
content_type="image/png",
category="<your-image-category>",
),
],
)
print([image.id for image in child.images.list()])

child.images has _async twins for every call (list_async, get_async, download_async, upload_async and delete_async), as does the parent document's document.images.

The SDK does not check the category. The server does. It refuses an unknown or a missing category with DocumentOperationError before it creates the child, and the SDK then tries to delete the uploaded file. This was verified live against a category that is optional and allows several images. Required and single-image categories are untested.

Filter and batch-read documents​

list() takes a plain page by default. Add where= (field equality), a raw filter_= expression, or sort_by= and the read switches to the Data Hub's filtered collection endpoint:

open_items = svi.documents.list(
entity_type_name="<your-entity-type>",
where={"status": "OPEN", "priority": 2},
sort_by="<your-updated-timestamp-field>:descending",
limit=20,
)
print([item.document_id for item in open_items])

everything = svi.documents.list_all(
entity_type_name="<your-entity-type>",
filter_="or(eq(status,'OPEN'),eq(status,'ESCALATED'))",
batch_size=100,
max_items=1000,
)

The filtered endpoint accepts a deliberately small grammar, and the SDK does not widen it:

  • Only eq, and, and or. There is no ge/le/contains; use the search builder for range and text queries.
  • Names are the entity type's field names, not table column names.
  • Filterable field types: STRING, INTEGER, SMALLINT, LONG, NUMERIC, BOOLEAN, and REFERENCE_DATA (compare against the item's code).
  • Child-document fields cannot be filtered.
  • sort_by is "<field>:ascending" or "<field>:descending".

where= and filter_= are ANDed when both are given. A where key that is not a valid field identifier raises ValidationError before any request.

When you already hold ids, get_many fetches them in chunks of 100 and returns bound documents in your order. Ids the server does not know are omitted, so compare the lengths when every document must exist:

documents = svi.documents.get_many(
entity_type_name="<your-entity-type>",
document_ids=["<id-1>", "<id-2>", "<id-3>"],
)
print(len(documents))

list, list_all, and get_many all have _async twins.

Create a managed document​

Use DocumentCollection.create() for managed entity types:

created = svi.documents.create(
entity_type_name="<your-entity-type>",
field_values={
"<your-first-field>": "<your-first-value>",
"<your-second-field>": "<your-second-value>",
},
)
print(created.document_id)

From async code, await svi.documents.create_async(...) takes the same arguments, sends the same two requests (one entity-type read, then the POST) and returns the same Document.

Go further​

Original SAS API docs​