Developer Interface

Entity API

This part of the documentation covers all the interfaces of pyPreservica EntityAPI object.

class pyPreservica.EntityAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook: Callable | None = None, credentials_path: str = 'credentials.properties')[source]

A class for the Preservica Repository web services Entity API

https://us.preservica.com/api/entity/documentation.html

The EntityAPI allows users to interact with the Preservica repository

add_access_representation(entity: Entity, access_file: str, name: str = 'Access')[source]

Add a new Access representation to an existing asset.

Parameters:
  • entity (Entity) – The existing asset which will receive the new representation

  • access_file (str) – The new digital file

  • name (str) – The name of the new access representation defaults to “Access”

Returns:

add_group_metadata(csv_file: str) str[source]

Perform bulk additions of metadata with a CSV file. This is designed for metadata which populates a New Gen Metadata Group Returns The process ID which will track the updates Requires DataManagement permission

Parameters:

csv_file (str) – The path of the CSV metadata file

Returns:

The process ID

Return type:

str

add_identifier(entity: Entity, identifier_type: str, identifier_value: str)[source]

Add a new external identifier to an Entity object.

Parameters:
  • entity (Entity) – The entity the identifier is added to.

  • identifier_type (str) – The identifier type label (e.g. "ISBN", "DOI").

  • identifier_value (str) – The identifier value.

Returns:

The internal API id assigned to the newly created identifier, or None if the response did not include one.

Return type:

str or None

Raises:

RuntimeError – If the connected Preservica system is older than v6.1.

add_metadata(entity: EntityT, schema: str, data) EntityT[source]

Add a new descriptive XML document to an existing entity

Parameters:
  • entity (Entity) – The entity to add the metadata to

  • schema (str) – The metadata schema URI

  • data (data) – The XML document as a string or as file bytes

Returns:

The updated entity with the new metadata

Return type:

Entity

add_metadata_as_fragment(entity: EntityT, schema: str, xml_fragment: str) EntityT[source]

Add a metadata fragment with a given namespace URI to an Entity Don’t parse the xml fragment which may add extra namespaces etc

Returns The updated Entity

Parameters:
  • xml_fragment (str) – The new XML as a string

  • entity (Entity) – The entity to update

  • schema (str) – The schema URI of the XML document

Return type:

Entity

add_physical_asset(title: str, description: str, parent: Folder, security_tag: str = 'open') Asset[source]

Create a new asset which represents a physical object

Returns Asset

Parameters:
  • title (str) – The title of the new Asset

  • description (str) – The description of the new Asset

  • parent (Folder) – The parent folder

  • security_tag (str) – The security tag, defaults to open

Returns:

The new physical object

Return type:

Asset

add_relation(from_entity: Entity, relationship_type: str, to_entity: Entity)[source]

Add a new relationship link between two Assets or Folders

Parameters:
  • from_entity (Entity) – The Source entity to link from

  • to_entity (Entity) – The Target entity

  • relationship_type (str) – The Relationship type

Returns:

relationship_type

Return type:

str

add_thumbnail(entity: Entity, image_file: str)[source]

Set the thumbnail for the entity to the uploaded image

Supported image formats are png, jpeg, tiff, gif and bmp. The image must be 10MB or less in size.

Parameters:
  • entity (Entity) – The entity

  • image_file (str) – The path to the image

all_descendants(folder: Folder | str | Entity | None = None) Generator[Entity, None, None][source]

Return all child entities recursively of a folder or repository down to the assets using a lazy iterator. The paging is done internally using a default page size of 100 elements. Callers can iterate over the result to get all children with a single call.

Parameters:

folder (str) – The parent folder reference, None for the children of root folders

Returns:

A set of entity objects (Folders and Assets)

Return type:

set(Entity)

all_events() Generator[source]

Returns a list of events for the user’s tenancy

This method uses a generator function to make repeated calls to the server for every page of results.

Returns:

A generator of events

Return type:

Generator

all_ingest_events(previous_days: int = 1) Generator[source]

Returns a list of ingest only events for the user’s tenancy

This method uses a generator function to make repeated calls to the server for every page of results.

Parameters:

previous_days (int) – The number of days to look back for events

Returns:

A generator of events

Return type:

Generator

all_metadata(entity: Entity) Generator[Tuple[str, str], None, None][source]

Retrieve all metadata fragments on an entity.

Yields each descriptive XML document attached to the entity as a two-element tuple whose first element is the schema URI and whose second element is the XML document text.

Parameters:

entity (Entity) – The entity whose metadata fragments should be retrieved.

Returns:

Generator that yields (schema_uri, xml_document) tuples, one per metadata fragment attached to the entity.

Return type:

Generator[Tuple[str, str], None, None]

asset(reference: str) Asset[source]

Returns an asset object back by its internal reference identifier

Parameters:

reference (str) – The unique identifier for the asset usually its uuid

Returns:

The Asset object

Return type:

Asset

Raises:

RuntimeError – if the identifier is incorrect

bitstream(url: str) Bitstream[source]

Fetch a bitstream object from the server using its URL

Parameters:

url (str) – The URL to the bitstream

Returns:

a bitstream object

Return type:

Bitstream

bitstream_bytes(bitstream: Bitstream, chunk_size: int = 4096) BytesIO[source]

Download a file represented as a Bitstream to a byteIO array

Returns the byteIO Returns None if the file does not contain the correct number of bytes (default 2k)

Parameters:
  • chunk_size – The buffer copy chunk size in bytes default

  • bitstream (Bitstream) – A Bitstream object

Returns:

The file in bytes

Return type:

byteIO

bitstream_chunks(bitstream: Bitstream, chunk_size: int = 4096) Generator[source]

Generator function to return bitstream chunks, allows the clients to process chunks as they are downloaded.

Parameters:
  • bitstream (Bitstream) – A bitstream object

  • chunk_size (int) – Optional size of the chunks to be downloaded

Returns:

Iterator

Return type:

Generator

bitstream_content(bitstream: Bitstream, filename: str, chunk_size: int = 4096) int[source]

Download a file represented as a Bitstream to a local filename

Returns the number of bytes written to the file Returns None if the file does not contain the correct number of bytes

Parameters:
  • chunk_size – The buffer copy chunk size in bytes default

  • bitstream (Bitstream) – A Bitstream object

  • filename (str) – The filename to write the bytes to

Returns:

The size of the file in bytes

Return type:

int

bitstream_location(bitstream: Bitstream) list[source]

” Retrieves information about a bitstreams storage locations

Parameters:

bitstream (Bitstream) – The bitstream object

Returns:

A list of strings containing all the storage locations of this bitstream

Return type:

list

bitstreams_for_asset(asset: Asset | Entity) Iterable[Bitstream][source]

Return all the active bitstreams within an asset. This includes all the representations and content objects

Parameters:

asset – The asset

Returns:

Iterable

children(folder: str | Folder | None = None, maximum: int = 100, next_page: str = None) PagedSet[source]

Return the child entities of a folder one page at a time. The caller is responsible for requesting the next page of results.

This function is deprecated, use descendants instead as the paging is automatic

Parameters:
  • folder (str) – The parent folder reference, None for the children of root folders

  • maximum (int) – The maximum size of the result set in each page

  • next_page (str) – A URL for the next page of results

Returns:

A set of entity objects

Return type:

set(Entity)

content_object(reference: str) ContentObject[source]

Returns a content object back by its internal reference identifier

Parameters:

reference (str) – The unique identifier for the content object usually its uuid

Returns:

The content object

Return type:

ContentObject

Raises:

RuntimeError – if the identifier is incorrect

content_objects(representation: Representation) list[ContentObject][source]

Return a list of content objects for a representation

Parameters:

representation (Representation) – The representation

Returns:

List of content objects

Return type:

list(ContentObject)

create_folder(title: str, description: str, security_tag: str, parent: str = None) Folder[source]

Create a new Folder in the repository If parent is None then the new Folder will be created at the root of the repository

Returns The updated Entity

Parameters:
  • title – The title of the new folder

  • description – The description of the new folder

  • security_tag – The security_tag of the new folder

  • parent – The parent of the new folder, Can be None to create a root Folder

delete_asset(asset: Asset, operator_comment: str, supervisor_comment: str, credentials_path: str = 'credentials.properties')[source]

Initiate and approve the deletion of an asset.

Parameters:
  • credentials_path

  • asset (Asset) – The asset to delete

  • operator_comment (str) – The comments from the operator which are added to the logs

  • supervisor_comment (str) – The comments from the supervisor which are added to the logs

Returns:

The asset reference

Return type:

str

delete_folder(folder: Folder, operator_comment: str, supervisor_comment: str, credentials_path: str = 'credentials.properties')[source]

Initiate and approve the deletion of a folder.

Parameters:
  • folder (Folder) – The folder to delete

  • operator_comment (str) – The comments from the operator which are added to the logs

  • supervisor_comment (str) – The comments from the supervisor which are added to the logs

Returns:

The folder reference

Return type:

str

delete_identifiers(entity: Entity, identifier_type: str | None = None, identifier_value: str | None = None) Entity[source]

Delete identifiers on an Entity object

Setting identifier_type and identifier_value to None acts a wildcard deleting all identifiers on the entity

Parameters:
  • entity (Entity) – The entity the identifiers are deleted from

  • identifier_type (str) – The identifier type

  • identifier_value (str) – The identifier value

Returns:

entity

Return type:

Entity

delete_metadata(entity: Entity, schema: str) EntityT[source]

Delete an existing descriptive XML document on an entity by its schema This call will delete all fragments with the same schema

Parameters:
  • entity (Entity) – The entity to add the metadata to

  • schema (str) – The metadata schema URI

Returns:

The updated Entity

Return type:

Entity

delete_relationships(entity: Entity, relationship_type: str | None = None)[source]

Delete a relationship between two entities by its internal id

This function only deletes the relationship FROM the specified entity to another entity It does not delete relationships TO this entity

If relationship_type is not specified all relationships FROM this entity are deleted.

Parameters:
  • entity (Entity)

  • relationship_type (str) – The relationship type to delete

descendants(folder: Folder | str | Entity | None = None) Generator[Entity, None, None][source]

Return the immediate child entities of a folder using a lazy iterator. The paging is done internally using a default page size of 100 elements. Callers can iterate over the result to get all children with a single call.

Parameters:

folder (str) – The parent folder reference, None for the children of root folders

Returns:

A set of entity objects (Folders and Assets)

Return type:

set(Entity)

download(entity: Entity, filename: str) str[source]

Download the first generation of the access representation of an asset

Parameters:
  • entity (Entity) – The entity

  • filename (str) – The file the image is written to

Returns:

The filename

Return type:

str

download_opex(pid: str) str[source]

Download a completed OPEX export using the workflow process ID

Parameters:

pid (str) – A process id which identifiers the export workflow

Returns:

The downloaded zip file name

Return type:

str

entity(entity_type: EntityType, reference: str) EntityT[source]

Returns a generic entity based on its reference identifier

Parameters:
  • entity_type (EntityType) – The type of entity

  • reference (str) – The unique identifier for the entity

Returns:

The entity either Asset, Folder or ContentObject

Return type:

Entity

Raises:

RuntimeError – if the identifier is incorrect

entity_events(entity: Entity) Generator[source]

Returns a list of event actions performed against this entity

This method uses a generator function to make repeated calls to the server for every page of results.

Parameters:

entity (Entity) – The entity

Returns:

A list of events

Return type:

list

entity_from_event(event_id: str) Generator[source]

Returns an entity from the user’s tenancy :rtype: Generator

entity_identifiers(entity: Entity, external_identifier_type: str | None = None) set[ExternIdentifier][source]

Get all external identifiers on an entity.

Returns the set of external identifiers on the entity. When external_identifier_type is supplied, only identifiers whose type matches are returned.

Parameters:
  • entity (Entity) – The Entity (Asset or Folder) to retrieve identifiers for.

  • external_identifier_type (str or None) – Optional identifier type used to filter the results. Pass None (the default) to return all identifiers.

Returns:

Set of ExternIdentifier objects belonging to the entity.

Return type:

set[ExternIdentifier]

Raises:

HTTPException – If the API call fails.

export_opex(entity: Entity, **kwargs) str[source]

Initiates export of the entity and downloads the opex package Blocks until the package is downloaded

By default, includes content, metadata with the latest active generations and the parent hierarchy.

Arguments are kwargs map

IncludeContent IncludeMetadata IncludedGenerations IncludeParentHierarchy

Parameters:
  • entity (Entity) – The entity to export Asset or Folder

  • IncludeContent (str) – “Content”, “NoContent”

  • IncludeMetadata (str) – “Metadata”, “NoMetadata”, “MetadataWithEvents”

  • IncludedGenerations (str) – “LatestActive”, “AllActive”, “All”

  • IncludeParentHierarchy (str) – “true”, “false”

Returns:

The path to the opex ZIP file

Return type:

str

export_opex_async(entity: Entity, **kwargs) str[source]

Initiates export of the entity returns an id to track progress

export_opex_sync(entity: Entity, **kwargs) str[source]

Initiates export of the entity and downloads the opex package Blocks until the package is downloaded

By default, includes content, metadata with the latest active generations and the parent hierarchy.

Arguments are kwargs map

IncludeContent IncludeMetadata IncludedGenerations IncludeParentHierarchy

folder(reference: str) Folder[source]

Returns a folder object back by its internal reference identifier

Parameters:

reference (str) – The unique identifier for the folder usually its uuid

Returns:

The Folder object

Return type:

Folder

Raises:

RuntimeError – if the identifier is incorrect

generation(url: str, content_ref: str = None) Generation[source]

Retrieve a list of generation objects

Parameters:
  • url

  • content_ref

Returns:

Generation

Return type:

Generation

generations(content_object: ContentObject) list[Generation][source]

Return a list of Generation objects for a content object

Parameters:

content_object (ContentObject) – The content object

Returns:

list of generations

Return type:

list(Generation)

get_async_progress(pid: str) str[source]

Return the status of a running process

Parameters:

pid – The progress ID

Returns:

Workflow status

Return type:

str

has_thumbnail(entity: Entity) bool[source]

Does the entity have a thumbnail image attached Returns false if the entity has no thumbnail

Parameters:

entity – The entity

identifier(identifier_type: str, identifier_value: str) set[EntityT][source]

Return a set of entities with external identifiers which match the type and value

Parameters:
  • identifier_type (str) – The identifier type

  • identifier_value (str) – The identifier value

Returns:

Set of entity objects which have a reference and title attribute

Return type:

set(Entity)

identifiers_for_entity(entity: Entity) set[Tuple][source]

Return a set of identifiers which belong to the entity

Parameters:

entity (Entity) – The entity

Returns:

Set of identifiers as tuples

Return type:

set(Tuple)

integrity_checks(bitstream: Bitstream) Generator[source]

Return integrity checks for a bitstream

merge_assets(assets: list[Asset], title: str, description: str) str[source]

Create a new Asset with the content from each Asset in supplied list This call will create a new multipart Asset which contains all the content from list of Assets.

The return value is the progress status of the merge operation.

merge_folder(folder: Folder) str[source]

Create a new Asset with the content from each Asset in the Folder

This call will create a new multipart Asset which contains all the content from the Folder.

The new Asset which is created will have the same title, description and parent as the Folder.

The return value is the progress status of the merge operation.

metadata(uri: str) str[source]

Fetch the metadata document by its identifier URI.

The URI is the key from the entity’s metadata dict (e.g. obtained from entity.metadata). The method strips the outer XIP MetadataContainer wrapper and returns only the inner content element as an XML string.

Parameters:

uri (str) – The full URL of the metadata fragment, as stored in the entity’s metadata map.

Returns:

The inner content of the metadata document serialised as an XML string.

Return type:

str

Raises:

HTTPException – If the server returns a non-200 response.

metadata_for_entity(entity: Entity, schema: str) str | None[source]

Fetch the first metadata document which matches the schema URI from an entity.

If the entity object does not have its metadata map populated (e.g. it was obtained from a lightweight search result) the full entity is fetched from the server first.

Parameters:
  • entity (Entity) – The entity containing the metadata.

  • schema (str) – The metadata schema URI to match against.

Returns:

The first XML document on the entity whose schema URI matches, as a string, or None if no matching document is found.

Return type:

str or None

metadata_tag_for_entity(entity: Entity, schema: str, tag: str, isXpath: bool = False) str | None[source]

Retrieve the text value of a single XML element from a metadata document on an entity.

Looks up the metadata document identified by schema on entity and returns the text content of the first element matched by tag. By default tag is treated as a local element name (matched with a wildcard namespace); set isXpath to True to supply a fully qualified XPath expression instead.

Parameters:
  • entity (Entity) – The entity that holds the metadata document.

  • schema (str) – The schema URI identifying which metadata document to look up.

  • tag (str) – The element local name to find, or a fully qualified XPath expression when isXpath is True.

  • isXpath (bool) – When True, tag is treated as a fully qualified XPath expression rather than a plain element name. Defaults to False.

Returns:

The text content of the matched element, or None if the metadata document or the element cannot be found.

Return type:

str or None

move(entity: EntityT, dest_folder: Folder) EntityT[source]

Move an entity (asset or folder) to a new folder This call is an alias for the move_sync (blocking) method.

Parameters:
  • entity (Entity) – The entity to move either asset or folder

  • dest_folder (Entity) – The new destination folder. This can be None to move a folder to the root of the repository

Returns:

The updated entity

Return type:

Entity

move_async(entity: Entity, dest_folder: Folder) str[source]

Move an Entity (Asset or Folder) to a new Folder If dest_folder is None then the entity must be a Folder and will be moved to the root of the repository

Returns a process ID asynchronous (without blocking)

Returns The updated Entity

Parameters:
  • entity (Entity) – The entity to move either asset or folder

  • dest_folder (Entity) – The new destination folder. This can be None to move a folder to the root of the repository

Returns:

Progress ID token

Return type:

str

move_sync(entity: EntityT, dest_folder: Folder) EntityT[source]

Move an entity (asset or folder) to a new folder This call blocks until the move is complete

Parameters:
  • entity (Entity) – The entity to move either asset or folder

  • dest_folder (Entity) – The new destination folder. This can be None to move a folder to the root of the repository

Returns:

The updated entity

Return type:

Entity

relationships(entity: Entity, page_size: int = 25) Generator[Relationship, None, None][source]

List the relationship links between entities

Parameters:
  • page_size – The number of items returned in a single server call

  • entity – The Source Entity

Type:

page_size: int

Type:

entity: An Entity type such as Asset, Folder etc

Returns:

Generator

Return type:

Relationship

remove_thumbnail(entity: Entity)[source]

Remove the thumbnail for the entity to the uploaded image

Parameters:

entity (Entity) – The entity with the thumbnail

replace_generation_async(content_object: ContentObject, file_name, fixity_algorithm=None, fixity_value=None) str[source]

Replace the last active generation of a content object with a new digital file.

Starts the workflow and returns a process ID

Parameters:
  • content_object (ContentObject) – The content object to replace

  • file_name (str) – The path to the new content object

  • fixity_algorithm (str) – Optional fixity algorithm

  • fixity_value (str) – Optional fixity value

Returns:

Process ID

Return type:

str

replace_generation_sync(content_object: ContentObject, file_name, fixity_algorithm=None, fixity_value=None) str[source]

Replace the last active generation of a content object with a new digital file.

Starts the workflow and blocks until the workflow completes.

Parameters:
  • content_object (ContentObject) – The content object to replace

  • file_name (str) – The path to the new content object

  • fixity_algorithm (str) – Optional fixity algorithm

  • fixity_value (str) – Optional fixity value

Returns:

Completed workflow status

Return type:

str

representations(asset: Asset) set[Representation][source]

Return a set of representations for the asset

Representations are used to define how the information object are composed in terms of technology and structure.

Parameters:

asset (Asset) – The asset containing the required representations

Returns:

Set of Representation objects

Return type:

set(Representation)

save(entity: EntityT) EntityT[source]

Updates the title and description of an entity The security tag and parent are not saved via this method call

Parameters:

entity (Entity) – The entity (asset, folder, content_object) to be updated

Returns:

The updated entity

Return type:

Entity

security_tag_async(entity: Entity, new_tag: str)[source]

Change the security tag of an asset or folder This is a non blocking call which returns immediately.

Parameters:
  • entity (Entity) – The entity (asset, folder) to be updated

  • new_tag (str) – The new security tag to be set on the entity

Returns:

A progress id which can be used to monitor the workflow

Return type:

str

security_tag_sync(entity: EntityT, new_tag: str) EntityT[source]

Change the security tag of an asset or folder This is a blocking call which returns after all entities have been updated.

Parameters:
  • entity (Entity) – The entity (asset, folder) to be updated

  • new_tag (str) – The new security tag to be set on the entity

Returns:

The updated entity

Return type:

Entity

thumbnail(entity: Entity, filename: str, size=Thumbnail.LARGE)[source]

Get the thumbnail image for an asset or folder

Parameters:
  • entity (Entity) – The entity

  • filename (str) – The file the image is written to

  • size (Thumbnail) – The size of the thumbnail image

Returns:

The filename

Return type:

str

update_identifiers(entity: Entity, identifier_type: str | None = None, identifier_value: str | None = None)[source]

Update external identifiers based on Entity and Type

Returns the internal identifier DB Key

Parameters:
  • entity – The entity to delete identifiers from

  • identifier_type – The type of the identifier to delete.

  • identifier_value – The value of the identifier to delete.

update_metadata(entity: EntityT, schema: str, data: Any) EntityT[source]

Update an existing descriptive XML document on an entity

Parameters:
  • entity (Entity) – The entity to add the metadata to

  • schema (str) – The metadata schema URI

  • data (data) – The XML document as a string or as a file bytes

Returns:

The updated Entity

Return type:

Entity

updated_entities(previous_days: int = 1) Generator[source]

Fetch a list of entities which have changed (been updated) over the previous n days.

This method uses a generator function to make repeated calls to the server for every page of results.

Parameters:

previous_days (int) – The number of days to check for changes.

Returns:

A list of entities

Return type:

list

user_security_tags(with_permissions: bool = False) dict[source]

Return security tags available for the current user

Parameters:

with_permissions (bool) – Return the permissions for each security tag

Returns:

dict of security tags

Return type:

dict

xml_asset(reference: str) str[source]

Retrieve the full XML representation of an Asset by its reference UUID.

Calls the entity API with expand=structure so that the returned XML includes the complete asset structure (representations, content objects, generations, etc.).

Parameters:

reference (str) – The unique identifier (UUID) of the asset.

Returns:

The raw XML response body describing the asset and its structure.

Return type:

str

Raises:
  • ReferenceNotFoundException – If no asset with the given reference exists.

  • HTTPException – If the server returns any other non-200 response.

class pyPreservica.Generation[source]

Generations represent changes to content objects over time, as formats become obsolete new generations may need to be created to make the information accessible.

original

original generation (True or False)

active

active generation (True or False)

format_group

format for this generation

effective_date

effective date generation

bitstreams

list of Bitstream objects

properties

list of technical properties each property is dict object containing PUID, PropertyName and Value

formats

list of technical formats each format is dict object containing PUID, FormatName and FormatVersion

class pyPreservica.Bitstream[source]

Bitstreams represent the actual computer files as ingested into Preservica, i.e. the TIFF photograph or the PDF document

filename

The filename of the original bitstream

length

The file size in bytes of the original Bitstream

fixity

Dictionary object of fixity values for this bitstream, the key is the algorithm name and the value is the fixity value

class pyPreservica.Representation[source]

Representations are used to define how the information object are composed in terms of technology and structure.

rep_type

The type of representation

name

The name of representation

asset

The asset the representation belongs to

class pyPreservica.Entity[source]

Entity is the base class for assets, folders and content objects They all have the following attributes

reference

The unique internal reference for the entity

title

The title of the entity

description

The description of the entity

security_tag

The security tag of the entity

parent

The unique internal reference for this entity’s parent object

The parent of an Asset is always a Folder

The parent of a Folder is always a Folder or None for a folder at the root of the repository

The parent of a Content Object is always an Asset

metadata

A map of descriptive metadata attached to the entity.

The key of the map is the metadata identifier used to retrieve the metadata document and the value is the schema URI

entity_type

Assets have entity type EntityType.ASSET

Folders have entity type EntityType.FOLDER

Content Objects have entity type EntityType.CONTENT_OBJECT

class pyPreservica.Asset[source]

Asset represents the information object or intellectual unit of information within the repository.

reference

The unique internal reference for the asset

title

The title of the asset

description

The description of the asset

security_tag

The security tag of the asset

parent

The unique internal reference for this asset’s parent folder

metadata

A dict of descriptive metadata attached to the asset.

The key of the dict is the metadata identifier used to retrieve the metadata document and the value is the schema URI

entity_type

Assets have entity type EntityType.ASSET

class pyPreservica.Folder[source]

Folder represents the structure of the repository and contains both Assets and Folder objects.

reference

The unique internal reference for the folder

title

The title of the folder

description

The description of the folder

security_tag

The security tag of the folder

parent

The unique internal reference for this folder’s parent folder

metadata

A map of descriptive metadata attached to the folder.

The key of the map is the metadata identifier used to retrieve the metadata document and the value is the schema URI

entity_type

Assets have entity type EntityType.FOLDER

class pyPreservica.ContentObject[source]

ContentObject represents the internal structure of an asset.

reference

The unique internal reference for the content object

title

The title of the content object

description

The description of the content object

security_tag

The security tag of the content object

parent

The unique internal reference for this content object parent asset

metadata

A map of descriptive metadata attached to the content object.

The key of the map is the metadata identifier used to retrieve the metadata document and the value is the schema URI

entity_type

Content objects have entity type EntityType.CONTENT_OBJECT

class pyPreservica.EntityType(*values)[source]

Enumeration of the Entity Types

class pyPreservica.RelationshipDirection(*values)[source]

Enumeration of the two possible directions for an entity relationship.

FROM indicates that the current entity is the subject of the relationship; TO indicates that it is the object.

class pyPreservica.IntegrityCheck(check_type, success, date, adapter, fixed, reason)[source]

Class to hold information about completed integrity checks

Content API

This part of the documentation covers all the interfaces of pyPreservica ContentAPI object.

class pyPreservica.ContentAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook: Callable | None = None, credentials_path: str = 'credentials.properties')[source]

The ContentAPI class provides the search interface to the Preservica repository.

download(reference, filename) str[source]

Download the access copy of an Asset and save it to a local file.

Streams the binary content from the Preservica content-download endpoint directly to disk, flushing each chunk as it is written.

Parameters:
  • reference (str) – The UUID reference of the Asset (Information Object) to download.

  • filename (str) – Local filesystem path where the downloaded content will be written.

Returns:

The filename path that was written to.

Return type:

str

Raises:

RuntimeError – If the reference is not found in the repository (HTTP 404), or if the download fails for any other reason.

download_bytes(reference) BytesIO[source]

Download the access copy of an Asset and return it as an in-memory byte buffer.

Streams the binary content from the Preservica content-download endpoint directly into a BytesIO object. The buffer’s position is reset to zero before it is returned so callers can read from it immediately.

Parameters:

reference (str) – The UUID reference of the Asset (Information Object) to download.

Returns:

An in-memory byte buffer containing the downloaded file content, seeked to position 0.

Return type:

io.BytesIO

Raises:

RuntimeError – If the reference is not found in the repository (HTTP 404), or if the download fails for any other reason.

full_text(reference: str) str | None[source]

Return the full-text index value for an Asset.

If the Asset has been OCR’d or otherwise indexed for full-text search, this method returns the indexed text content. The reference must identify an Asset (document type IO); content objects and folders are not supported.

Parameters:

reference (str) – The UUID reference of the Asset whose full-text index value should be retrieved.

Returns:

The full-text index string for the Asset, or None if the reference is not found or does not correspond to an Asset.

Return type:

str or None

indexed_fields() dict[source]

Return all search-index field names and their associated URIs.

Queries the Preservica /api/content/indexed-fields endpoint and returns a dictionary mapping each field’s short dotted name (e.g. "xip.title", "cmis:name") to its full schema URI. This is useful for discovering which fields are available when building search queries or filter dictionaries for the various search methods.

Returns:

Dictionary mapping indexed field names ("<schema>.<index>" format) to their full schema URI strings.

Return type:

dict

Raises:

RuntimeError – If the API call fails.

object_details(entity_type, reference: str, exclude_dates: bool = False) dict[source]

Return the CMIS property bag for a single repository object.

Retrieves all indexed metadata attributes stored against the object, such as cmis:name, cmis:objectId, and custom schema fields. Date-related properties (cmis:createdBy, cmis:creationDate, cmis:lastModifiedBy, cmis:lastModificationDate) can be omitted by setting exclude_dates=True.

Parameters:
  • entity_type (EntityType or str) – The type of entity to look up. Either an EntityType enum value (e.g. EntityType.ASSET) or the raw string representation used by the API (e.g. "IO").

  • reference (str) – The UUID reference of the entity.

  • exclude_dates (bool) – When True, omits the four CMIS date/history properties from the returned dictionary.

Returns:

Dictionary of CMIS property names to their values for the requested object.

Return type:

dict

Raises:

RuntimeError – If the reference is not found in the repository (HTTP 404), or if the API call fails for any other reason.

search_callback(fn: Callable)[source]

Register a progress callback that is invoked after each search page is fetched.

The callback receives a single string argument formatted as "<fetched>:<total>" (e.g. "50:320"), allowing callers to report or act on incremental search progress.

Parameters:

fn (callable) – Callable that accepts one positional str argument.

search_fields(query: str = '%', fields: list[Field] | None = None, page_size: int = 25) Generator[source]

Run a structured search using Field objects and yield all matching result rows.

Provides a richer search interface than simple_search_list() or search_index_filter_list() by accepting a list of Field instances that can carry value filters, IS/NOT operators, and sort orders. Results are paginated automatically and yielded lazily.

Requires Preservica v7.5 or higher; raises RuntimeError on older servers.

Parameters:
  • query (str) – Lucene-style search expression. Use "%" (default) to match all objects.

  • fields (list[Field] or None) – List of Field instances specifying which index fields to retrieve and optionally filter or sort by. When None or empty, only xip.title is requested with no filters.

  • page_size (int) – Number of results to fetch per API request (default 25).

Returns:

Generator that yields one dict per matching object, with xip.reference always present as a key.

Return type:

Generator[dict, None, None]

Raises:

RuntimeError – If the server version is below v7.5 or the API call fails.

search_index_filter_csv(query: str = '%', csv_file='search.csv', page_size: int = 50, filter_values: dict | None = None, sort_values: dict | None = None)[source]

Run a filtered search and write all results to a CSV file.

Executes the same query as search_index_filter_list() but writes every result row to a UTF-8 encoded CSV file instead of returning a generator. Column headers are derived from the keys of filter_values; xip.reference is always the first column.

Parameters:
  • query (str) – Lucene-style search expression. Use "%" (default) to match all objects.

  • csv_file (str) – Path to the output CSV file (default "search.csv").

  • page_size (int) – Number of results to fetch per API request (default 50).

  • filter_values (dict or None) – Dictionary mapping index field names to filter values. An empty string value ("") means “return this field but do not restrict by value”. A non-empty string or list of strings restricts results to objects whose field matches one of the supplied values. xip.reference is added automatically if absent.

  • sort_values (dict or None) – Optional dictionary mapping index field names to sort directions. Values starting with "d" (case-insensitive) sort descending; all other values sort ascending.

search_index_filter_hits(query: str = '%', filter_values: dict | None = None) int[source]

Run a filtered search and return only the total number of matching objects.

Performs the same field-filtered query as search_index_filter_list() but fetches only a minimal page (10 results) and returns the totalHits count reported by the API, without yielding the actual result rows. This is useful for counting matches cheaply before deciding whether to retrieve the full result set.

Parameters:
  • query (str) – Lucene-style search expression. Use "%" (default) to match all objects.

  • filter_values (dict or None) – Dictionary mapping index field names to filter values. An empty string value ("") means “do not restrict by value”. A non-empty string or list of strings restricts the count to objects whose field matches one of the supplied values. When None, defaults to {"xip.reference": "", "xip.title": ""}.

Returns:

Total number of repository objects that match the query and filters.

Return type:

int

Raises:

RuntimeError – If the API call fails.

search_index_filter_list(query: str = '%', page_size: int = 25, filter_values: dict | None = None, sort_values: dict | None = None) Generator[source]

Run a filtered search and yield all matching result rows as dictionaries.

Issues paginated requests to the Preservica search endpoint, applying per-field value filters and optional sort criteria. Pagination continues automatically until all matching objects have been yielded. Each result row is a dict whose keys come from filter_values, with xip.reference always present.

If a progress callback has been registered via search_callback(), it is called after each page with the current progress string.

Parameters:
  • query (str) – Lucene-style search expression. Use "%" (default) to match all objects.

  • page_size (int) – Number of results to fetch per API request (default 25).

  • filter_values (dict or None) – Dictionary mapping index field names to filter values. An empty string value ("") means “return this field but do not restrict by value”. A non-empty string or list of strings restricts results to objects whose field matches one of the supplied values.

  • sort_values (dict or None) – Optional dictionary mapping index field names to sort directions. Values starting with "d" (case-insensitive) sort descending; all other values sort ascending.

Returns:

Generator that yields one dict per matching object.

Return type:

Generator[dict, None, None]

Raises:

RuntimeError – If the API call fails.

simple_search_csv(query: str = '%', page_size: int = 50, csv_file='search.csv', list_indexes: list | None = None)[source]

Run a simple keyword search and write all results to a CSV file.

Executes the same query as simple_search_list() but instead of returning a generator it writes every result row to a UTF-8 encoded CSV file. The first column is always xip.reference. If list_indexes is omitted, the default set of fields (xip.reference, xip.title, xip.description, xip.document_type, xip.parent_ref, xip.security_descriptor) is used as both the column headers and the requested metadata fields.

Parameters:
  • query (str) – Lucene-style search expression. Use "%" (default) to match all objects.

  • page_size (int) – Number of results to fetch per API request (default 50).

  • csv_file (str) – Path to the output CSV file (default "search.csv").

  • list_indexes (list or None) – Optional list of index field names to include as columns. xip.reference is always prepended if not present.

simple_search_list(query: str = '%', page_size: int = 50, list_indexes: list | None = None) Generator[source]

Run a simple keyword search and yield all matching result rows as dictionaries.

Issues paginated requests to the Preservica search endpoint and lazily yields each result row as a dict whose keys are the requested index field names. xip.reference is always present as the first key. Pagination continues automatically until all matching objects have been yielded.

If a progress callback has been registered via search_callback(), it is called after each page with the current progress string.

Parameters:
  • query (str) – Lucene-style search expression. Use "%" (default) to match all objects.

  • page_size (int) – Number of results to fetch per API request (default 50).

  • list_indexes (list or None) – List of index field names to retrieve for each result. When omitted, the default set (xip.title, xip.description, xip.document_type, xip.parent_ref, xip.security_descriptor) is used. xip.reference is always included.

Returns:

Generator that yields one dict per matching object.

Return type:

Generator[dict, None, None]

Raises:

RuntimeError – If the API call fails.

thumbnail(entity_type, reference, filename, size=Thumbnail.LARGE) str[source]

Retrieve the thumbnail image for a repository entity and save it to a local file.

Downloads the PNG thumbnail generated by Preservica for the given entity and writes it to filename on the local filesystem.

Parameters:
  • entity_type (EntityType or str) – The type of entity whose thumbnail is requested. Either an EntityType enum value or the corresponding raw string used by the API (e.g. "IO", "SO").

  • reference (str) – The UUID reference of the entity.

  • filename (str) – Local filesystem path where the PNG thumbnail will be written.

  • size (Thumbnail) – The desired thumbnail size. One of SMALL, MEDIUM, or LARGE (default).

Returns:

The filename path that was written to.

Return type:

str

Raises:

RuntimeError – If the reference is not found in the repository (HTTP 404), or if the thumbnail retrieval fails for any other reason.

thumbnail_bytes(entity_type, reference: str, size: Thumbnail = Thumbnail.LARGE) BytesIO[source]

Retrieve the thumbnail image for a repository entity and return it as an in-memory byte buffer.

Downloads the PNG thumbnail generated by Preservica for the given entity. The buffer’s position is reset to zero before it is returned so callers can read or pass it directly to image-processing libraries.

Parameters:
  • entity_type (EntityType or str) – The type of entity whose thumbnail is requested. Either an EntityType enum value or the corresponding raw string used by the API (e.g. "IO", "SO").

  • reference (str) – The UUID reference of the entity.

  • size (Thumbnail) – The desired thumbnail size. One of SMALL, MEDIUM, or LARGE (default).

Returns:

An in-memory byte buffer containing the PNG thumbnail image, seeked to position 0.

Return type:

io.BytesIO

Raises:

RuntimeError – If the reference is not found in the repository (HTTP 404), or if the thumbnail retrieval fails for any other reason.

user_security_tags(with_permissions: bool = False)[source]

Return the security tags available to the currently authenticated user.

When with_permissions is False (the default) the returned dict maps each tag name to itself. When True, each tag name maps to the list of permission strings associated with that tag.

Requires Preservica v6.3.2 or higher; raises RuntimeError on older servers.

Parameters:

with_permissions (bool) – When True, include the permissions list for each tag instead of just the tag name.

Returns:

Dictionary mapping security-tag names to their display name (or to a list of permission strings when with_permissions=True).

Return type:

dict

Raises:

RuntimeError – If the server version is below v6.3.2 or the API call fails.

Upload API

This part of the documentation covers all the interfaces of pyPreservica UploadAPI object.

pyPreservica.simple_asset_package(preservation_file: str | None = None, access_file: str | None = None, export_folder: str | None = None, parent_folder=None, compress=True, **kwargs)[source]

Create a Preservica package containing a single Asset from a single preservation file and an optional access file. The Asset contains one Content Object for each representation.

If only the preservation file is provided the asset has one representation

Parameters:
  • preservation_file (str) – Path to the preservation file

  • access_file (str) – Path to the access file

  • export_folder (str) – The package location folder

  • parent_folder (Folder) – The folder to ingest the asset into

  • compress (bool) – Compress the ZIP file

  • Title (str) – Asset Title

  • Description (str) – Asset Description

  • SecurityTag (str) – Asset SecurityTag

  • CustomType (str) – Asset CustomType

  • Preservation_Content_Title (str) – Title of the Preservation Representation Content Object

  • Preservation_Content_Description (str) – Description of the Preservation Representation Content Object

  • Access_Content_Title (str) – Title of the Access Representation Content Object

  • Access_Content_Description (str) – Description of the Access Representation Content Object

  • Asset_Metadata (dict) – Dictionary of Asset metadata documents

  • Identifiers (dict) – Dictionary of Asset rd party identifiers

pyPreservica.complex_asset_package(preservation_files_list: list | None = None, access_files_list: list | None = None, export_folder=None, parent_folder=None, compress=True, **kwargs)[source]

Create a Preservica package containing a single Asset from a multiple preservation files and optional access files. The Asset contains multiple Content Objects within each representation.

If only the preservation files are provided the asset has one representation

param list preservation_files_list:

Paths to the preservation files

param list access_files_list:

Paths to the access files

param str export_folder:

The package location folder

param Folder parent_folder:

The folder to ingest the asset into

param bool compress:

Compress the ZIP file

param str Title:

Asset Title

param str Description:

Asset Description

param str SecurityTag:

Asset SecurityTag

param str CustomType:

Asset CustomType

param str Preservation_Content_Title:

Title of the Preservation Representation Content Object

param str Preservation_Content_Description:

Description of the Preservation Representation Content Object

param str Access_Content_Title:

Title of the Access Representation Content Object

param str Access_Content_Description:

Description of the Access Representation Content Object

param dict Asset_Metadata:

Dictionary of Asset metadata documents

param dict Identifiers:

Dictionary of Asset rd party identifiers

optional kwargs map ‘Title’ Asset Title ‘Description’ Asset Description ‘SecurityTag’ Asset Security Tag ‘CustomType’ Asset Type ‘Preservation_Content_Title’ Content Object Title of the Preservation Object ‘Preservation_Content_Description’ Content Object Description of the Preservation Object ‘Access_Content_Title’ Content Object Title of the Access Object ‘Access_Content_Description’ Content Object Description of the Access Object ‘Preservation_Generation_Label’ Generation Label for the Preservation Object ‘Access_Generation_Label’ Generation Label for the Access Object ‘Asset_Metadata’ Map of metadata schema/documents to add to asset ‘Identifiers’ Map of asset identifiers ‘Preservation_files_fixity_callback’ Callback to allow external generated fixity values ‘Access_files_fixity_callback’ Callback to allow external generated fixity values ‘IO_Identifier_callback’ Callback to allow external generated Asset identifier ‘Preservation_Representation_Name’ Name of the Preservation Representation ‘Access_Representation_Name’ Name of the Access Representation

pyPreservica.csv_to_xml(csv_file, xml_namespace, root_element, file_name_column='filename', export_folder=None, additional_namespaces=None)[source]

Export the rows of a CSV file as individual XML metadata documents for Preservica assets.

Each data row in csv_file is converted to an XML document whose root element is root_element and whose child elements correspond to the CSV column headers. One XML file is written per data row; the file is named after the value in the column identified by file_name_column.

Parameters:
  • csv_file (str) – Path to the CSV file to process.

  • xml_namespace (str) – The XML namespace URI applied to the generated documents.

  • root_element (str) – The root element name for each generated XML document.

  • file_name_column (str) – The CSV column header whose value is used to name each output XML file. Defaults to "filename".

  • export_folder (str or None) – Directory where the generated XML files are written. If None, files are written to the current working directory.

  • additional_namespaces (dict or None) – Mapping of namespace prefix to URI for any extra namespaces to declare on the root element.

Returns:

Generator that yields the path to each written XML file.

Return type:

Generator[str, None, None]

pyPreservica.csv_to_xsd(csv_file, xml_namespace, root_element, export_folder=None, additional_namespaces=None)[source]

Create an XSD schema definition derived from the column headers of a CSV file.

Reads the column headers from the first row of csv_file and generates an XML Schema Definition (.xsd) file that validates the XML documents produced by csv_to_xml().

Parameters:
  • csv_file (str) – Path to the CSV file whose headers define the element names.

  • xml_namespace (str) – The target namespace URI for the generated schema.

  • root_element (str) – The root element name that the schema will validate.

  • export_folder (str or None) – Directory where the generated .xsd file is written. If None, the file is written to the current working directory.

  • additional_namespaces (dict or None) – Mapping of namespace prefix to URI for any extra namespaces referenced in the CSV headers.

Returns:

Path to the generated XSD file.

Return type:

str

pyPreservica.csv_to_cmis_xslt(csv_file, xml_namespace, root_element, title='Metadata Title', export_folder=None, additional_namespaces=None)[source]

Create a custom CMIS XSLT transform to display metadata within Universal Access (UA).

Reads the column headers from the first row of csv_file and generates an XSL stylesheet that maps the XML elements produced by csv_to_xml() to the Tessella CMIS metadata display format used by Preservica Universal Access.

Parameters:
  • csv_file (str) – Path to the CSV file whose headers define the metadata fields.

  • xml_namespace (str) – The XML namespace URI used in the metadata documents.

  • root_element (str) – The root element name used in the metadata documents.

  • title (str) – Human-readable title shown in UA for this metadata group. Defaults to "Metadata Title".

  • export_folder (str or None) – Directory where the generated .xslt file is written. If None, the file is written to the current working directory.

  • additional_namespaces (dict or None) – Mapping of namespace prefix to URI for any extra namespaces referenced in the CSV headers (e.g. {"dc": "http://..."}.

Returns:

Path to the generated XSLT file.

Return type:

str

class pyPreservica.UploadAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook: Callable | None = None, credentials_path: str = 'credentials.properties')[source]
clean_upload_bucket(bucket_name: str, older_than_days: int = 90)[source]

Delete objects in an upload bucket that are older than a given number of days.

Supports both AWS S3 buckets and Azure Blob Storage containers. The appropriate cloud credentials are obtained automatically via upload_credentials().

Parameters:
  • bucket_name (str) – The name of the S3 bucket or Azure container to clean.

  • older_than_days (int) – Objects whose last-modified timestamp is more than this many days in the past are deleted. Defaults to 90.

Returns:

None

Return type:

None

ingest_web_video(url=None, parent_folder=None, **kwargs)[source]

Download a web video (e.g. YouTube) and ingest it into Preservica as an asset.

Requires the optional youtube_dl package (pip install --upgrade youtube-dl). The video is downloaded to the current working directory as <video_id>.mp4, wrapped in a simple preservation package, and then uploaded via upload_zip_package().

Parameters:
  • url (str or None) – URL of the web video to download and ingest.

  • parent_folder (Folder or str or None) – The Preservica folder into which the video asset is ingested.

  • Title (str) – Optional title for the asset. Defaults to the video title from the metadata.

  • Description (str) – Optional description for the asset. Defaults to the video description from the metadata.

  • SecurityTag (str) – Optional security tag for the asset. Defaults to "open".

  • Identifiers (dict) – Optional mapping of identifier type to value; the video id is automatically added under the key "Video-ID".

  • Asset_Metadata (dict) – Optional mapping of schema URI to metadata document for the asset.

  • callback (callable or None) – Optional upload progress callback.

Raises:

RuntimeError – If the youtube_dl package is not installed.

upload_buckets() dict[source]

Get a list of available upload buckets.

Alias for upload_locations(); returns all upload locations configured on the Preservica system (both S3 buckets and Azure containers).

Returns:

List of upload location dictionaries (see upload_locations()).

Return type:

list[dict]

Raises:

HTTPException – If the server returns a non-200 response.

upload_credentials(location_id: str) dict[source]

Retrieve temporary upload credentials for a specific upload location.

For AWS deployments, the credentials are Amazon STS temporary credentials (key, secret, sessionToken, endpoint). For Azure deployments they are Azure SAS credentials (key, sessionToken).

Parameters:

location_id (str) – The API id of the upload location (from upload_locations()).

Returns:

Dictionary of credential fields appropriate for the deployment type.

Return type:

dict

Raises:

HTTPException – If the server returns a non-200 response.

upload_locations() dict[source]

Return all configured upload locations for this Preservica system.

Upload locations are configured on the Preservica Sources page as SIP Upload entries and represent S3 buckets or Azure containers connected to ingest workflows.

Returns:

List of upload location dictionaries, each containing at least containerName, type ("AWS" or "Azure"), and apiId.

Return type:

list[dict]

Raises:

HTTPException – If the server returns a non-200 response.

upload_zip_package(path_to_zip_package, folder=None, callback=None, delete_after_upload=False, limit_per_minute=180)[source]

Upload a ZIP package directly to Preservica via the built-in S3 endpoint and start an ingest workflow.

Uses auto-refreshing Preservica token credentials so that long-running uploads do not fail due to token expiry. Multipart chunk sizes are automatically adjusted based on the package size.

This function can be rate limited to restrict the number of uploads per minute, it will default to a max of 180 / min.

Parameters:
  • path_to_zip_package (str) – Local path to the ZIP package file.

  • folder (Folder or str or None) – Optional Preservica folder (or UUID string) that the ingested package should be placed into.

  • callback (callable or None) – Optional progress callback invoked during the upload. Must be compatible with the boto3 Callback interface (i.e. a callable that accepts the number of bytes transferred).

  • delete_after_upload (bool :param limit_per_minute: Restrict the number of uploads per min, default is 180 (3 per second)) – When True, the local ZIP file is deleted after a successful upload. Defaults to False.

Returns:

The preservica-progress-token header value returned by the server, which can be used to monitor the ingest workflow progress.

Return type:

str

Raises:
  • NoCredentialsError – If AWS credentials cannot be resolved.

  • ClientError – If the S3 upload fails.

upload_zip_package_to_Azure(path_to_zip_package: str, container_name: str, folder=None, delete_after_upload=False, show_progress=False)[source]

Uploads a zip file package to an Azure container connected to a Preservica Cloud System

Parameters:
  • path_to_zip_package (str) – Path to the package

  • container_name (str) – container connected to the ingest workflow

  • folder (Folder) – The folder to ingest the package into

  • delete_after_upload (bool) – Delete the local copy of the package after the upload has completed

upload_zip_package_to_S3(path_to_zip_package: str, bucket_name: str, folder=None, callback=None, delete_after_upload=False)[source]

Uploads a zip file package to an S3 bucket connected to a Preservica Cloud System

Parameters:
  • path_to_zip_package (str) – Path to the package

  • bucket_name (str) – Bucket connected to an ingest workflow

  • folder (Folder) – The folder to ingest the package into

  • callback (Callable) – Optional callback to allow the callee to monitor the upload progress

  • delete_after_upload (bool) – Delete the local copy of the package after the upload has completed

upload_zip_to_Source(path_to_zip_package: str, container_name, folder=None, delete_after_upload=False, show_progress=False)[source]

Upload a ZIP package to an upload source (Azure container or S3 bucket).

Automatically dispatches to upload_zip_package_to_S3() or upload_zip_package_to_Azure() based on the deployment type reported by upload_locations().

Parameters:
  • path_to_zip_package (str) – Local path to the ZIP package file.

  • container_name (str) – Name of the S3 bucket or Azure container connected to an ingest workflow.

  • folder (Folder or str or None) – Optional Preservica folder (or UUID string) that the ingested package should be placed into.

  • delete_after_upload (bool) – When True, the local ZIP file is deleted after a successful upload. Defaults to False.

  • show_progress (bool) – When True, an upload progress bar is displayed on the console. Defaults to False.

Returns:

None

Return type:

None

Retention Management API

https://demo.preservica.com/api/entity/documentation.html#/%2Fretention-policies

class pyPreservica.RetentionPolicy(name: str, reference: str)[source]
class pyPreservica.RetentionAssignment(entity_reference: str, policy_reference: str, api_id: str, start_date, expired=False)[source]
class pyPreservica.RetentionAPI(username=None, password=None, tenant=None, server=None, use_shared_secret=False, two_fa_secret_key: str = None, protocol: str = 'https', request_hook: Callable = None, credentials_path: str = 'credentials.properties')[source]
add_assignments(entity: Entity, policy: RetentionPolicy) RetentionAssignment[source]

Assign a retention policy to an Asset.

Parameters:
  • entity (Entity) – The Preservica Entity to assign a policy to

  • policy (RetentionPolicy) – The RetentionAssignment

Returns:

The RetentionAssignment

Return type:

RetentionAssignment

assignable_policy(reference: str, status: bool)[source]

Make a policy assignable

Parameters:
  • reference (str) – The policy ID

  • status (bool) – The assignable status

Returns:

No return value.

Return type:

None

Raises:

RuntimeError – If the API request fails.

assignments(entity: Entity) Generator[RetentionPolicy, None, None][source]

Return a list of retention policies for an entity.

Parameters:

entity (class:Entity) – The entity to fetch assignments for

Returns:

Policy assignments

Return type:

Generator[RetentionAssignment]

create_policy(**kwargs)[source]

Create a new retention policy and return it.

All keyword arguments listed below are required.

Parameters:

kwargs

Policy field values. The following keys are all required:

  • Name (str) – Display name of the policy.

  • Description (str) – Human-readable description.

  • SecurityTag (str) – Security tag applied to the policy.

  • StartDateField (str) – Metadata field used as the retention start date.

  • Period (str) – Numeric retention period value.

  • PeriodUnit (str) – Unit of the retention period (e.g. "years").

  • ExpiryAction (str) – Action taken when the retention period expires.

  • ExpiryActionParameters (str) – Parameters for the expiry action.

  • Restriction (str) – Restriction applied during the retention period.

  • Assignable (bool) – Whether the policy may be assigned to new assets.

Returns:

The newly created retention policy fetched from the server.

Return type:

RetentionPolicy

Raises:

RuntimeError – If any required kwarg is missing or if the API request fails.

delete_policy(reference: str)[source]

Delete a retention policy

Parameters:

reference (str) – The policy reference

Returns:

No return value.

Return type:

None

Raises:

RuntimeError – If the API request fails.

find(policy: RetentionPolicy | None = None) Generator[source]

Find all entities which have a retention policy

Find entities with a specific policy

Parameters:

policy (RetentionPolicy) – Find entities with this specific policy

Returns:

entities with the policy or policies

Return type:

Generator of entities

policies() Generator[RetentionPolicy, None, None][source]

Return a list of all retention policies Returns a maximum of 100 policies for each call to the server

Returns:

Generator of retention policies

Return type:

Generator[RetentionPolicy]

policy(reference: str) RetentionPolicy[source]

Return a retention policy by reference

Parameters:

reference (str) – The policy reference

Returns:

The retention policy

Return type:

RetentionPolicy

policy_by_name(name: str) RetentionPolicy[source]

Return a retention policy by name

Parameters:

name (str) – The policy name

Returns:

The retention policy

Return type:

RetentionPolicy

remove_assignments(retention_assignment: RetentionAssignment)[source]

Delete a retention policy from an asset

Parameters:

retention_assignment (RetentionAssignment) – The Preservica Entity to assign a policy to

Returns:

The Asset Reference

Return type:

str

update_policy(reference: str, **kwargs)[source]

Update an existing retention policy and return the updated policy.

All keyword arguments listed below are required.

Parameters:
  • reference (str) – The unique reference (UUID) of the policy to update.

  • kwargs

    Policy field values. The following keys are all required:

    • Name (str) – Display name of the policy.

    • Description (str) – Human-readable description.

    • SecurityTag (str) – Security tag applied to the policy.

    • StartDateField (str) – Metadata field used as the retention start date.

    • Period (str) – Numeric retention period value.

    • PeriodUnit (str) – Unit of the retention period (e.g. "years").

    • ExpiryAction (str) – Action taken when the retention period expires.

    • ExpiryActionParameters (str) – Parameters for the expiry action.

    • Restriction (str) – Restriction applied during the retention period.

    • Assignable (bool) – Whether the policy may be assigned to new assets.

Returns:

The updated retention policy fetched from the server.

Return type:

RetentionPolicy

Raises:

RuntimeError – If any required kwarg is missing or if the API request fails.

Workflow API

Note

The Workflow API is available for Enterprise Preservica users

https://demo.preservica.com/api/admin/documentation.html

class pyPreservica.WorkflowContext(workflow_id: str, workflow_name: str)[source]

Defines a workflow context. The workflow context is the pre-defined workflow which is ready to run

class pyPreservica.WorkflowInstance(instance_id: int)[source]

Defines a workflow Instance. The workflow Instance is a context which has been executed

class pyPreservica.WorkflowAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook: Callable | None = None, credentials_path: str = 'credentials.properties')[source]

A class for calling the Preservica Workflow API

This API can be used to programmatically manage the Preservica Workflows.

https://demo.preservica.com/sdb/rest/workflow/documentation.html

get_workflow_contexts(definition: str) list[WorkflowContext][source]

Return a list of Workflow Contexts that share the same Workflow Definition.

Parameters:

definition (str) – The Workflow Definition text ID used to filter contexts.

Returns:

List of WorkflowContext objects associated with the given workflow definition.

Return type:

list[WorkflowContext]

Raises:

RuntimeError – If the API call fails.

get_workflow_contexts_by_type(workflow_type: str) list[WorkflowContext][source]

Return a list of Workflow Contexts that share the same workflow type.

Parameters:

workflow_type (str) – The workflow type to filter by. Must be one of "Ingest", "Access", "Transformation", or "DataManagement".

Returns:

List of WorkflowContext objects whose type matches workflow_type.

Return type:

list[WorkflowContext]

Raises:

RuntimeError – If the API call fails.

start_workflow_instance(workflow_context: WorkflowContext, **kwargs)[source]

Start a new workflow instance from the given workflow context.

Any extra keyword arguments are forwarded to the workflow as Key/Value parameter pairs in the XML start request (e.g. parameter_key=parameter_value).

Parameters:
  • workflow_context (WorkflowContext) – The workflow context to start.

  • kwargs – Arbitrary keyword arguments forwarded as workflow parameters.

Returns:

A UUID correlation id that can be used to monitor the workflow progress.

Return type:

str

Raises:

RuntimeError – If the server does not return HTTP 201 Created.

terminate_workflow_instance(instance_ids)[source]

Terminate one or more running workflow instances by their instance ids.

Parameters:

instance_ids (int or list[int]) – A single workflow instance id or a list of instance ids to terminate.

Returns:

None

Return type:

None

Raises:

RuntimeError – If the server does not return HTTP 202 Accepted.

workflow_instance(instance_id: int) WorkflowInstance[source]

Retrieve a single workflow instance by its numeric id.

The returned WorkflowInstance is populated with state, timing, context, and archival process information retrieved from the server.

Parameters:

instance_id (int) – The numeric id of the workflow instance to retrieve.

Returns:

A fully populated WorkflowInstance object.

Return type:

WorkflowInstance

Raises:

RuntimeError – If the server returns a non-200 response.

workflow_instances(workflow_state: str, workflow_type: str, **kwargs) Generator[WorkflowInstance, None, None][source]

Return a generator of workflow instances filtered by state and type.

Results are fetched from the server in pages of 100 and yielded lazily. Optional keyword arguments allow further filtering by context, creator, or date range.

Parameters:
  • workflow_state (str) – The workflow state to filter by. Must be one of "Aborted", "Active", "Completed", "Finished_Mixed_Outcome", "Pending", "Suspended", "Unknown", or "Failed".

  • workflow_type (str) – The workflow type to filter by. Must be one of "Ingest", "Access", "Transformation", or "DataManagement".

  • contextId (str) – Optional workflow context id to filter results.

  • creator (str) – Optional username of the workflow creator to filter results.

  • from_date (datetime.date or datetime.datetime or str) – Optional start date for filtering by workflow start time.

  • to_date (datetime.date or datetime.datetime or str) – Optional end date for filtering by workflow start time.

Returns:

Generator that lazily yields WorkflowInstance objects.

Return type:

Generator[WorkflowInstance, None, None]

Raises:

RuntimeError – If an invalid state or type is supplied, or if the API call fails.

Administration and Management API

Note

The Administration and Management API needs to be enabled by the help desk.

https://demo.preservica.com/api/admin/documentation.html

class pyPreservica.AdminAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook=None, credentials_path: str = 'credentials.properties')[source]
add_security_tag(tag_name) str[source]

Create a new security tag in the Preservica tenancy.

Security tags are used to control access to repository content.

Parameters:

tag_name (str) – The name of the new security tag to create.

Returns:

The name of the newly created security tag as confirmed by the server.

Return type:

str

Raises:

RuntimeError – If tag_name is empty, if the Preservica server is below v6.4.0, or if the creation request fails.

add_system_role(role_name) str[source]

Create a new user access role in the Preservica tenancy.

Parameters:

role_name (str) – The name of the new role to create.

Returns:

The name of the newly created role as confirmed by the server.

Return type:

str

Raises:

RuntimeError – If role_name is empty, if the Preservica server is below v6.5.0, or if the creation request fails.

add_user(username: str, full_name: str, roles: list[str], externally_authenticated: bool = False) dict[source]

Create a new user account to the Preservica tenancy.

Parameters:
  • username (str) – The email address of the new user (used as the login username).

  • full_name (str) – The full display name of the new user.

  • roles (list[str]) – A list of role names to assign to the new user.

  • externally_authenticated (bool) – If True, the user is authenticated via an external identity provider (e.g. LDAP/SSO) rather than Preservica’s internal authentication. Defaults to False.

Returns:

A dictionary of the newly created user’s attributes with keys: UserName, FullName, Email, Tenant, Enabled, Roles.

Return type:

dict

Raises:

RuntimeError – If the creation request fails.

add_xml_document(name: str, xml_data: Any, document_type: str = 'MetadataTemplate')[source]

Upload a new XML document to the Preservica XML document store.

The default document type is a descriptive metadata template. Supported document_type values are:

  • "MetadataDropdownLists" — Authority Lists

  • "CustomIndexDefinition" — Custom Search Indexes

  • "MetadataTemplate" — Descriptive Metadata Template (default)

  • "UploadWizardConfigurationFile" — Upload Wizard Configuration

  • "ConfigurationFile" — Heritrix Crawler Configuration File

Parameters:
  • name (str) – The display name for the XML document within Preservica.

  • xml_data (str or file-like object) – The XML document content, either as a UTF-8 encoded string or as a file-like object opened in binary mode.

  • document_type (str) – The document type identifier. Defaults to "MetadataTemplate".

Returns:

None

Return type:

None

Raises:

RuntimeError – If the upload request fails.

add_xml_schema(name: str, description: str, originalName: str, xml_data: Any)[source]

Upload a new XSD schema document to the Preservica schema store.

Parameters:
  • name (str) – The display name for the XSD schema within Preservica.

  • description (str) – A human-readable description of the XSD schema.

  • originalName (str) – The original filename of the schema file on disk (e.g. "my-schema.xsd").

  • xml_data (str or file-like object) – The XSD schema content, either as a UTF-8 encoded string or as a file-like object opened in binary mode.

Returns:

None

Return type:

None

Raises:

RuntimeError – If the upload request fails.

add_xml_transform(name: str, input_uri: str, output_uri: str, purpose: str, originalName: str, xml_data: Any)[source]

Upload a new XSLT transform document to the Preservica transform store.

Parameters:
  • name (str) – The display name for the XSLT transform within Preservica.

  • input_uri (str) – The schema URI of the input (source) XML format that the transform accepts.

  • output_uri (str) – The schema URI of the output (target) XML format that the transform produces.

  • purpose (str) – The intended use of the transform. Accepted values are "transform" (format conversion), "edit" (in-place editing), or "view" (rendering/display). The value is lowercased before submission.

  • originalName (str) – The original filename of the XSLT file on disk (e.g. "my-transform.xslt").

  • xml_data (str or file-like object) – The XSLT transform content, either as a UTF-8 encoded string or as a file-like object opened in binary mode.

Returns:

None

Return type:

None

Raises:

RuntimeError – If the upload request fails.

all_users() list[str][source]

Return a list of all user email addresses registered in the Preservica tenancy.

Returns:

A list of username strings, each being the email address of a registered user.

Return type:

list[str]

Raises:

RuntimeError – If the request fails.

change_user_display_name(username: str, new_display_name: str) dict[source]

Change the full display name of an existing Preservica user.

Parameters:
  • username (str) – The email address of the user whose display name should be changed.

  • new_display_name (str) – The new full display name to assign to the user.

Returns:

A dictionary of the updated user’s attributes with keys: UserName, FullName, Email, Tenant, Enabled, Roles.

Return type:

dict

Raises:

RuntimeError – If fetching or updating the user record fails.

current_user()[source]

Return details about the currently authenticated user.

Returns:

A dictionary of the current user’s attributes

Return type:

dict

Raises:

RuntimeError – If the request fails.

delete_security_tag(tag_name)[source]

Delete an existing security tag from the Preservica tenancy.

Parameters:

tag_name (str) – The name of the security tag to delete.

Returns:

None

Return type:

None

Raises:

RuntimeError – If the Preservica server is below v6.4.0, or if the delete request fails.

delete_system_role(role_name)[source]

Delete an existing system role from the Preservica tenancy.

Parameters:

role_name (str) – The name of the role to delete.

Returns:

None

Return type:

None

Raises:

RuntimeError – If the Preservica server is below v6.5.0, or if the delete request fails.

delete_user(username: str)[source]

Permanently delete a user from the Preservica tenancy.

The user account is disabled before deletion. This operation cannot be undone.

Parameters:

username (str) – The email address of the user to delete.

Returns:

None

Return type:

None

Raises:

RuntimeError – If the delete request fails.

delete_xml_document(uri: str)[source]

Delete an XML document from Preservica’s XML document store by its schema URI.

If no document with the given URI is found, the method returns without error.

Parameters:

uri (str) – The schema URI of the XML document to delete (as returned in the SchemaUri key from xml_documents()).

Returns:

None

Return type:

None

Raises:

RuntimeError – If a matching document is found but the delete request fails.

delete_xml_schema(uri: str)[source]

Delete an XSD schema document from Preservica by its schema URI.

If no schema with the given URI is found, the method returns without error.

Parameters:

uri (str) – The schema URI of the XSD document to delete (as returned in the SchemaUri key from xml_schemas()).

Returns:

None

Return type:

None

Raises:

RuntimeError – If a matching schema is found but the delete request fails.

delete_xml_transform(input_uri: str, output_uri: str)[source]

Delete an XSLT transform from Preservica by its input and output schema URIs.

If no transform matching both URIs is found, the method returns without error.

Parameters:
  • input_uri (str) – The FromSchemaUri of the transform to delete — the URI of the input XML schema that the transform accepts.

  • output_uri (str) – The ToSchemaUri of the transform to delete — the URI of the output XML schema that the transform produces.

Returns:

None

Return type:

None

Raises:

RuntimeError – If a matching transform is found but the delete request fails.

disable_user(username)[source]

Disable a Preservica user account to prevent the user from logging in.

Parameters:

username (str) – The email address of the user to disable.

Returns:

The server response body as a string.

Return type:

str

Raises:

RuntimeError – If the request fails.

enable_user(username)[source]

Enable a previously disabled Preservica user account.

Parameters:

username (str) – The email address of the user to enable.

Returns:

The server response body as a string.

Return type:

str

Raises:

RuntimeError – If the request fails.

security_tags() list[str][source]

Return a list of all security tag names defined in the Preservica tenancy.

Returns:

A list of security tag name strings.

Return type:

list[str]

Raises:

RuntimeError – If the request fails.

system_roles() list[str][source]

Return a list of all role names defined in the Preservica tenancy.

Returns:

A list of role name strings.

Return type:

list[str]

Raises:

RuntimeError – If the Preservica server is below v6.5.0, or if the request fails.

user_details(username: str) dict[source]

Retrieve the full details of a Preservica user by their email address.

Parameters:

username (str) – The email address of the user to look up.

Returns:

A dictionary of the user’s attributes with keys: UserName (str), FullName (str), Email (str), Tenant (str), Enabled (bool), Roles (list[str]).

Return type:

dict

Raises:

RuntimeError – If the request fails.

user_report(report_name='users.csv')[source]

Write a CSV report of all users in the Preservica tenancy to a file.

The report contains one row per user with the following columns: UserName, FullName, Email, Tenant, Enabled, Roles.

Parameters:

report_name (str) – The file path to write the CSV report to. Defaults to "users.csv" in the current working directory.

Returns:

None

Return type:

None

Raises:

RuntimeError – If any underlying user detail request fails.

xml_document(uri: str) str | None[source]

Fetch the content of an XML document stored in Preservica by its URI.

Parameters:

uri (str) – The schema URI of the XML document to fetch (as returned in the SchemaUri key from xml_documents()).

Returns:

The XML document content as a UTF-8 string, or None if no document with the given URI exists.

Return type:

str or None

Raises:

RuntimeError – If a matching document is found but the content fetch fails.

xml_documents() List[source]

Return a list of all XML documents stored in the Preservica XML document store.

Returns:

A list of dictionaries, one per document. Each dictionary contains: SchemaUri (str), Name (str), DocumentType (str), ApiId (str).

Return type:

list[dict]

Raises:

RuntimeError – If the request fails.

xml_schema(uri: str) str | None[source]

Fetch the content of an XSD schema document stored in Preservica by its URI.

Parameters:

uri (str) – The schema URI of the XSD document to fetch (as returned in the SchemaUri key from xml_schemas()).

Returns:

The XSD schema content as a UTF-8 string, or None if no schema with the given URI exists.

Return type:

str or None

Raises:

RuntimeError – If a matching schema is found but the content fetch fails.

xml_schemas() List[source]

Return a list of all XSD schema documents stored in the Preservica schema store.

Returns:

A list of dictionaries, one per schema. Each dictionary contains: SchemaUri (str), Name (str), Description (str), ApiId (str).

Return type:

list[dict]

Raises:

RuntimeError – If the request fails.

xml_transform(input_uri: str, output_uri: str) str | None[source]

Fetch the content of an XSLT transform stored in Preservica by its input and output URIs.

Parameters:
  • input_uri (str) – The FromSchemaUri of the transform to fetch — the URI of the input XML schema that the transform accepts.

  • output_uri (str) – The ToSchemaUri of the transform to fetch — the URI of the output XML schema that the transform produces.

Returns:

The XSLT transform content as a UTF-8 string, or None if no transform matching both URIs exists.

Return type:

str or None

Raises:

RuntimeError – If a matching transform is found but the content fetch fails.

xml_transforms() List[source]

Return a list of all XSLT transforms stored in the Preservica transform store.

Returns:

A list of dictionaries, one per transform. Each dictionary contains: FromSchemaUri (str), ToSchemaUri (str), Name (str), Purpose (str), ApiId (str).

Return type:

list[dict]

Raises:

RuntimeError – If the request fails.

Process Monitor API

https://demo.preservica.com/api/processmonitor/documentation.html

class pyPreservica.MonitorStatus(*values)[source]
FAILED = 'Failed'
PENDING = 'Pending'
RECOVERABLE = 'Recoverable'
RUNNING = 'Running'
SUCCEEDED = 'Succeeded'
SUSPENDED = 'Suspended'
class pyPreservica.MonitorCategory(*values)[source]
AUTOMATED = 'Automated'
DATA_MANAGEMENT = 'DataManagement'
EXPORT = 'Export'
INGEST = 'Ingest'
class pyPreservica.MonitorAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook=None, credentials_path: str = 'credentials.properties')[source]

A class for the Preservica Repository Process Monitor API

https://us.preservica.com/api/processmonitor/documentation.html

API for retrieving and updating monitoring information about processes.

messages(monitor_id, status: MessageStatus = None) Generator[source]

List of messages for a process

Parameters:
  • monitor_id (str) – The Process ID

  • status (MessageStatus) – The message status, info, warning, error etc.

Returns:

Generator for each message, each message is a dict object.

Return type:

Generator[dict, None, None]

Raises:

RuntimeError – If the API request fails.

monitors(status: MonitorStatus = None, category: MonitorCategory = None) Generator[source]

Get a filtered list of non-abandoned process monitors

Parameters:
  • status (MonitorStatus) – process status values (Pending, Running, Succeeded, Failed, Suspended, Recoverable)

  • category (MonitorCategory) – process categories (Ingest, Export, DataManagement, Automated)

Returns:

Generator for each monitor, each monitor is a dict object.

Return type:

Generator[dict, None, None]

Raises:

RuntimeError – If the API request fails.

timeseries(monitor_id)[source]

Get the historical record of progress for a single monitor

Parameters:

monitor_id (str) – The Process ID

Returns:

List of timeseries snapshot dicts, each containing progress information recorded at a point in time.

Return type:

list

Raises:

RuntimeError – If the API request fails.

WebHook API

https://demo.preservica.com/api/webhook/documentation.html

class pyPreservica.TriggerType(*values)[source]

Enumeration of the Web hooks Trigger Types

CHANGE_ASSET_VISIBILITY = 'CHANGE_ASSET_VISIBILITY'
INDEXED = 'FULL_TEXT_INDEXED'
INGEST_FAILED = 'INGEST_FAILED'
MOVED = 'MOVED'
SECURITY_CHANGED = 'CHANGED_SECURITY_DESCRIPTOR'
class pyPreservica.WebHooksAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook=None, credentials_path: str = 'credentials.properties')[source]

Class to register new webhook endpoints

subscribe(url: str, triggerType: TriggerType, secret: str)[source]

Create a new webhook subscription.

Registers the given URL to receive event notifications for the specified trigger type. The subscription is created with includeIdentifiers set to true so that entity references are included in each notification payload. Requires the calling user to hold the CONFIG_MANAGER role.

Parameters:
  • url (str) – The publicly reachable HTTPS endpoint that Preservica will POST events to.

  • triggerType (TriggerType) – The type of repository event that should trigger the webhook.

  • secret (str) – The shared HMAC secret used to sign outbound payloads; must also be configured in the receiving handler (e.g. LambdaURLHandler or FlaskWebhookHandler).

Returns:

The raw JSON response body from the server describing the new subscription.

Return type:

str

Raises:

HTTPException – If the server returns a non-200 response.

subscriptions()[source]

Return all current active webhook subscriptions.

Requires the calling user to hold the CONFIG_MANAGER role.

Returns:

A list of subscription dicts, each describing an active webhook registration.

Return type:

list

Raises:

HTTPException – If the server returns a non-200 response.

unsubscribe(subscription_id: str)[source]

Unsubscribe from a specific webhook subscription by its identifier.

Requires the calling user to hold the CONFIG_MANAGER role.

Parameters:

subscription_id (str) – The unique identifier of the webhook subscription to remove.

Returns:

The raw response body returned by the server (typically empty for a 204 No Content).

Return type:

str

Raises:

HTTPException – If the server returns a non-204 response.

unsubscribe_all()[source]

Unsubscribe from all active webhook subscriptions.

Retrieves the current subscriptions via subscriptions() and calls unsubscribe() for each one. Requires the calling user to hold the CONFIG_MANAGER role.

Raises:

HTTPException – If any individual unsubscribe request fails.

Authority Records API

https://demo.preservica.com/api/reference-metadata/documentation.html

This API is used for managing the Authority records within Preservica.

class pyPreservica.Table(name: str, security_tag: str, displayField: str = None, metadataConnections: list = [])[source]
class pyPreservica.AuthorityAPI(username: str | None = None, password: str | None = None, tenant: str | None = None, server: str | None = None, use_shared_secret: bool = False, two_fa_secret_key: str | None = None, protocol: str = 'https', request_hook=None, credentials_path: str = 'credentials.properties')[source]
add_record(table: Table, record: dict)[source]

Add a single new record to an existing authority table.

Dictionary keys become field names (lowercased) and dictionary values become the corresponding field values in the new record.

Parameters:
  • table (Table) – The authority table to which the record will be added.

  • record (dict) – A mapping of field name to field value for the new record.

Returns:

The raw JSON response body for the created record.

Return type:

str

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

add_records(table: Table, csv_file, encoding=None)[source]

Add new records to an existing authority table from a CSV document.

Each row in the CSV becomes one record. If the CSV does not already contain an id or ID column, the reader’s line number is used as the record ID.

Parameters:
  • table (Table) – The authority table to which records will be added.

  • csv_file (str) – Path to the CSV file whose rows will be imported as records.

  • encoding (str or None) – Character encoding used to open the CSV file (e.g. "utf-8"). Defaults to the platform default when None.

Returns:

None

Return type:

None

Raises:

HTTPException – If any individual add_record call returns an unexpected HTTP error status.

add_table(new_table: Table)[source]

Create a new authority (reference metadata) table in Preservica.

Parameters:

new_table (Table) – The Table object describing the table to create. Set new_table.description, new_table.displayField, new_table.metadataConnections, and new_table.fields before calling this method if those optional attributes are required.

Returns:

The newly created authority table, fetched fresh from the API so that the reference attribute is populated.

Return type:

Table

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

delete_record(reference: str)[source]

Delete a record from a table by its reference.

Parameters:

reference (str) – The unique reference of the record to delete.

Returns:

None

Return type:

None

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

record(reference: str) dict[source]

Return a single record by its unique reference.

Parameters:

reference (str) – The unique reference of the record to retrieve.

Returns:

The record as a JSON dictionary.

Return type:

dict

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

records(table: Table) List[dict][source]

Return all records from an authority table.

Parameters:

table (Table) – The authority table whose records should be retrieved.

Returns:

A list of records, each represented as a JSON dictionary with field values expanded.

Return type:

list[dict]

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

table(reference: str) Table[source]

Fetch an authority table by its unique reference.

Parameters:

reference (str) – The unique reference identifier for the authority table.

Returns:

The authority table with all available attributes populated.

Return type:

Table

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

tables() Set[Table][source]

Return all reference metadata (authority) tables in the tenancy.

Returns:

A set of all authority tables.

Return type:

set[Table]

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

Metadata Groups API

https://demo.preservica.com/api/metadata/documentation.html#/%2Fgroups

The Metadata Groups API is designed allows the creation of custom metadata within NGI (New Generation Interface).

class pyPreservica.Group(name: str, description: str)[source]
description: str
fields: List[GroupField]
group_id: str
name: str
schemaUri: str
class pyPreservica.GroupField(field_id: str, name: str, field_type: GroupFieldType = GroupFieldType.STRING, maxLength: int = -1, default: str = '', visible: bool = True, editable: bool = True, minOccurs: int = 0, maxOccurs: int = 1, indexed: bool = True, values: List = None)[source]
default: str
editable: bool
field_id: str
field_type: GroupFieldType
indexed: bool
maxLength: int
maxOccurs: int
minOccurs: int
name: str
values: List[str]
visible: bool
class pyPreservica.GroupFieldType(*values)[source]
DATE = 'DATE'
LONG_STRING = 'LONGSTRING'
NUMBER = 'NUMBER'
STRING = 'STRING'
class pyPreservica.MetadataGroupsAPI(username: str = None, password: str = None, tenant: str = None, server: str = None, use_shared_secret: bool = False, two_fa_secret_key: str = None, protocol: str = 'https', request_hook: Callable = None, credentials_path: str = 'credentials.properties')[source]
add_fields(group_id: str, new_fields: List[GroupField]) dict[source]

Append new metadata fields to an existing metadata group.

The new fields are appended after any fields already present in the group.

Parameters:
  • group_id (str) – The unique identifier of the group to update.

  • new_fields (List[GroupField]) – The list of new fields to append to the group.

Returns:

The updated metadata group as a JSON dictionary.

Return type:

dict

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

add_form(json_form: dict | str)[source]

Create a new metadata form using a JSON dictionary or JSON-encoded string.

Parameters:

json_form (dict or str) – The form definition as a JSON-serialisable dict or a JSON-encoded string.

Returns:

The newly created form as a JSON dictionary.

Return type:

dict

Raises:
  • RuntimeError – If json_form is neither a dict nor a str.

  • HTTPException – If the Preservica API returns an unexpected HTTP error status.

add_group(group_name: str, group_description: str, fields: List[GroupField]) dict[source]

Create a new metadata group with the supplied name, description, and fields.

Parameters:
  • group_name (str) – The name of the new group.

  • group_description (str) – A human-readable description of the new group.

  • fields (List[GroupField]) – The list of GroupField objects that define the group’s schema.

Returns:

The newly created metadata group as a JSON dictionary.

Return type:

dict

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

add_group_json(json_object: dict | str) dict[source]

Create a new metadata group using a JSON dictionary or JSON-encoded string.

Parameters:

json_object (dict or str) – The group definition as a JSON-serialisable dict or a JSON-encoded string.

Returns:

The newly created metadata group as a JSON dictionary.

Return type:

dict

Raises:
  • RuntimeError – If json_object is neither a dict nor a str.

  • HTTPException – If the Preservica API returns an unexpected HTTP error status.

delete_form(form_id: str)[source]

Delete a metadata form by its unique ID.

Parameters:

form_id (str) – The unique identifier of the form to delete.

Returns:

None

Return type:

None

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

delete_group(group_id: str)[source]

Delete a Metadata Group by its unique ID.

Parameters:

group_id (str) – The unique identifier of the group to delete.

Returns:

None

Return type:

None

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

delete_group_namespace(schema: str)[source]

Delete a Metadata Group identified by its schema URI.

Iterates over all groups in the tenancy and deletes the first one whose schemaUri matches the supplied schema string. If no group matches, the method returns without raising an exception.

Parameters:

schema (str) – The XML namespace / schema URI that uniquely identifies the group.

Returns:

None

Return type:

None

Raises:

HTTPException – If the underlying delete API call returns an unexpected HTTP error.

download_template(form_name: str)[source]

Download a CSV template for the named metadata form to allow bulk data input.

The template is written to a file named <form_name>.csv in the current working directory. The method searches all forms in the tenancy for one whose title matches form_name; if no match is found None is returned without raising an exception.

Parameters:

form_name (str) – The title of the metadata form for which to download a template.

Returns:

The path to the downloaded CSV file, or None if no matching form was found.

Return type:

str or None

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

form(form_id: str) dict[source]

Return a metadata form as a JSON dictionary by its unique ID.

Parameters:

form_id (str) – The unique identifier of the form to retrieve.

Returns:

The metadata form as a JSON dictionary.

Return type:

dict

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

forms(schema_uri: str | None = None) dict[source]

Return all metadata forms in the tenancy as a list of JSON dictionaries.

An optional schema_uri filter limits results to forms associated with a specific XML namespace URI.

Parameters:

schema_uri (str or None) – If provided, only forms whose schema URI matches this value are returned. When None (the default) all forms are returned.

Returns:

A list where each element is a JSON dictionary representing one metadata form.

Return type:

list[dict]

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

group(group_id: str) Group[source]

Return a metadata group as a Group object by its unique ID.

Parameters:

group_id (str) – The unique identifier of the group to retrieve.

Returns:

The metadata group as a Group object with all fields populated.

Return type:

Group

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

group_json(group_id: str) dict[source]

Return a metadata group as a raw JSON dictionary.

Parameters:

group_id (str) – The unique identifier of the group to retrieve.

Returns:

The metadata group as a JSON dictionary.

Return type:

dict

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

groups() Generator[Group, None, None][source]

Yield all metadata groups in the tenancy as Group objects.

Returns:

A generator that yields one Group object per metadata group in the tenancy.

Return type:

Generator[Group, None, None]

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

groups_json() List[dict][source]

Return all metadata groups in the tenancy as a list of raw JSON dictionaries.

Returns:

A list where each element is a JSON dictionary representing one metadata group.

Return type:

List[dict]

Raises:

HTTPException – If the Preservica API returns an unexpected HTTP error status.

update_form(form_id: str, json_form: dict | str)[source]

Update an existing metadata form using a JSON dictionary or JSON string.

Parameters:
  • form_id (str) – The unique identifier of the form to update.

  • json_form (dict or str) – The updated form definition as a JSON-serialisable dict or a JSON-encoded string.

Returns:

The updated form as a JSON dictionary.

Return type:

dict

Raises:
  • RuntimeError – If json_form is neither a dict nor a str.

  • HTTPException – If the Preservica API returns an unexpected HTTP error status.

Settings API

https://demo.preservica.com/api/settings/documentation.html

API for retrieving information about configuration settings.

class pyPreservica.SettingsAPI(username=None, password=None, tenant=None, server=None, use_shared_secret=False, two_fa_secret_key: str = None, protocol: str = 'https', request_hook: Callable = None, credentials_path: str = 'credentials.properties')[source]

API for retrieving information about configuration settings.

Includes methods for:

  • metadata-enrichment

metadata_enrichment_add_profile(name: str, active: bool = True)[source]

Create a metadata enrichment profile to control automatic metadata enrichment of content and return it. Profiles define a set of behaviours that will be applied when the profile is selected by a rule. A profile has no effect if it is not used by a rule. Includes settings for PII identification. PII detection tools may be run against the full text extracted from content.

Parameters:
  • name (str) – The profile name

  • active (bool) – The profile active status

Returns:

The metadata enrichment profile

Return type:

dict

metadata_enrichment_add_rule(profile_id: str, priority: int = 1)[source]

Create a metadata enrichment rule to control when metadata enrichment profiles are applied and return it. Rules define where particular behaviours, defined by profiles, will be applied. Rules are evaluated in order, with the first matching rule being applied. Note that not specifying, or specifying an empty selection implies that the rule will be applied to all content. Currently only securityDescriptorSelector, representationSelector and hierarchySelector are supported selectors. If a rule already exists for the requested priority, existing rules will be shifted down priority to accommodate the new entry.

Parameters:
  • profile_id (str) – The profile id

  • priority (int) – The rule priority

Returns:

The metadata enrichment rule

Return type:

dict

metadata_enrichment_delete_profile(profile_id: str) None[source]

Deletes a metadata enrichment profile

Parameters:

profile_id (str) – The profile name

Returns:

No return value

Return type:

None

metadata_enrichment_delete_rule(rule_id: str)[source]

Deletes a metadata enrichment rule.

Parameters:

rule_id (str) – The rule id

Returns:

No return value

Return type:

None

metadata_enrichment_profile(profile_id: str) dict[source]

Returns a single profile by its ID Profiles define a set of behaviours that will be applied when the profile is selected by a rule. A profile has no effect if it is not used by a rule. Includes settings for PII identification. PII detection tools may be run against the full text extracted from content.

Parameters:

profile_id (str) – The profile name

Returns:

The metadata enrichment profile

Return type:

dict

metadata_enrichment_profiles() dict[source]

Returns the list of all metadata enrichment profiles. Profiles define a set of behaviours that will be applied when the profile is selected by a rule. A profile has no effect if it is not used by a rule. Includes settings for PII identification. PII detection tools may be run against the full text extracted from content.

Returns:

A dict containing a "profiles" key whose value is a list of profile dicts.

Return type:

dict

Raises:

RuntimeError – If the API request fails.

metadata_enrichment_rules(profile_id: str = None) dict[source]

Returns a list of metadata enrichment rules. An empty selection implies that the rule is applied to all content. Rules define where particular behaviours, defined by profiles, will be applied. Rules are evaluated in order, with the first matching rule being applied.

Parameters:

profile_id (str) – The rules for a specific profile id, Set to None for all rules

Returns:

A dict containing a "rules" key whose value is a list of rule dicts. Each rule dict includes profileId, priority, and selectorSettings.

Return type:

dict

Raises:

RuntimeError – If the API request fails.