Python Client

v11.1.0

The official TerminusDB Python client library for data science and backend applications. Integrate graph database capabilities into your Python workflows.

$pip install terminusdb-client

Quick Navigation

Client

Client for TerminusDB server.

__init__(server_url, user_agent, **kwargs)

The Client constructor.

Parameters
server_urlstrURL of the server that this client will connect to.
user_agentoptional, strUser agent header when making requests. Defaults to terminusdb-client-python with the version appended.
**kwargsExtra configuration options

_check_connection()

Raise connection InterfaceError if not connected Defaults to check if a db is connected

_generate_commit(msg, author)

Pack the specified commit info into a dict format expected by the server.

Parameters
msgstrCommit message.
authorstrCommit author.
Returns
dictFormatted commit info.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client._generate_commit("<message>", "<author>")
{'author': '<author>', 'message': '<message>'}

_get_prefixes()

Get the prefixes for a given database

add_role(role)

Add a new role

Parameters
roledictThe role dict
Returns
dict or None if failed
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")
>>> role = {
    "name": "Grand Pubah",
    "action": [
        "branch",
        "class_frame",
        "clone",
        "commit_read_access",
        "commit_write_access",
        "create_database",
        "delete_database",
        "fetch",
        "instance_read_access",
        "instance_write_access",
        "manage_capabilities",
        "meta_read_access",
        "meta_write_access",
        "push",
        "rebase",
        "schema_read_access",
        "schema_write_access"
      ]
  }
>>> client.add_role(role)

add_user(username, password)

Add a new user

Parameters
usernamestrThe username of the user
passwordstrThe user's password
Returns
dict or None if failed

apply(before_version, after_object, branch)

Diff two different commits and apply changes on branch

Parameters
before_versionstringBefore branch/commit to compare
after_objectstringAfter branch/commit to compare
branchstringBranch to apply to. Optional.

change_capabilities(capability_change)

Change the capabilities of a certain user

Parameters
capability_changedictDict for the capability change request. Example: { "operation": "revoke", "scope": "UserDatabase/f5a0ef94469b32e1aee321678436c7dfd5a96d9c476672b3282ae89a45b5200e", "user": "User/admin", "roles": [ "Role/consumer", "Role/admin" ] }
Returns
dict or None if request failed

change_role(role)

Change role actions for a particular role

Parameters
roledictRole dict
Returns
dict or None if failed
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")
>>> role = {
    "name": "Grand Pubah",
    "action": [
        "branch",
        "class_frame",
        "clone",
        "commit_read_access",
        "commit_write_access",
        "create_database",
        "delete_database",
        "fetch",
        "instance_read_access",
        "instance_write_access",
        "manage_capabilities",
        "meta_read_access",
        "meta_write_access",
        "push",
        "rebase",
        "schema_read_access",
        "schema_write_access"
      ]
  }
>>> client.change_role(role)

change_user_password(username, password)

Change user's password

Parameters
usernamestrThe username of the user
passwordstrThe new password
Returns
dict or None if failed

clonedb(clone_source, newid, Description, remote_auth)

Clone a remote repository and create a local copy.

Parameters
clone_sourcestrThe source url of the repo to be cloned.
newidstrIdentifier of the new repository to create.
Descriptionstr, optionalOptional description about the cloned database.
remote_authstr, optionalOptional remote authorization (uses client remote auth otherwise)
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.clonedb("http://terminusdb.com/some_user/test_db", "my_test_db")

close()

Undo connect and close the connection.

commit()

Not implementated: open transactions currently not suportted. Please check back later.

connect(team, db, remote_auth, key, user, use_token, jwt_token, api_token, branch, ref, repo, **kwargs)

Connect to a Terminus server at the given URI with an API key.

Parameters
teamstrName of the team, default to be "admin"
dboptional, strName of the database connected
remote_authoptional, dictRemote Auth setting
keyoptional, strAPI key for connecting, default to be "root"
useroptional, strName of the user, default to be "admin"
use_tokenboolUse token to connect. If both `jwt_token` and `api_token` is not provided (None), then it will use the ENV variable TERMINUSDB_ACCESS_TOKEN to connect as the API token
jwt_tokenoptional, strThe Bearer JWT token to connect. Default to be None.
api_tokenoptional, strsThe API token to connect. Default to be None.
branchoptional, strBranch to be connected, default to be "main"
refoptional, strRef setting
repooptional, strLocal or remote repo, default to be "local"
**kwargsExtra configuration options.
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.connect(key="root", team="admin", user="admin", db="example_db")

copy()

Create a deep copy of this client.

Returns
ClientThe copied client instance.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> clone = client.copy()
>>> assert client is not clone

create_branch(new_branch_id, empty)

Create a branch starting from the current branch.

Parameters
new_branch_idstrNew branch identifier.
emptyboolCreate an empty branch if true (no starting commit)

create_database(dbid, team, label, description, prefixes, include_schema)

Create a TerminusDB database by posting a terminus:Database document to the Terminus Server.

Parameters
dbidstrUnique identifier of the database.
teamstr, optionalID of the Team in which to create the DB (defaults to 'admin')
labelstr, optionalDatabase name.
descriptionstr, optionalDatabase description.
prefixesdict, optionalOptional dict containing ``"@base"`` and ``"@schema"`` keys. @base (str) IRI to use when ``doc:`` prefixes are expanded. Defaults to ``terminusdb:///data``. @schema (str) IRI to use when ``scm:`` prefixes are expanded. Defaults to ``terminusdb:///schema``.
include_schemaboolIf ``True``, a main schema graph will be created, otherwise only a main instance graph will be created.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.create_database("someDB", "admin", "Database Label", "My Description")

create_organization(org)

Add a new organization

Parameters
orgstrThe id of the organization
Returns
dict or None if failed

delete_branch(branch_id)

Delete a branch

Parameters
branch_idstrBranch to delete

delete_database(dbid, team, force)

Delete a TerminusDB database.

Parameters
dbidstrID of the database to delete
teamstr, optionalthe team in which the database resides (defaults to "admin")
forcebool
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.delete_database("<database>", "<team>")

delete_document(document, graph_type, commit_msg, last_data_version)

Delete the specified document(s)

Parameters
documentstr or list of strDocument(s) (as dictionary or DocumentTemplate objects) or id(s) of document(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly

delete_organization(org)

Deletes a specific organization

Parameters
orgstrThe id of the organization
Returns
dict or None if request failed

delete_user(username)

Delete a user

Parameters
usernamestrThe username of the user
Returns
dict or None if failed

diff()

DEPRECATED

Returns
objPatch object
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> result = client.diff({ "@id" : "Person/Jane", "@type" : "Person", "name" : "Jane"}, { "@id" : "Person/Jane", "@type" : "Person", "name" : "Janine"})
>>> result.to_json = '{ "name" : { "@op" : "SwapValue", "@before" : "Jane", "@after": "Janine" }}'

diff_object(before_object, after_object)

Diff two different objects.

Parameters
before_objectstringBefore object to compare
after_objectstringAfter object to compare

diff_version(before_version, after_version)

Diff two different versions. Can either be a branch or a commit

Parameters
before_versionstringCommit or branch of the before version to compare
after_versionstringCommit or branch of the after version to compare

fetch(remote_id)

Fetch the branch from a remote repo

Parameters
remote_idstrid of the remote

get_all_branches()

Get all the branches available in the database.

get_all_documents(graph_type, skip, count, as_list, get_data_version, kwargs)

Retrieves all avalibale the documents

Parameters
graph_typeGraphType, optionalGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
skipintThe starting posiion of the returning results, default to be 0
countint or NoneThe maximum number of returned result, if None (default) it will return all of the avalible result.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "unfold"
Returns
iterableStream of dictionaries

get_available_roles()

Get the available roles for the current authenticated user

Returns
dict or None if failed

get_class_frame(class_name)

Get the frame of the class of class_name. Provide information about all the avaliable properties of that class.

Parameters
class_namestrName of the class
Returns
dictDictionary containing information

get_commit_history(max_history)

Get the whole commit history. Commit history - Commit id, author of the commit, commit message and the commit time, in the current branch from the current commit, ordered backwards in time, will be returned in a dictionary in the follow format: ``` { "commit_id": { "author": "commit_author", "message": "commit_message", "timestamp: <datetime object of the timestamp>" } } ```

Parameters
max_historyint, optionalmaximum number of commit that would return, counting backwards from your current commit. Default is set to 500. It needs to be nop-negative, if input is 0 it will still give the last commit.
Returns
list

get_database()

Returns metadata (id, organization, label, comment) about the requested database Parameters ---------- dbid : str The id of the database team : str The organization of the database (default self.team)

Returns
dict

get_databases()

Returns a list of database metadata records for all databases the user has access to

Returns
list of dicts

get_document(iri_id, graph_type, get_data_version, kwargs)

Retrieves the document of the iri_id

Parameters
iri_idstrIri id for the document that is to be retrieved
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
get_data_versionboolIf the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "minimized", "unfold"
Returns
dict

get_documents_by_type(doc_type, graph_type, skip, count, as_list, get_data_version, kwargs)

Retrieves the documents by type

Parameters
doc_typestrSpecific type for the docuemnts that is retriving
graph_typeGraphType, optionalGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
skipintThe starting posiion of the returning results, default to be 0
countint or NoneThe maximum number of returned result, if None (default) it will return all of the avalible result.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
kwargsAdditional boolean flags for retriving. Currently avaliable: "prefixed", "unfold"
Returns
iterableStream of dictionaries

get_existing_classes()

Get all the existing classes (only ids) in a database.

get_organization(org)

Returns a specific organization

Parameters
orgstrThe id of the organization
Returns
dict or None if not found

get_organization_user(org, username)

Returns user info related to an organization.

Parameters
orgstr
usernamestr
Returns
dict or None if not found

get_organization_user_databases(org, username)

Returns the databases available to a user which are inside an organization

Parameters
orgstr
usernamestr
Returns
dict or None if not found

get_organization_users(org)

Returns a list of users in an organization.

Parameters
orgstr
Returns
dict or None if not found

get_organizations()

Returns a list of organizations in the database.

Returns
dict or None if not found

get_triples(graph_type)

Retrieves the contents of the specified graph as triples encoded in turtle format

Parameters
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
Returns
str

get_user(username)

Get a user

Parameters
usernamestrThe username of the user
Returns
dict or None if failed

get_users()

Get all users

Returns
dict or None if failed

has_database(dbid, team)

Check whether a database exists

Parameters
dbidstrThe id of the database
teamstrThe organization of the database (default self.team)
Returns
True or False if not found

has_doc(doc_id, graph_type)

Check if a certain document exist in a database

Parameters
doc_idstrId of document to be checked.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
Returns
Boolif the document exist

info()

Get info of a TerminusDB database server

Returns
dictDict with version information: ``` { "@type": "api:InfoResponse", "api:info": { "authority": "anonymous", "storage": { "version": "1" }, "terminusdb": { "git_hash": "53acb38f9aedeec6c524f5679965488788e6ccf5", "version": "10.1.5" }, "terminusdb_store": { "version": "0.19.8" } }, "api:status": "api:success" } ```

insert_document(document, graph_type, full_replace, commit_msg, last_data_version, compress, raw_json)

Inserts the specified document(s)

Parameters
documentdict or list of dictDocument(s) to be inserted.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
full_replaceboolIf True then the whole graph will be replaced. WARNING: you should also supply the context object as the first element in the list of documents if using this option.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.
raw_jsonboolUpdate as raw json
Returns
listlist of ids of the inseted docuemnts

insert_triples(graph_type, content, commit_msg)

Inserts into the specified graph with the triples encoded in turtle format.

Parameters
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
contentValid set of triples in Turtle or Trig format.
commit_msgstrCommit message.

list_databases()

Returns a list of database ids for all databases the user has access to

Returns
list of dicts

log()

Get commit history of a database Parameters ---------- team : str, optional The team from which the database is. Defaults to the class property. db : str, optional The database. Defaults to the class property. start : int, optional Commit index to start from. Defaults to 0. count : int, optional Amount of commits to get. Defaults to -1 which gets all.

Returns
listList of the following commit objects: ``` { "@id":"InitialCommit/hpl18q42dbnab4vzq8me4bg1xn8p2a0", "@type":"InitialCommit", "author":"system", "identifier":"hpl18q42dbnab4vzq8me4bg1xn8p2a0", "message":"create initial schema", "schema":"layer_data:Layer_4234adfe377fa9563a17ad764ac37f5dcb14de13668ea725ef0748248229a91b", "timestamp":1660919664.9129035 } ```

ok()

Check whether the TerminusDB server is still OK. Status is not OK when this function returns false or throws an exception (mostly ConnectTimeout)

Returns
bool

optimize(path)

Optimize the specified path.

Parameters
pathstringPath to optimize, for instance admin/database/_meta for the repo graph.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.optimize('admin/database') # optimise database branch (here main)
>>> client.optimize('admin/database/_meta') # optimise the repository graph (actually creates a squashed flat layer)
>>> client.optimize('admin/database/local/_commits') # commit graph is optimised

patch(before, patch)

Apply the patch object to the before object and return an after object. Note that this change does not commit changes to the graph.

Parameters
beforedictObject before to patch
patchPatchPatch object to apply to the dict
Returns
dictAfter object
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> patch_obj = Patch(json='{"name" : { "@op" : "ValueSwap", "@before" : "Jane", "@after": "Janine" }}')
>>> result = client.patch({ "@id" : "Person/Jane", "@type" : Person", "name" : "Jane"}, patch_obj)
>>> print(result)
'{ "@id" : "Person/Jane", "@type" : Person", "name" : "Janine"}'

patch_resource()

Apply the patch object to the given resource

Returns
dictAfter object
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> patch_obj = Patch(json='{"name" : { "@op" : "ValueSwap", "@before" : "Jane", "@after": "Janine" }}')
>>> result = client.patch_resource(patch_obj,branch="main")
>>> print(result)
'["Person/Jane"]'

pull(remote, remote_branch, message, author)

Pull updates from a remote repository to the current database.

Parameters
remotestrremote to pull from, default "origin"
remote_branchstr, optionalremote branch to pull from, default to be your current barnch
messagestr, optionaloptional commit message
authorstr, optionaloption to overide the author of the operation
Returns
dict
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.pull()

push(remote, remote_branch, message, author, remote_auth)

Push changes from a branch to a remote repo

Parameters
remotestrremote to push to, default "origin"
remote_branchstr, optionalremote branch to push to, default to be your current barnch
messagestr, optionaloptional commit message
authorstr, optionaloption to overide the author of the operation
remote_authdict, optionaloptional remote authorization (uses client remote auth otherwise)
Returns
dict
Example: Python
>>> Client(server="http://localhost:6363").push(remote="origin", remote_branch = "main", author = "admin", message = "commit message"})

query(woql_query, commit_mg, get_data_version, last_data_version, file_dict)

Updates the contents of the specified graph with the triples encoded in turtle format Replaces the entire graph contents

Parameters
woql_querydict or WOQLQuery objectA woql query as an object or dict
commit_mgstrA message that will be written to the commit log to describe the change
get_data_versionboolIf the data version of the query result(s) should be obtained. If True, the method return the result and the version as a tuple.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
file_dict**deprecated**File dictionary to be associated with post name => filename, for multipart POST
Returns
dict
Example: Python
>>> Client(server="http://localhost:6363").query(woql, "updating graph")

query_document(document_template, graph_type, as_list, get_data_version)

Retrieves all documents that match a given document template

Parameters
document_templatedictTemplate for the document that is being retrived
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
as_listboolIf the result returned as list rather than an iterator.
get_data_versionboolIf the data version of the document(s) should be obtained. If True, the method return the result and the version as a tuple.
Returns
Iterable

rebase(branch, rebase_source, message, author)

Rebase the current branch onto the specified remote branch. Need to specify one of 'branch','commit' or the 'rebase_source'.

Parameters
branchstr, optionalthe branch for the rebase
rebase_sourcestr, optionalthe source branch for the rebase
messagestr, optionalthe commit message
authorstr, optionalthe commit author
Returns
dict
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.rebase("the_branch")

replace_document(document, graph_type, commit_msg, last_data_version, compress, create, raw_json)

Updates the specified document(s)

Parameters
documentdict or list of dictDocument(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.
createboolCreate the document if it does not yet exist.
raw_jsonboolUpdate as raw json

reset(commit, soft, use_path)

Reset the current branch HEAD to the specified commit path. If `soft` is not True, it will be a hard reset, meaning reset to that commit in the backend and newer commit will be wipped out. If `soft` is True, the client will only reference to that commit and can be reset to the newest commit when done.

Parameters
commitstringCommit id or path to the commit (if use_path is True), for instance '234980523ffaf93' or 'admin/database/local/commit/234980523ffaf93'. If not provided, it will reset to the newest commit (useful when need to go back after a soft reset).
softboolFlag indicating if the reset if soft, that is referencing to a previous commit instead of resetting to a previous commit in the backend and wipping newer commits.
use_pathboolWheather or not the commit given is an id or path. Default using id and use_path is False.
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.reset('234980523ffaf93')
>>> client.reset('admin/database/local/commit/234980523ffaf93', use_path=True)

rollback()

Curently not implementated. Please check back later.

set_db(dbid, team)

Set the connection to another database. This will reset the connection.

Parameters
dbidstrDatabase identifer to set in the config.
teamstrTeam identifer to set in the config. If not passed in, it will use the current one.
Returns
strThe current database identifier.
Example: Python
>>> client = Client("http://127.0.0.1:6363")
>>> client.set_db("database1")
'database1'

squash(message, author, reset)

Squash the current branch HEAD into a commit

Parameters
messagestringMessage for the newly created squash commit
authorstringAuthor of the commit
resetboolPerform reset after squash
Returns
strcommit id to be reset
Example: Python
>>> client = Client("http://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> client.squash('This is a squash commit message!')

update_document(document, graph_type, commit_msg, last_data_version, compress)

Updates the specified document(s). Add the document if not existed.

Parameters
documentdict or list of dictDocument(s) to be updated.
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
commit_msgstrCommit message.
last_data_versionstrLast version before the update, used to check if the document has been changed unknowingly
compressstr or intIf it is an integer, size of the data larger than this (in bytes) will be compress with gzip in the request (assume encoding as UTF-8, 0 = always compress). If it is `never` it will never compress the data.

update_triples(graph_type, content, commit_msg)

Updates the contents of the specified graph with the triples encoded in turtle format. Replaces the entire graph contents

Parameters
graph_typeGraphTypeGraph type, either GraphType.INSTANCE or GraphType.SCHEMA.
contentValid set of triples in Turtle or Trig format.
commit_msgstrCommit message.