Start with a Client API
A step-by-step guide with examples to install and get started with a JavaScript or Python client.
This guide demonstrates the basic use of the WOQLClient library to connect to TerminusCMS with a JavaScript or Python client. Refer to the JavaScript Client or Python Client references guides for detailed documentation. The code discussed on this page is also available in full:
JavaScript
Python
Install the TerminusDB JavaScript client by adding it as a dependency in your Node project.
npm install --save @terminusdb/terminusdb-client
Install the Python client using
pip
. Using a virtual environment is recommended - see Python documentation.Create a new virtual environment named terminusdb-env
python3 -m venv terminusdb-env
Activate terminusdb-env environment
Unix/macOS:
source terminusdb-env/bin/activate
Windows:
.\terminusdb-env\Scripts\activate
Install the Python client
python3 -m pip install terminusdb-client
A
WOQLClient
object enables connection to TerminusCMS (or TerminusDB.) To create a client object:- Copy the JavaScript/Python code snippet generated in the step above.
- Provide the URL to a database server.
Define and initialize a WOQLClient, and connect to a database using the example below.
Code: Define and initialize a WOQLClient
JavaScript
Python
Use the package
@terminusdb/terminusdb-client
const TerminusDBClient = require("@terminusdb/terminusdb-client");
// TODO: change the team name
const team = "TEAM_NAME";
const client = new TerminusDBClient.WOQLClient(`https://cloud.terminusdb.com/${team}/`, {
user: "[email protected]",
organization: team
});
//set the key as an environment variable.
client.setApiKey(process.env.TERMINUSDB_ACCESS_TOKEN)
from terminusdb_client import WOQLClient
user = "jimbo"
team = "logicistics" # My team name.
endpoint = "https://cloud.terminusdb.com/{team}/"
client = WOQLClient(endpoint)
client.connect(user=user, team=team, use_token=True)
Code: Connect to a database
Connect to an existing database using the example below.
JavaScript
Python
client.db('ExampleDatabase');
connect(team=team, user="admin", db="example_db", use_token=True)
Code: Create a database
Create a new database using the example below.
JavaScript
Python
const createNewDB = async () => {
try {
await client.createDatabase('ExampleDatabase', {
label: "ExampleDatabase",
comment: "Created new ExampleDatabase",
});
console.log("Database created Successfully!")
} catch (err) {
console.error(err)
}
};
createNewDB();
client.connect(team=team, user="admin", use_token=True)
client.create_database("example_db")
To use the TerminusCMS document interface, create a schema and add documents to the schema. Refer to Documents for an overview of the document interface. After creating or connecting to a database, create a schema to add and retrieve data. A simple player roster is used as an example. Using basic Player roster data, the steps below are demonstrated.
name | position
------ | --------
George | Center Back
Doug | Full Back
Karen | Center Forward
Create a schema object with properties
name
and position
. The object is uniquely identified by name
.JavaScript
Python
const schema = { "@type" : "Class",
"@id" : "Player",
"@key" : { "@type": "Lexical", "@fields": ["name"] },
name : "xsd:string",
position: "xsd:string" };
from terminusdb_client.woqlschema import WOQLSchema, DocumentTemplate, LexicalKey
schema = WOQLSchema()
class Player(DocumentTemplate):
_schema = schema
_key = LexicalKey(["name"])
name: str
position: str
Add the schema object to the database.
JavaScript
Python
Add the schema object to a document using
addDocument
which returns a Promise.await client.addDocument(schema, { graph_type: "schema" })
Commit the schema object to the database.
schema.commit(client, commit_msg = "Adding Player Schema")
Once a schema is added, add documents corresponding to the schema.
JavaScript
Python
Add documents to the schema using
addDocument
which returns a Promise.const objects = [
{
"@type" : "Player",
name : "George",
position: "Center Back",
},
{
"@type" : "Player",
name : "Doug",
position: "Full Back",
},
{
"@type" : "Player",
name : "Karen",
position: "Center Forward"
}
];
await client.addDocument(objects);
Add documents to the schema using
insert_document
.objects = [
Player(name="George", position="Centre Back"),
Player(name="Doug", position="Full Back"),
Player(name="Karen", position="Centre Forward")
]
client.insert_document(objects, commit_msg = f"Inserting player data")
Get a list of documents or specific documents added to the schema
JavaScript
Python
Get a list of documents using
getDocument
as_list
. Results, stored in document
, are shown further below.const getDocs = async () => {
const documents = await client.getDocument({ as_list: "true" });
console.log("All Documents", documents)
}
[
{
'@id' : 'Player/Doug',
'@type' : 'Player',
name : 'Doug',
position: 'Full Back'
},
{
'@id' : 'Player/George',
'@type' : 'Player',
name : 'George',
position: 'Center Back'
},
{
'@id' : 'Player/Karen',
'@type' : 'Player',
name : 'Karen',
position: 'Center Forward'
}
]
Get a specific document using
query_document
. Results, stored in matches
, are shown further below.documents = client.get_all_documents()
# documents comes back as a iterable that can be convert into a list
print("All documents")
print(list(documents))
print("=============")
# getting a specific document by id
player_doug = client.get_document("Player/Doug")
print("Specific document")
print(player_doug)
All documents
[
{
'@id' : 'Player_Doug',
'@type' : 'Player',
name : 'Doug',
position: 'Full Back'
},
{
'@id' : 'Player_George',
'@type' : 'Player',
name : 'George',
position: 'Center Back'
},
{
'@id' : 'Player_Karen',
'@type' : 'Player',
name : 'Karen',
position: 'Center Forward'
}
]
=============
Specific document
{
'@id' : 'Player_Doug',
'@type' : 'Player',
name : 'Doug',
position: 'Full Back'
}
Get a list of documents that matches the query
JavaScript
Python
Get a list of documents using
getDocument
as_list
. Results, stored in document
, are shown further below.const queryDocuments = async () => {
const query = {
"type": "Player",
"query": { "position": "Full Back" },
}
const result = await client.queryDocument(query,{"as_list":true});
console.log("Query Documents",result)
}
[{"@type" : "Player",
"name" : "Doug",
"position" : "Full Back"}]
Get a specific document using
query_document
. Results, stored in matches
, are shown further below.matches = client.query_document({"@type" : "Player",
"position": "Full Back"})
# matches comes back as a iterable that can be convert into a list
print(list(matches))
[{"@type" : "Player",
"name" : "Doug",
"position" : "Full Back"}]
Query documents using Web Object Query Language (WOQL) to get the same result given by the above example. You can find more about WOQL here.
JavaScript
Python
Get documents using using
WOQL.triple()
to create a WOQL query then execute that query using client.query()
. Results, stored in results
, are shown further belowconst queryDocuments = async () => {
const { WOQL } = TerminusDBClient;
const query = WOQL.triple(
"v:Player",
"position",
WOQL.string("Full Back")
).triple("v:Player", "position", "v:position");
const results = await client.query(query);
console.log("Query Documents using WOQL: ",results.bindings);
}
[
{
Player: 'Player/Doug',
position: { '@type': 'xsd:string', '@value': 'Full Back' }
}
]
Get documents using
WOQLQuery()
and WOQLQuery().triple()
to create a WOQL query then execute that query using client.query()
. Results, stored in results
, are shown further below.WOQL = WOQLQuery()
query = WOQL.triple("v:Player", "position", WOQL.string("Full Back")).triple(
"v:Player", "position", "v:position"
)
results = client.query(query)
print("Specific document using WOQL")
# results['bindings'] holds the query output as a list
print(results['bindings'])
[
{
Player: 'Player/Doug',
position: { '@type': 'xsd:string', '@value': 'Full Back' }
}
]
The following code segments demonstrate creating relationships or links between documents
The
Team
object is uniquely identified by the property name
. The players
property consists of a set of Player
classes that create a link between theTeam
and Player
schema.Javascript
Python
const team_schema = [
{
"@type" : "Class",
"@id" : "Team",
"@key" : {
"@type": "Lexical",
"@fields": ["name"]
},
name : "xsd:string",
players: { "@type" : "Set",
"@class" : "Player" },
}
];
from typing import Set
class Team(DocumentTemplate):
_schema = schema
_key = LexicalKey(["name"])
name: str
players: Set['Player']
Add the schema object to the database.
JavaScript
Python
Add the schema object to a document using
addDocument
that returns a Promise.await client.addDocument(team_schema, { graph_type: "schema" })
Commit the schema object to the database.
schema.commit(client, commit_msg = "Adding Team Schema")
Add documents corresponding to the
Team
schema.JavaScript
Python
const team_instance = [
{
"@type" : "Team",
name : "Wildcats",
players: ["Player/Doug", "Player/Karen"],
},
{
"@type" : "Team",
name : "Donkeys",
players: ["Player/George"],
}
]
await client.addDocument(team_instance)
doug_raw = client.get_document("Player/Doug")
karen_raw = client.get_document("Player/Karen")
george_raw = client.get_document("Player/George")
doug = schema.import_objects(doug_raw)
karen = schema.import_objects(karen_raw)
george = schema.import_objects(george_raw)
team_objects = [
Team(name="Wildcats", position={doug, karen}),
Team(name="Donkeys", position={george},
]
client.insert_document(team_objects, commit_msg = f"Inserting teams data")
Get a list of
Team
documents.JavaScript
Python
const getTeams = async () => {
const query = {
"type": "Team",
};
const result = await client.queryDocument(query, {"as_list":true});
console.log("Teams ",result)
}
teams = client.query_document({"@type" : "Team"})
print(list(matches))
Last modified 2d ago