Python SDK

Detailed Python SDK docs for Keeper Secrets Manager

Download and Installation

Install with PIP

pip3 install -U keeper-secrets-manager-core

Source Code

Find the Python source code in the GitHub repository

Using the SDK

Initialize

Using token only to generate a new config (for later usage) requires at least one read operation to bind the token and fully populate config.json

SecretsManager(token, config)
# Using token, only to generate a config (for later usage),
# requires at least one access operation to bind the token
#get_secrets(uids=None)

Parameter

Required

Description

Type

token

Yes

One Time Access Token

String

config

Yes

Storage Configuration

KeyValueStorage

Retrieve Secrets

get_secrets(uids=None)

Parameter

Type

Required

Default

Description

uids

String[]

Optional

None

Record UIDs to fetch

Response

Type: Record[]

All Keeper records, or records with the given UIDs

Retrieve Values From a Secret

Retrieve a Password

This shortcut gets the password of a secret once that secret has been retrieved from Keeper Secrets Manager.

secret.field('password', single=True)

Retrieve Standard Fields

secret.field(field_type, single=False, value=None)

Parameter

Type

Required

Default

Description

field_type

String

Yes

Field type to get

single

boolean

Optional

False

Return only the first value

value

String or String[]

Optional

None

If passed, set the value of the field to the given value

Fields are found by type, for a list of field types see the Record Types documentation.

Retrieve Custom Fields

secret.custom_field(label, field_type=None, single=False, value=None)

Parameter

Type

Required

Default

Description

label

String

Yes

Label of the custom field

field_type

String

Yes

Field type to get

single

boolean

Optional

False

Return only the first value

value

String or String[]

Optional

None

If passed, set the value of the field to the given value

Custom fields are any field that is not part of the record type definition, but can be added by users. For a list of fields in each standard record type, see the Record Types documentation.

It is possible for multiple fields of the same custom type to appear on a single record, to differentiate these fields, the field label is required.

Response

Type: String or String[]

the value or values of the field. Will be a single value only if the single=True option is passed.

Retrieve Secrets by Title

# get all matching records
get_secrets_by_title(record_title)

# get only the first matching record
get_secret_by_title(record_title)
Parameter
Type
Required
Description

record_title

String

Yes

Record title to search for

Retrieve Values using Keeper Notation

get_notation(query)

See Keeper Notation documentation to learn about Keeper Notation format and capabilities

Parameter

Type

Required

Default

Description

query

String

Yes

Keeper Notation query for getting a value from a specified field

Returns

Type: string or string[]

The value of the queried field

Retrieve a TOTP Code

get_totp_code(url)

Parameter

Type

Required

Default

Description

url

String

Yes

TOTP Url

Update a Secret

Record update commands don't update local record data on success (esp. updated record revision) so any consecutive updates to an already updated record will fail due to revision mismatch. Make sure to reload all updated records after each update batch.

Save Changes to a Secret

save(record: KeeperRecord)

record

KeeperRecord

Yes

Storage and query configuration

Set field values using the field method.

Fields are found by type, for a list of field types see the Record Types documentation. Some fields have multiple values, in these cases the value can be set to a list.

Update a Standard Field Value

secret.field(field_type, single=False, value=None)

Parameter

Type

Required

Default

Description

field_type

String

Yes

Field type to get

single

boolean

Optional

False

Return only the first value

value

String or String[]

Optional

None

If passed, set the value of the field to the given value

Fields are found by type, for a list of field types see the Record Types documentation.

Update a Custom Field Value

secret.custom_field(label, field_type=None, single=False, value=None)

Parameter

Type

Required

Default

Description

label

String

Yes

Label of the custom field

field_type

String

Yes

Field type to get

single

boolean

Optional

False

Return only the first value

value

String or String[]

Optional

None

If passed, set the value of the field to the given value

Generate a Random Password

generate_password(length, lowercase, uppercase, digits, specialCharacters)
Parameter
Type
Required
Default

length

int

Optional

64

lowercase

int

Optional

0

uppercase

int

Optional

0

digits

int

Optional

0

specialCharacters

int

Optional

0

Each parameter indicates the min number of a type of character to include. For example, 'uppercase' indicates the minimum number of uppercase letters to include.

Download a File

file.save_file(file_path, create_folders=False)

Parameter

Type

Required

Default

Description

file_path

String

Yes

Path to save file to

create_folders

boolean

No

False

Create folders in the file_path if not present

Upload a File

Upload File:

upload_file(owner_record, file: my_file)

Creating the Keeper File Upload Object:

KeeperFileUpload.from_file(path, file_name=None, file_title=None, mime_type=None)

Upload File

Parameter
Type
Required
Description

owner_record

KeeperRecord

Yes

The record to attach the uploaded file to

file

KeeperFileUpload

Yes

The File to upload

Keeper File Upload From File

Parameter
Type
Required
Default
Description

path

string

Yes

Path to the file to upload

file_name

string

No

None

What the name of the file will be in Keeper once uploaded

file_title

string

No

None

What the title of the file will be in Keeper once uploaded

mime_type

string

No

None

The type of data in the file. If none is provided, 'application/octet-stream' will be used

Returns

Type: string

The file UID of the attached file

Create a Secret

Prerequisites:

  • Shared folder UID

    • Shared folder must be accessible by the Secrets Manager Application

    • You and the Secrets Manager application must have edit permission

    • There must be at least one record in the shared folder

  • Created records and record fields must be formatted correctly

    • See the documentation for expected field formats for each record type

  • TOTP fields accept only URL generated outside of the KSM SDK

  • After record creation, you can upload file attachments using upload_file

secrets_manager.create_secret(folder_uid, record)
Parameter
Type
Required
Default

folder_uid

String

Yes

record

KeeperRecord

Yes

Returns

Type: string

The record UID of the new record

Delete a Secret

The Python KSM SDK can delete records in the Keeper Vault.

secrets_manager.delete_secret(record_uid)

Parameter
Type
Required

record_uid

string

Yes

Caching

To protect against losing access to your secrets when network access is lost, the Python SDK allows caching of secrets to the local machine in an encrypted file.

Setup and Configure Cache

In order to setup caching in the Python SDK, include a caching post function when creating a SecretsManager object.

The Python SDK includes a default caching function in KSMCache class which stores cached queries to a local file thus serving as a disaster recovery function (as long as there's network connectivity it always prefers network over cached data and will use cache only if web vault is inaccessible). You can create your own caching function using KSMCache as a starting point - ex. one that prefers local cache over network access and provide own cache management (ex. refresh cached data once every 5 min)

secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json'),
    custom_post_function=KSMCache.caching_post_function
)

The default caching function in KSMCache class always stores last request only - ex. filtered request on UID1 but on disconnect request UID2 from same cache will return empty response (although UID2 may be shared to the same KSM app but it was not cached)

Updating a record from cache (or creating new record) invalidates cached record data and consecutive updates of the same record will fail. Batch updates work as long as they modify different records. Always follow up cached record updates with a call to get_secrets function to refresh cache (and pull updated metadata from vault like the new record revision etc.)

Folders

Folders have full CRUD support - create, read, update and delete operations.

Read Folders

Downloads full folder hierarchy.

get_folders()

Response

Type: List[KeeperFolder]

Example Usage

from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

secrets_manager = SecretsManager(config=FileKeyValueStorage('ksm-config.json'))
folders = secrets_manager.get_folders()

Create a Folder

Requires CreateOptions and folder name to be provided. The folder UID parameter in CreateOptions is required - UID of a shared folder, while sub-folder UID is optional and if missing new regular folder is created directly under the parent (shared folder). There's no requirement for the sub-folder to be a direct descendant of the parent shared folder - it could be many levels deep.

create_folder(create_options: CreateOptions, folder_name: str, folders=None)
Parameter
Type
Required
Default
Description

create_options

CreateOptions

Yes

The parent and sub-folder UIDs

folder_name

str

Yes

The Folder name

folders

List[KeeperFolder]

No

None

List of folders to use in the search for parent and sub-folder from CreateOptions

Example Usage

from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.core import CreateOptions
from keeper_secrets_manager_core.storage import FileKeyValueStorage

secrets_manager = SecretsManager(config=FileKeyValueStorage('ksm-config.json'))
co = CreateOptions(folder_uid="[PARENT_SHARED_FOLDER_UID]", subfolder_uid="")
new_folder_uid = secrets_manager.create_folder(co, "new_folder")

Update a Folder

Updates the folder metadata - currently folder name only.

update_folder(folder_uid: str, folder_name: str, folders=None)
Parameter
Type
Required
Default
Description

folder_uid

str

Yes

The folder UID

folder_name

str

Yes

The new folder name

folders

List[KeeperFolder]

No

None

List of folders to use in the search for parent folder

Example Usage

from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

secrets_manager = SecretsManager(config=FileKeyValueStorage('ksm-config.json'))
secrets_manager.update_folder("[FOLDER_UID]", "new_folder_name")

Delete Folders

Removes a list of folders. Use force_deletion flag to remove non-empty folders.

When using force_deletion avoid sending parent with its children folder UIDs. Depending on the delete order you may get an error - ex. if parent force-deleted child first. There's no guarantee that list will always be processed in FIFO order.

Any folders UIDs missing from the vault or not shared to the KSM Application will not result in error.

delete_folder(folder_uids: List[str], force_deletion: bool = False)
Parameter
Type
Required
Default
Description

folder_uids

List[str]

Yes

The folder UID list

force_deletion

bool

No

False

Force deletion of non-empty folders

Example Usage

from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

secrets_manager = SecretsManager(config=FileKeyValueStorage('ksm-config.json'))
secrets_manager.delete_folder(["[FOLDER_UID1]", "[FOLDER_UID2]"], True)

Last updated