> For the complete documentation index, see [llms.txt](https://docs.keeper.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.keeper.io/keeperpam/secrets-manager/developer-sdk-library/python-sdk.md). Agents can also search and read this documentation through its [MCP server](https://docs.keeper.io/~gitbook/mcp).

# Python SDK

Detailed Python SDK docs for Keeper Secrets Manager

<figure><img src="https://762006384-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJXOXEifAmpyvNVL1to%2Fuploads%2Fq5NweawmL7egYFUPwVGz%2FKSM%20%2B%20python.png?alt=media&#x26;token=f444ebf4-73be-42a6-bbd9-ce8e5938f89f" alt=""><figcaption></figcaption></figure>

## Download and Installation

### Install with PIP

```bash
pip3 install -U keeper-secrets-manager-core
```

**Python Requirements**: Python 3.10 or higher

Python 3.9 users stay on core 17.3.0 and helper 1.1.2. pip selects these versions automatically.

For more information, see <https://pypi.org/project/keeper-secrets-manager-core/>

### Source Code

Find the Python source code in the [GitHub repository](https://github.com/Keeper-Security/secrets-manager/tree/master/sdk/python)

**Related Packages**:

* [Core SDK (keeper-secrets-manager-core)](https://pypi.org/project/keeper-secrets-manager-core/)
* [Helper Package (keeper-secrets-manager-helper)](https://pypi.org/project/keeper-secrets-manager-helper/)
* [Storage Packages](https://pypi.org/project/keeper-secrets-manager-storage/), with integrations for:
  * [AWS KMS Encryption](https://docs.keeper.io/keeperpam/secrets-manager/integrations/aws-kms.md)
  * [AWS Secrets Manager Storage](https://docs.keeper.io/keeperpam/secrets-manager/integrations/aws-secrets-manager-storage.md)
  * [Azure Key Vault Encryption](https://docs.keeper.io/keeperpam/secrets-manager/integrations/azure-key-vault-ksm.md)
  * [Entrust HSM Encryption](https://docs.keeper.io/keeperpam/secrets-manager/integrations/entrust-hsm.md)
  * [Google Cloud KMS](https://docs.keeper.io/keeperpam/secrets-manager/integrations/google-cloud-key-management-encryption.md)
  * [Oracle Cloud Infrastructure Vault](https://docs.keeper.io/keeperpam/secrets-manager/integrations/oracle-key-vault-1.md)

## Using the SDK

### Initialize

{% hint style="warning" %}
**One-Time Token behavior**: The token is consumed on first use, including on failed attempts. If the first request that binds the client fails, the SDK (v17.3.0+ for `get_secrets()`, v18.0.0+ for `get_folders()`) removes the incomplete config file when the storage is file-based. Generate a new One-Time Token from your KSM Application and retry.

At least one API call (e.g. `get_secrets()` or `get_folders()`) must follow initialization to complete token binding and fully populate the config file. Subsequent runs without a token use the config file directly.
{% endhint %}

{% tabs %}
{% tab title="Secrets Manager" %}

```python
SecretsManager(token=token, config=config)
# At least one API call is required to complete token binding
get_secrets(uids=None)
```

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)
# Required: completes token binding and populates the config file
secrets_manager.get_secrets()
```

{% endtab %}
{% endtabs %}

| Parameter          | Type              | Required | Default                 | Description                                                                                                                                                                                                             |
| ------------------ | ----------------- | -------- | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `token`            | `str`             | Optional | None                    | One-time access token. Needed on first run to bind the application; omit once config is bound                                                                                                                           |
| `config`           | `KeyValueStorage` | Optional | `FileKeyValueStorage()` | Storage backend. If omitted, the SDK uses the `KSM_CONFIG` environment variable when it is set, and otherwise file storage. The file is named by `KSM_CONFIG_FILE`, or is `client-config.json` in the current directory |
| `hostname`         | `str`             | Optional | None                    | Server hostname. **Required** when using a bare token without a region prefix. A token with a region prefix sets the hostname itself                                                                                    |
| `verify_ssl_certs` | `bool`            | Optional | True                    | Verify SSL certificates on outbound requests. The `KSM_SKIP_VERIFY` environment variable overrides this value                                                                                                           |
| `log_level`        | `str` or `int`    | Optional | None                    | SDK log level: `"CRITICAL"`, `"ERROR"`, `"WARNING"`, `"INFO"`, `"DEBUG"`, or `"NOTSET"`, or a `logging` level number. With `None`, SDK logging is off                                                                   |

{% hint style="info" %}
Configuration files are automatically created with secure permissions (0600 on Unix-based systems) in v17.1.0+.
{% endhint %}

### Binding Lifecycle

The one-time token is redeemed on the first call that reads secrets or folders, such as `get_secrets()` or `get_folders()`, not at construction. If you persist config to an external store (AWS Secrets Manager, Azure Key Vault, etc.), read it back only after that call. For the full explanation, see [Binding Lifecycle](https://docs.keeper.io/keeperpam/secrets-manager/about/secrets-manager-configuration.md#binding-lifecycle).

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# First run: provide a one-time token and a persistent storage path.
sm = SecretsManager(
    token="US:BASE64_ONE_TIME_TOKEN",
    config=FileKeyValueStorage("ksm-config.json")
)
records = sm.get_secrets()  # Token is redeemed here; ksm-config.json is updated.

# Subsequent runs: omit the token. Stored credentials are used directly.
sm = SecretsManager(config=FileKeyValueStorage("ksm-config.json"))
records = sm.get_secrets()
```

### Retrieve Secrets

{% tabs %}
{% tab title="Get Secrets" %}

```python
get_secrets(uids=None, full_response=False)
```

{% endtab %}

{% tab title="Example: Get All Secrets" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get all records
all_secrets = secrets_manager.get_secrets()

# print out all records
for secret in all_secrets:
    print(secret.dict)
```

{% endtab %}

{% tab title="Example: Get Secrets With a Filter" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by record UID
secret = secrets_manager.get_secrets(['EG6KdJaaLG7esRZbMnfbFA'])[0]

# print out secret
print(secret.dict)
```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th width="150">Parameter</th><th width="150">Type</th><th width="150">Required</th><th width="150">Default</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Default</td><td>Description</td></tr><tr><td><code>uids</code></td><td><code>List[str]</code></td><td>Optional</td><td>None</td><td>Record UIDs to fetch</td></tr><tr><td><code>full_response</code></td><td><code>bool</code></td><td>Optional</td><td>False</td><td>Return the full response object (<code>records</code>, <code>folders</code>, <code>bad_records</code>, <code>drive_folder_uids</code>) instead of a list of records</td></tr></tbody></table>

**Response**

Type: **`Record[]`**

All Keeper records, or records with the given UIDs

`get_secrets()` returns each record once, also when a record is reachable through both a shared folder and a direct share.

If the SDK cannot decrypt a record in a shared folder, it skips that record and returns the other records of the folder. Call `get_secrets(full_response=True)` and read `bad_records` on the response to see the skipped records. The SDK also logs each skipped record when SDK logging is enabled.

Each record has `is_drive`. It is `True` when a folder entry of Nested Shared Folders (NSF) in the response holds the record. With `full_response=True`, each folder in `folders` also has `is_drive`. The `drive_folder_uids` attribute holds the UIDs of the NSF folder entries in the response.

### 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.

{% tabs %}
{% tab title="Get Password" %}

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

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by record UID
secret = secrets_manager.get_secrets(['<RECORD UID>'])[0]

# get password from record
my_secret_password = secret.field('password', single=True)
```

{% endtab %}
{% endtabs %}

#### Retrieve Standard Fields

{% tabs %}
{% tab title="Field" %}

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

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by record UID
secret = secrets_manager.get_secrets(['<RECORD UID>'])[0]

# get login field from the secret
my_secret_login = secret.field("login", single=True)
```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th width="168">Parameter</th><th width="150">Type</th><th>Required</th><th width="202">Default</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Default</td><td>Description</td></tr><tr><td><code>field_type</code></td><td><code>str</code></td><td>Yes</td><td></td><td>Field type to get</td></tr><tr><td><code>value</code></td><td><code>str</code>, <code>int</code>, <code>bool</code>, <code>dict</code>, or a <code>list</code> of these</td><td>Optional</td><td>None</td><td>If passed, set the value of the field to the given value. A value that is not a list is wrapped in a list. The type depends on the field type, for example a <code>dict</code> for a name or host field</td></tr><tr><td><code>single</code></td><td><code>bool</code></td><td>Optional</td><td>False</td><td>Return only the first value, or <code>None</code> when the field has no value. Has no effect when you set a value</td></tr></tbody></table>

Field types are based on the Keeper [Record Type](https://docs.keeper.io/enterprise-guide/record-types.md). For a detailed list of available fields based on the Keeper Record Type, see the [record-type-info](https://docs.keeper.io/keeperpam/commander-cli/command-reference/record-commands/record-type-commands.md#record-type-info-command) command in Keeper Commander.

#### Retrieve Custom Fields

{% tabs %}
{% tab title="Custom Field" %}

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

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by UID
secret = secrets_manager.get_secrets(['EG6KdJaaLG7esRZbMnfbFA'])[0]

# Get a standard template field
password = secret.field('password', single=True)

# Get a custom field, e.g. API Key
api_key = secret.custom_field('API Key', single=True)
```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th>Parameter</th><th width="150">Type</th><th width="150">Required</th><th width="150">Default</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Default</td><td>Description</td></tr><tr><td><code>label</code></td><td><code>str</code></td><td>Yes</td><td></td><td>Label of the custom field</td></tr><tr><td><code>value</code></td><td><code>str</code>, <code>int</code>, <code>bool</code>, <code>dict</code>, or a <code>list</code> of these</td><td>Optional</td><td>None</td><td>If passed, set the value of the field to the given value. A value that is not a list is wrapped in a list. The type depends on the field type, for example a <code>dict</code> for a name or host field</td></tr><tr><td><code>field_type</code></td><td><code>str</code></td><td>Optional</td><td>None</td><td>Field type to get</td></tr><tr><td><code>single</code></td><td><code>bool</code></td><td>Optional</td><td>False</td><td>Return only the first value, or <code>None</code> when the field has no value. Has no effect when you set a value</td></tr></tbody></table>

Custom fields are any field that is **not** part of the record type definition, but can be added by users.

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: **`list`** of values, or one value when `single=True` is passed

A value is a `str`, `int`, `bool`, or `dict`, depending on the field type.

#### Retrieve Secrets by Title

{% tabs %}
{% tab title="Records by Title" %}

```python
# get all matching records
get_secrets_by_title(record_title)

# get only the first matching record
get_secret_by_title(record_title)
```

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    config=FileKeyValueStorage('ksm-config.json'))

# get the first secret matching the record title
secret = secrets_manager.get_secret_by_title("My Credentials")

# get all secrets matching the record title
secrets = secrets_manager.get_secrets_by_title("My Credentials")
```

{% endtab %}
{% endtabs %}

<table><thead><tr><th width="178.10385756676556">Parameter</th><th width="226.46137991694417">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>record_title</code></td><td><code>str</code></td><td>Yes</td><td>Record title to search for</td></tr></tbody></table>

#### Retrieve Values using Keeper Notation

{% tabs %}
{% tab title="Get Notation" %}

```python
get_notation(url)
```

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific standard field with Keeper Notation
password = secrets_manager.get_notation('EG6KdJaaLG7esRZbMnfbFA/field/password')

# get a specific custom field with Keeper Notation
custom_field_value = secrets_manager.get_notation('EG6KdJaaLG7esRZbMnfbFA/custom_field/my_field')
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
See [Keeper Notation documentation](https://docs.keeper.io/keeperpam/secrets-manager/about/keeper-notation.md) to learn about Keeper Notation format and capabilities
{% endhint %}

<table data-header-hidden><thead><tr><th width="150">Parameter</th><th width="150">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>Yes</td><td>Keeper Notation query for getting a value from a specified field</td></tr></tbody></table>

#### Returns

Type: depends on the notation

The `type`, `title` and `notes` selectors return a `str` (`None` when there are no notes). The `file` selector returns `bytes`. The `field` and `custom_field` selectors return one value, or a list of values for a notation that ends with `[]`. A value is a `str`, `int`, `bool`, or `dict`.

#### Retrieve a TOTP Code

{% tabs %}
{% tab title="Get TOTP Code" %}

```python
get_totp_code(url)
```

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
from keeper_secrets_manager_core.utils import get_totp_code

# setup secrets manager
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by record UID
record = secrets_manager.get_secrets(['<RECORD UID>'])[0]

# get TOTP url value from the record
url = record.get_standard_field_value('oneTimeCode', True)

# get code from TOTP url
totp = get_totp_code(url)
print(totp.code)
```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th width="150">Parameter</th><th width="150">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>url</code></td><td><code>str</code></td><td>Yes</td><td>TOTP URI in <code>otpauth://</code> format. Raises <code>ValueError</code> if the URI scheme is not <code>otpauth</code></td></tr></tbody></table>

### PAM Record Types

Use `record.type` to identify PAM records returned by the SDK.

```python
for record in records:
    if record.type == "pamMachine":
        host = record.field("pamHostname")[0]  # {"hostName": ..., "port": ...}
    elif record.type == "pamUser":
        login = record.field("login")[0]
    elif record.type == "pamDatabase":
        db_type = record.field("databaseType")[0]
```

For field schemas of all 11 PAM record types, see [PAM Record Types](https://docs.keeper.io/keeperpam/secrets-manager/about/pam-record-types.md).

### Linked Credentials

PAM records can carry links to credential records. Links are not included in `get_secrets()` responses by default. Request them via `get_secrets_with_options()` with `request_links=True`, then call `record.get_links()` to access them as typed `KeeperRecordLink` objects.

{% tabs %}
{% tab title="Get Links" %}

```python
from keeper_secrets_manager_core.dto.payload import QueryOptions

query_options = QueryOptions(
    records_filter=['<RECORD UID>'],
    folders_filter=None,
    request_links=True
)
records = secrets_manager.get_secrets_with_options(query_options)

for link in records[0].get_links():
    print(link.record_uid)   # UID of the linked record
    print(link.path)         # None = credential link; "meta" = PAM settings
```

{% endtab %}

{% tab title="Example: Credential Links" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
from keeper_secrets_manager_core.dto.payload import QueryOptions

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

query_options = QueryOptions(
    records_filter=['<RECORD UID>'],
    folders_filter=None,
    request_links=True
)
records = secrets_manager.get_secrets_with_options(query_options)

for link in records[0].get_links():
    print(f"Linked record: {link.record_uid}  path: {link.path}")

    # Credential link flags (path is None)
    if link.path is None:
        print(f"  Admin user:         {link.is_admin_user()}")
        print(f"  Launch credential:  {link.is_launch_credential()}")
        print(f"  IAM user:           {link.is_iam_user()}")

    # PAM settings flags (path == "meta")
    if link.path == "meta":
        print(f"  Allows rotation:     {link.allows_rotation()}")
        print(f"  Allows connections:  {link.allows_connections()}")
```

{% endtab %}
{% endtabs %}

**`KeeperRecordLink` attributes**

| Attribute    | Type            | Description                                                                                                                                                                |
| ------------ | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `record_uid` | `str`           | UID of the linked record                                                                                                                                                   |
| `path`       | `str` or `None` | Link type discriminator. `None` = credential link to another record; `"meta"` = PAM settings self-link; `"ai_settings"` / `"jit_settings"` = encrypted settings self-links |
| `data`       | `str` or `None` | Raw base64 link payload. Use accessor methods instead of reading this directly                                                                                             |

**`KeeperRecordLink` methods**

| Method                       | Returns          | Description                                     |
| ---------------------------- | ---------------- | ----------------------------------------------- |
| `is_admin_user()`            | `bool`           | Linked credential is an admin user              |
| `is_launch_credential()`     | `bool`           | Link is a launch credential                     |
| `is_iam_user()`              | `bool`           | Linked credential is an IAM user                |
| `belongs_to()`               | `bool`           | Linked credential belongs to the record         |
| `allows_rotation()`          | `bool`           | Rotation is permitted (credential or meta link) |
| `allows_connections()`       | `bool`           | Connections are permitted                       |
| `allows_port_forwards()`     | `bool`           | Port forwarding is permitted                    |
| `allows_session_recording()` | `bool`           | Session recording is enabled                    |
| `get_rotation_settings()`    | `dict` or `None` | Rotation schedule and complexity settings       |
| `get_meta_data()`            | `dict` or `None` | Full PAM settings payload (`path == "meta"`)    |
| `get_link_data()`            | `dict` or `None` | Complete parsed link payload for any path       |

### Update a Secret

{% hint style="warning" %}
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.
{% endhint %}

**Save Changes to a Secret**

{% tabs %}
{% tab title="Save Secret" %}

```python
save(record: Record, transaction_type=None, links_to_remove=None)
```

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by UID
secret_to_update = secrets_manager.get_secrets(['EG6KdJaaLG7esRZbMnfbFA'])[0]

# update a field value
secret_to_update.field('login', value='new login')

# save updated secret
secrets_manager.save(secret_to_update)
```

{% endtab %}

{% tab title="Transactional updates" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
     config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by UID
secret = secrets_manager.get_secrets(['EG6KdJaaLG7esRZbMnfbFA'])[0]

# rotate password on the record
secret.field('password', value='new password')
# start a transaction
secrets_manager.save(secret, 'rotation')
# rotate password on remote host
success = rotate_remote_ssh_password('new password')
# complete the transaction - commit or rollback
secrets_manager.complete_transaction(secret.uid, rollback=not success)

```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th width="150">Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td><code>record</code></td><td><code>Record</code></td><td>Yes</td><td>Record to save</td></tr><tr><td><code>transaction_type</code></td><td><code>str</code></td><td>No</td><td><code>'rotation'</code> starts a transaction. Finish it with <code>complete_transaction()</code></td></tr><tr><td><code>links_to_remove</code></td><td><code>str</code> or <code>List[str]</code></td><td>No</td><td>File UID(s) to remove from the record</td></tr></tbody></table>

Set field values using the [field](#retrieve-standard-fields) method. For a detailed list of available fields based on the Keeper Record Type, see the [record-type-info](https://docs.keeper.io/keeperpam/commander-cli/command-reference/record-commands/record-type-commands.md#record-type-info-command) command in Keeper Commander. Some fields have multiple values, in these cases the value can be set to a list.

#### Update a Standard Field Value

{% tabs %}
{% tab title="Field" %}

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

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by record UID
secret = secrets_manager.get_secrets(['<RECORD UID>'])[0]

# update login
secret.field("login", value="My New Login")

# save secret
secrets_manager.save(secret)
```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th width="168">Parameter</th><th width="150">Type</th><th width="150">Required</th><th width="150">Default</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Default</td><td>Description</td></tr><tr><td><code>field_type</code></td><td><code>str</code></td><td>Yes</td><td></td><td>Field type to get</td></tr><tr><td><code>value</code></td><td><code>str</code>, <code>int</code>, <code>bool</code>, <code>dict</code>, or a <code>list</code> of these</td><td>Optional</td><td>None</td><td>If passed, set the value of the field to the given value. A value that is not a list is wrapped in a list. The type depends on the field type, for example a <code>dict</code> for a name or host field</td></tr><tr><td><code>single</code></td><td><code>bool</code></td><td>Optional</td><td>False</td><td>Return only the first value, or <code>None</code> when the field has no value. Has no effect when you set a value</td></tr></tbody></table>

#### Update a Custom Field Value

{% tabs %}
{% tab title="Custom Field" %}

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

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by UID
secret = secrets_manager.get_secrets(['EG6KdJaaLG7esRZbMnfbFA'])[0]

# Get a standard template field
password = secret.field('password', single=True)

# Set custom field 'API Key'
my_new_api_key = "wKridl2ULt20qGuiP3IY"
secret.custom_field('API Key', value=my_new_api_key)

# Save changes to the secret
secrets_manager.save(secret)
```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th width="171">Parameter</th><th width="150">Type</th><th width="150">Required</th><th width="150">Default</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Default</td><td>Description</td></tr><tr><td><code>label</code></td><td><code>str</code></td><td>Yes</td><td></td><td>Label of the custom field</td></tr><tr><td><code>value</code></td><td><code>str</code>, <code>int</code>, <code>bool</code>, <code>dict</code>, or a <code>list</code> of these</td><td>Optional</td><td>None</td><td>If passed, set the value of the field to the given value. A value that is not a list is wrapped in a list. The type depends on the field type, for example a <code>dict</code> for a name or host field</td></tr><tr><td><code>field_type</code></td><td><code>str</code></td><td>Optional</td><td>None</td><td>Field type to get</td></tr><tr><td><code>single</code></td><td><code>bool</code></td><td>Optional</td><td>False</td><td>Return only the first value, or <code>None</code> when the field has no value. Has no effect when you set a value</td></tr></tbody></table>

#### Generate a Random Password

{% tabs %}
{% tab title="Generate Password" %}

```python
generate_password(length, lowercase, uppercase, digits, special_characters, special_characterset)
```

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
from keeper_secrets_manager_core.utils import generate_password

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# get a specific secret by UID
secret = secrets_manager.get_secrets(['EG6KdJaaLG7esRZbMnfbFA'])[0]

# generate a random password
password = generate_password(special_characterset="@!#$%^&*<>?")
# update a record with new password
secret.field('password', value=password)

# Save changes to the secret
secrets_manager.save(secret)
```

{% endtab %}
{% endtabs %}

<table><thead><tr><th width="202.20703125">Parameter</th><th width="103.15625">Type</th><th width="125.875">Required</th><th width="100.046875">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>length</code></td><td><code>int</code></td><td>Optional</td><td>32</td><td>Minimum total password length</td></tr><tr><td><code>lowercase</code></td><td><code>int</code></td><td>Optional</td><td>None</td><td>Minimum lowercase chars (positive), exact count (zero or negative), or unconstrained (<code>None</code>)</td></tr><tr><td><code>uppercase</code></td><td><code>int</code></td><td>Optional</td><td>None</td><td>Minimum uppercase chars (positive), exact count (zero or negative), or unconstrained (<code>None</code>)</td></tr><tr><td><code>digits</code></td><td><code>int</code></td><td>Optional</td><td>None</td><td>Minimum digit chars (positive), exact count (zero or negative), or unconstrained (<code>None</code>)</td></tr><tr><td><code>special_characters</code></td><td><code>int</code></td><td>Optional</td><td>None</td><td>Minimum special chars (positive), exact count (zero or negative), or unconstrained (<code>None</code>)</td></tr><tr><td><code>special_characterset</code></td><td><code>str</code></td><td>Optional</td><td><code>"!@#$%()+;&#x3C;>=?[]{}^.,</code></td><td>Custom set of characters to draw from when generating the special character portion</td></tr></tbody></table>

Each character-class parameter sets the minimum count if positive, an exact count if zero or negative, or is unconstrained if `None` (the default). When all four groups are `None`, the remaining positions are filled from all four groups uniformly at random. Otherwise the remaining positions are filled from the groups that are `None` or positive. If all four counts are zero or negative and the sum of their absolute values is less than `length`, the SDK treats the negative counts as minimum counts and logs a warning. If all four counts are zero, the remaining positions are filled from all four groups.

### Download a File

{% tabs %}
{% tab title="Save File" %}

```python
file.save_file(path, create_folders=False, verify_ssl_certs=True, proxy_url=None)
```

{% endtab %}

{% tab title="Example" %}

```python
# Save all files to a /tmp folder (create folder if does not exist)
for file in secret.files:
    print("file: %s" % file)
    file.save_file("/tmp/" + file.name, True)
```

{% endtab %}
{% endtabs %}

<table data-header-hidden><thead><tr><th width="203">Parameter</th><th width="150">Type</th><th width="150">Required</th><th width="150">Default</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Default</td><td>Description</td></tr><tr><td><code>path</code></td><td><code>str</code></td><td>Yes</td><td></td><td>Path to save file to</td></tr><tr><td><code>create_folders</code></td><td><code>bool</code></td><td>No</td><td>False</td><td>Create folders in the path if not present</td></tr><tr><td><code>verify_ssl_certs</code></td><td><code>bool</code></td><td>No</td><td>True</td><td>Verify SSL certificates for the download</td></tr><tr><td><code>proxy_url</code></td><td><code>str</code></td><td>No</td><td>None</td><td>Proxy URL for the download</td></tr></tbody></table>

`save_file()` does not use the `proxy_url` and `verify_ssl_certs` of the `SecretsManager` client. Pass them to `save_file()` when you need them.

### Upload a File

{% tabs %}
{% tab title="Upload File" %}
Upload File:

```python
upload_file(owner_record, file: KeeperFileUpload)
```

Creating the Keeper File Upload Object:

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

{% endtab %}

{% tab title="Example" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
from keeper_secrets_manager_core.core import KeeperFileUpload

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

# Get an individual secret by UID to attach the file to
UID_FILTER = 'XXX'
owner_record= secrets_manager.get_secrets([UID_FILTER])[0]

# Prepare file data for upload
my_file = KeeperFileUpload.from_file("./myFile.json", "myfile.json", "My File") 

# Upload file attached to the owner record and get the file UID
file_uid = secrets_manager.upload_file(owner_record, file = my_file)
```

{% endtab %}
{% endtabs %}

Upload File

<table><thead><tr><th width="184.14763231197773">Parameter</th><th width="173">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>owner_record</code></td><td><code>Record</code></td><td>Yes</td><td>The record to attach the uploaded file to</td></tr><tr><td><code>file</code></td><td>KeeperFileUpload</td><td>Yes</td><td>The File to upload</td></tr></tbody></table>

Keeper File Upload From File

<table><thead><tr><th width="169">Parameter</th><th width="150">Type</th><th width="150">Required</th><th width="150">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>path</code></td><td><code>str</code></td><td>Yes</td><td></td><td>Path to the file to upload</td></tr><tr><td><code>file_name</code></td><td><code>str</code></td><td>No</td><td>None</td><td>What the name of the file will be in Keeper once uploaded</td></tr><tr><td><code>file_title</code></td><td><code>str</code></td><td>No</td><td>None</td><td>What the title of the file will be in Keeper once uploaded</td></tr><tr><td><code>mime_type</code></td><td><code>str</code></td><td>No</td><td>None</td><td>The type of data in the file. If none is provided, the SDK guesses the type from the extension of <code>path</code> and uses 'application/octet-stream' when it cannot guess</td></tr></tbody></table>

#### Returns

Type: `str`

The file UID of the attached file

### Remove File Attachments

{% tabs %}
{% tab title="Remove Files" %}

```python
secrets_manager.save(record, links_to_remove=['<FILE_UID>'])
```

{% endtab %}

{% tab title="Example Usage" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

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

# Get a secret by UID
secret = secrets_manager.get_secrets(['<RECORD_UID>'])[0]

# Get file UIDs from the record
file_uids = [file.f.get('fileUid') for file in secret.files]
print(f"Files to remove: {file_uids}")

# Remove specific files by UID
secrets_manager.save(secret, links_to_remove=file_uids)
```

{% endtab %}

{% tab title="Remove Multiple Files" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

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

# Get a secret by UID
secret = secrets_manager.get_secrets(['<RECORD_UID>'])[0]

# Remove multiple specific files
files_to_remove = ['<FILE_UID_1>', '<FILE_UID_2>']
secrets_manager.save(secret, links_to_remove=files_to_remove)

# Or, instead of the call above, remove all files.
# Reload the record, because the save above changed it.
secret = secrets_manager.get_secrets(['<RECORD_UID>'])[0]
all_file_uids = [file.f.get('fileUid') for file in secret.files]
secrets_manager.save(secret, links_to_remove=all_file_uids)
```

{% endtab %}
{% endtabs %}

<table><thead><tr><th width="200">Parameter</th><th width="150">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>record</code></td><td><code>Record</code></td><td>Yes</td><td>The record to update</td></tr><tr><td><code>links_to_remove</code></td><td><code>str</code> or <code>List[str]</code></td><td>No</td><td>File UID(s) to remove from the record</td></tr></tbody></table>

{% hint style="warning" %}
After removing files, make sure to reload the record with `get_secrets()` if you plan to make additional updates, as the record revision will have changed.
{% endhint %}

### 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
  * A classic shared folder does not need a record
* Created records and record fields must be formatted correctly
  * See the [documentation](https://docs.keeper.io/enterprise-guide/record-types.md) for expected field formats for each record type
* An NSF folder that is shared directly to the application also works as the target. `create_secret()` and `create_secret_with_options()` find the folder only when it holds at least one record. When the target is an NSF folder, `create_secret()` and `create_secret_with_options()` send the NSF payload. No extra parameter is needed.
* TOTP fields accept only URL generated outside of the KSM SDK
* After record creation, you can upload file attachments using [upload\_file](#upload-a-file)

{% tabs %}
{% tab title="Create a Record" %}

```python
from keeper_secrets_manager_core.dto.dtos import RecordCreate,RecordField

record = RecordCreate(record_type='login', title='test_KSM')
record.fields = [ 
    RecordField(field_type='login',value='test_login'),
    RecordField(field_type='password',value='test_pwd') 
]

secrets_manager.create_secret(folder_uid, record)
```

<table><thead><tr><th width="162">Parameter</th><th width="255">Type</th><th>Required</th><th>Default</th></tr></thead><tbody><tr><td><code>folder_uid</code></td><td><code>str</code></td><td>Yes</td><td></td></tr><tr><td><code>record_data</code></td><td><code>RecordCreate</code></td><td>Yes</td><td></td></tr></tbody></table>
{% endtab %}

{% tab title="Create Record in Sub-folder" %}

```python
from keeper_secrets_manager_core.dto.dtos import RecordCreate,RecordField

record = RecordCreate(record_type='login', title='test_KSM')
record.fields = [ 
    RecordField(field_type='login',value='test_login'),
    RecordField(field_type='password',value='test_pwd') 
]

from keeper_secrets_manager_core.dto.payload import CreateOptions

create_options = CreateOptions(
    folder_uid='shared_folder_uid',
    subfolder_uid='user_folder_uid'
)

secrets_manager.create_secret_with_options(create_options, record)
```

<table><thead><tr><th width="195">Parameter</th><th width="168">Type</th><th width="127">Required</th><th>Default</th></tr></thead><tbody><tr><td><code>create_options</code></td><td><code>CreateOptions</code></td><td>Yes</td><td></td></tr><tr><td><code>record_data</code></td><td><code>RecordCreate</code></td><td>Yes</td><td></td></tr><tr><td><code>folders</code></td><td><code>List[KeeperFolder]</code></td><td>No</td><td><code>[]</code></td></tr></tbody></table>
{% endtab %}

{% tab title="Login Record Example" %}
This example creates a login type record with a login value and a generated password.

{% hint style="info" %}
Replace '`[FOLDER UID]`' in the example with the UID of a shared folder that your Secrets Manager has access to.
{% endhint %}

```python
# create a new login record
new_login_record = RecordCreate('login', "Sample KSM Record: Python")
# fill in login and password fields
new_login_record.fields = [
    RecordField(field_type='login', value='username@email.com'),
    RecordField(field_type='password', value=generate_password())
]
# fill in notes
new_login_record.notes = 'This is a Python record creation example'
# create the new record and get its UID
record_uid = secrets_manager.create_secret('[FOLDER UID]', new_login_record)
```

{% endtab %}

{% tab title="Custom Type Example" %}
This example creates a record with a custom record type.

{% hint style="info" %}
Replace '`[FOLDER UID]`' in the example with the UID of a shared folder that your Secrets Manager has access to.
{% endhint %}

<pre class="language-python"><code class="lang-python">from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
from keeper_secrets_manager_core.dto.dtos import RecordCreate, RecordField
from keeper_secrets_manager_core.utils import generate_password

# setup secrets manger
secrets_manager = SecretsManager(
    # token='US:XXXXXX',
    config=FileKeyValueStorage('ksm-config.json')
)

custom_login = RecordCreate(record_type='Custom Login', title='Sample Custom Type KSM Record: Python')
<strong>custom_login.fields = [
</strong>    RecordField(field_type='host', 
                value={'hostName': '127.0.0.1', 'port': '8080'}, 
                label="My Custom Host lbl", 
                required=True),
    RecordField(field_type='login', 
                value='login@email.com', 
                label='My Custom Login lbl', 
                required=True),
    RecordField(field_type='password', 
                value=generate_password(), 
                label='My Custom Password lbl', 
                required=True),
    RecordField(field_type='url', 
                value='http://localhost:8080/login', 
                label='My Login Page', 
                required=True),
    RecordField(field_type='securityQuestion', 
                value={
                    'question': 'What is one plus one (write just a number)', 
                    'answer': '2'
                }, 
                label='My Question 1', 
                required=True),
    RecordField(field_type='phone', 
                value={
                  'region': 'US', 
                  'number': '510-444-3333', 
                  'ext': '2345', 
                  'type': 'Mobile'}, 
                label='My Phone Number'),
    RecordField(field_type='date', 
                value=1641934793000, 
                label='My Date Lbl', 
                required=True),
    RecordField(field_type='name', 
                value={
                  'first': 'John', 
                  'middle': 'Patrick', 
                  'last': 'Smith'}, 
                label="My Custom Name lbl", 
                required=True),
    RecordField(field_type='oneTimeCode', 
                value='otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&#x26;issuer=Example', 
                label='My TOTP', 
                required=True)
]

custom_login.custom = [
    RecordField(field_type='phone', 
                value={'region': 'US', 'number': '510-222-5555', 'ext': '99887', 'type': 'Mobile'}, 
                label='My Custom Phone Lbl 1'),
    RecordField(field_type='phone', 
                value={'region': 'US', 'number': '510-111-3333', 'ext': '45674', 'type': 'Mobile'}, 
                label='My Custom Phone Lbl 2'),
]

custom_login.notes = "\tThis custom type record was created\n\tvia Python SDK copied from https://docs.keeper.io/secrets-manager/secrets-manager/developer-sdk-library/python-sdk"

record_uid = secrets_manager.create_secret('[FOLDER UID]', custom_login)
</code></pre>

{% endtab %}
{% endtabs %}

#### Returns

Type: `str`

The record UID of the new record

### Delete a Secret

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

{% tabs %}
{% tab title="Delete Secret" %}

```python
secrets_manager.delete_secret(record_uids)
```

<table><thead><tr><th>Parameter</th><th width="187.875">Type</th><th width="107.32421875">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>record_uids</code></td><td><code>str</code> or <code>List[str]</code></td><td>Yes</td><td>UID or list of UIDs of records to delete</td></tr></tbody></table>
{% endtab %}

{% tab title="Example" %}

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

# setup secrets manger
secrets_manager = SecretsManager(
    token='<One Time Access Token>',
    config=FileKeyValueStorage('ksm-config.json')
)

# delete a specific secret by record UID
secrets_manager.delete_secret('EG6KdJaaLG7esRZbMnfbFA')
```

{% endtab %}
{% endtabs %}

#### Returns

Type: `List[dict]`

One result for each record and folder pair: `recordUid`, `folderUid`, `responseCode`, and `errorMessage`. A record that is in more than one folder has more than one result. The list is empty when the server returns no results.

The server can refuse a record without failing the request, for example an NSF record that an enforcement keeps in its folder. The SDK does not raise an error for that refusal. Check each `responseCode`. The SDK logs each result that is not `ok`. Other refusals fail the whole request with a `KeeperError`.

### 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 a file. The file holds the encrypted response and the key that decrypts it, so protect the file like a secret. On Linux and macOS, the SDK creates it with mode 0600. On Windows, it gives the file an owner-only ACL.

**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 (it always prefers the network and uses the cache only when the request raises an exception, for example when the network is down. An HTTP error response from the server is returned as is). 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)*

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

{% hint style="danger" %}
The default `KSMCache` stores only the most recent response. If you call `get_secrets(['<uid>'])` and then call `get_secrets()` without arguments while offline, the second call returns only the one cached record, not your full vault.
{% endhint %}

{% hint style="warning" %}
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.)*
{% endhint %}

On Linux and macOS, `KSMCache` writes the cache file with mode 0600 (owner read and write only) and sets that mode on an existing cache file at the next write. On Windows, it gives the cache file an owner-only ACL (the current user and Administrators) before it writes the data. Each Windows account must use its own cache file, for example its own `KSM_CACHE_DIR`. If the SDK cannot set the ACL, it removes the cache file and does not write the data. Set `KSM_CONFIG_SKIP_MODE` to `TRUE` to skip the ACL. A new cache file then gets the ACL of its folder. On Linux and macOS, this variable does not change the mode of the cache file. The default path is `ksm_cache.bin` in the directory set by the `KSM_CACHE_DIR` environment variable, or in the current directory when the variable is not set. To use another path, assign it to `KSMCache.kms_cache_file_name`. An explicit assignment takes precedence over `KSM_CACHE_DIR`.

If the SDK cannot write the cache file after a successful request, `KSMCache.caching_post_function` returns the live response and logs a warning when SDK logging is enabled. On Windows, this also occurs when the SDK cannot set the ACL. The offline fallback then has no cached data until a later write succeeds.

#### Creating your own caching function

For start create caching function with following arguments and call `post_function`

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.core import KSMCache, KSMHttpResponse

def caching_post_function(
        url, transmission_key, encrypted_payload_and_signature, verify_ssl_certs=True, proxy_url=None
):
    ksm_rs = SecretsManager.post_function(
        url, transmission_key, encrypted_payload_and_signature, verify_ssl_certs, proxy_url
    )
    # Your custom caching logic here ...

    # Make sure to always return a KSMHttpResponse object
    return ksm_rs
```

Then you can implement any custom logic of caching using KSMCache.\
Full basic example:

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.core import KSMCache, KSMHttpResponse
from keeper_secrets_manager_core.storage import FileKeyValueStorage
import logging
from http import HTTPStatus

def caching_post_function(
        url, transmission_key, encrypted_payload_and_signature, verify_ssl_certs=True, proxy_url=None
):
    try:
        ksm_rs = SecretsManager.post_function(
            url, transmission_key, encrypted_payload_and_signature, verify_ssl_certs, proxy_url
        )
    except Exception:
        # The vault cannot be reached. KSMCache can be empty, then get_cached_data() raises an error
        cached_data = KSMCache.get_cached_data()
        transmission_key.key = cached_data[:32]
        return KSMHttpResponse(HTTPStatus.OK, cached_data[32:], None)

    if ksm_rs.status_code == 200:
        try:
            KSMCache.save_cache(transmission_key.key + ksm_rs.data)
        except Exception as err:
            # Keep the live response when the cache write fails
            logging.getLogger("ksm").warning("Cannot write the KSM cache file: %s", type(err).__name__)
    return ksm_rs


secrets_manager = SecretsManager(
    config=FileKeyValueStorage('ksm-config.json'),
    verify_ssl_certs=False,
    custom_post_function=caching_post_function
)
```

### Folders

The SDK works with both kinds of folders in your vault: classic shared folders and Nested Shared Folders (NSF). NSF is the newer folder model; some earlier releases and the SDK's `is_drive` attribute call it Keeper Drive. See [Nested Shared Folders](https://docs.keeper.io/enterprise-guide/sharing/nested-share-subfolders) for the model and availability.

With classic shared folders, the SDK reads folders, creates, renames, and deletes subfolders, and works with their records. With NSF folders, the SDK reads the folders and creates records in them. You create, rename, and delete NSF folders, and classic shared folders themselves, in the vault. For NSF folders you can also use the `nsf-mkdir`, `nsf-rndir`, and `nsf-rmdir` commands in [Keeper Commander](https://docs.keeper.io/keeperpam/commander-cli/command-reference/keeper-drive-commands.md).

| Task            | Classic shared folders                               | NSF folders                                                                      |
| --------------- | ---------------------------------------------------- | -------------------------------------------------------------------------------- |
| Read folders    | `get_folders()`                                      | `get_folders(include_nsf=True)`                                                  |
| Read records    | `get_secrets()`                                      | `get_secrets()`                                                                  |
| Create a record | `create_secret()` or `create_secret_with_options()`  | The same methods. The SDK sends the NSF payload when the target is an NSF folder |
| Create a folder | `create_folder()` under a shared folder or subfolder | In the vault, or `nsf-mkdir` in Commander                                        |
| Rename a folder | `update_folder()` for a subfolder of a shared folder | In the vault, or `nsf-rndir` in Commander                                        |
| Delete a folder | `delete_folder()` for a subfolder of a shared folder | In the vault, or `nsf-rmdir` in Commander                                        |

### Read Folders

Downloads the full folder hierarchy. Nested folders of any depth are decrypted.

```python
get_folders(*, include_nsf=False)
```

| Parameter     | Type   | Required | Default | Description                                                                                                    |
| ------------- | ------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------- |
| `include_nsf` | `bool` | No       | `False` | Also return NSF folders that are shared directly to the application and hold at least one record. Keyword only |

With `include_nsf=True`, the SDK also sends a `get_secret` request with no filter and adds each NSF folder that the response lists. That request downloads every record that the application can access, and it fails when the application has more records than the server limit. An NSF folder in the result has no parent and has `is_drive=True`. Without `include_nsf`, the result has no NSF folders.

If the SDK cannot decrypt a folder, or the folder data has a parent cycle, the SDK skips that folder, logs an error, and returns the other folders.

**Response**

Type: `List[KeeperFolder]`

Each `KeeperFolder` has `folder_uid`, `parent_uid`, `name`, `folder_key`, `use_gcm`, `is_drive`, and `data` (the decrypted folder JSON, or `None` when the SDK has none, for example for an NSF folder).

**Example Usage**

```python
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 the sub-folder UID can be empty (`""` or `None`). Pass both arguments: `CreateOptions(folder_uid, subfolder_uid)` raises `TypeError` when one is missing. If the sub-folder UID is empty, the 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.

<details>

<summary>If the parent is an NSF folder</summary>

The SDK does not create folders in NSF folders. If `folders` marks the parent folder or the shared folder as NSF, `create_folder()` raises `KeeperError` and sends no `create_folder` request. Only the result of `get_folders(include_nsf=True)` marks a folder as NSF. If `folders` is empty or not passed, the SDK reads the folders with `get_folders()`. That list marks no folder as NSF, so `create_folder()` does not give the NSF refusal. If the shared folder is not in the list, `create_folder()` raises `KeeperError`.

</details>

```python
create_folder(create_options: CreateOptions, folder_name: str, folders=None)
```

<table><thead><tr><th width="200.85161529417937">Parameter</th><th width="225.99431983802478">Type</th><th width="102">Required</th><th width="86">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>create_options</code></td><td><code>CreateOptions</code></td><td>Yes</td><td></td><td>The parent and sub-folder UIDs</td></tr><tr><td><code>folder_name</code></td><td><code>str</code></td><td>Yes</td><td></td><td>The Folder name</td></tr><tr><td><code>folders</code></td><td><code>List[KeeperFolder]</code></td><td>No</td><td><code>None</code></td><td>List of folders to use in the search for parent and sub-folder from CreateOptions</td></tr></tbody></table>

**Example Usage**

```python
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

Renames a subfolder of a shared folder. The color and the other fields of the folder data stay unchanged.

If you pass `folders`, pass the result of `get_folders()`. An old list can overwrite a later metadata change. If the folder in `folders` has no complete data, the SDK sends one more `get_folders` request. If that request also gives no data, `update_folder()` raises `KeeperError` and sends no update.

<details>

<summary>If the folder is a shared folder or an NSF folder</summary>

`update_folder()` raises `KeeperError` and sends no `update_folder` request. For a classic shared folder, the error has the `result_code` `access_denied`. Rename NSF folders in the vault or with `nsf-rndir`.

</details>

```python
update_folder(folder_uid: str, folder_name: str, folders=None)
```

<table><thead><tr><th width="194.85161529417937">Parameter</th><th width="218.99431983802478">Type</th><th width="104">Required</th><th width="92">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>folder_uid</code></td><td><code>str</code></td><td>Yes</td><td></td><td>The folder UID</td></tr><tr><td><code>folder_name</code></td><td><code>str</code></td><td>Yes</td><td></td><td>The new folder name</td></tr><tr><td><code>folders</code></td><td><code>List[KeeperFolder]</code></td><td>No</td><td><code>None</code></td><td>List of folders to use in the search for parent folder</td></tr></tbody></table>

**Example Usage**

```python
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.

{% hint style="info" %}
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.
{% endhint %}

* A call with at least one UID first sends a `get_folders` request. Pass all UIDs in one call to send that request once.
* A UID that is missing from the vault or not shared to the KSM Application does not raise an error. Its item has the `responseCode` `doesnt_exist`. Do not treat that result as proof that the folder is gone.
* Pass one UID string or an iterable of UID strings, such as a list.

<details>

<summary>If a UID is a shared folder or an NSF folder</summary>

`delete_folder()` deletes only subfolders of shared folders. For any other UID, the SDK sends nothing and returns an item for it. A classic shared folder gets the `responseCode` `access_denied`. An NSF folder usually gets `doesnt_exist`, because `get_folders()` does not list it. It gets `access_denied` when the list does include it. Delete NSF folders in the vault or with `nsf-rmdir`.

</details>

```python
delete_folder(folder_uids, force_deletion=False)
```

<table><thead><tr><th width="209.85161529417937">Parameter</th><th width="165.99431983802478">Type</th><th width="108">Required</th><th width="101">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>folder_uids</code></td><td><code>str</code> or iterable of <code>str</code></td><td>Yes</td><td></td><td>The folder UID list</td></tr><tr><td><code>force_deletion</code></td><td><code>bool</code></td><td>No</td><td><code>False</code></td><td>Force deletion of non-empty folders</td></tr></tbody></table>

**Example Usage**

```python
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)
```

**Response**

Type: `List[dict]`

The results for the folder UIDs: `folderUid`, `errorMessage`, and `responseCode`. A UID that the SDK does not send gets a result with the `responseCode` `access_denied` or `doesnt_exist`. The list is empty when the server returns no results and the SDK refused no UID. A refusal does not raise an error. Check each `responseCode`. The SDK logs each result that is not `ok`. Other refusals fail the whole request with a `KeeperError`.

## Error Handling

`KeeperError` is the main SDK error class. Other errors can reach your code: `ValueError` for invalid arguments, `KeeperError` from some calls with invalid arguments, such as `delete_folder()`, `requests` exceptions such as `requests.exceptions.HTTPError`, and `FileNotFoundError`, `PermissionError`, or `Exception` from the file storage. The SDK does not raise `KeeperAccessDenied`. The class derives from `Exception`, not from `KeeperError`. When the server rejects a request with an error code, the SDK raises `KeeperError` with these attributes:

| Attribute         | Description                                        |
| ----------------- | -------------------------------------------------- |
| `result_code`     | The error code that the server returned            |
| `status_code`     | The HTTP status of the response                    |
| `additional_info` | The `additional_info` text of the response, if any |

The attributes are `None` for an error that the SDK raises itself, except that `update_folder()` sets `result_code` to `access_denied` when the folder list shows no parent, or conflicting parents, for the folder, as for a shared folder.

A malformed proxy URL usually raises `KeeperInvalidURLError`. It is both a `KeeperError` and a `requests.exceptions.InvalidURL`, and its message never contains the URL. A proxy URL with no host raises `requests.exceptions.InvalidProxyURL` instead, which the SDK does not change.

## Proxy support

### Environment variable

Keeper Secrets Manager SDK uses the [requests](https://pypi.org/project/requests/) library to support the HTTPS\_PROXY environment variable by [default](https://requests.readthedocs.io/en/latest/user/advanced/#proxies)

```
HTTPS_PROXY=https://yourproxy:8888 python main.py
```

Every request including Keeper Secrets Manager requests will go through declared proxy

{% hint style="info" %}
Using environment variables for proxy settings is preferred because it keeps configuration out of code, ensures consistency across tools, and simplifies deployment.
{% endhint %}

### SecretsManager parameter

Optionally, you can pass your proxy url to `SecretsManager` if you want proxy to be used only in SDK:

```python
secrets_manager = SecretsManager(
    config=FileKeyValueStorage('ksm-config.json'),
    proxy_url="https://yourproxy:8888"
)
```

{% hint style="info" %}
If your proxy has authentication, just pass your username and password in proxy url
{% endhint %}

```
https://username:pass@yourproxy:8888
```

A malformed proxy URL usually raises `KeeperInvalidURLError`, and its message does not contain the URL, so the password does not reach logs. A proxy URL with no host raises `requests.exceptions.InvalidProxyURL`, which the SDK does not change. Existing `except requests.exceptions.InvalidURL` handlers still match both.

## Advanced Configuration

### Custom Server Public Key

For isolated or private deployments where the SDK cannot ship with the server public key, supply an EC P-256 public key via either of two paths. Precedence is programmatic > pre-existing config.

**Programmatic** — pass `server_public_key` and `server_public_key_id` to `SecretsManager()`:

```python
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage

secrets_manager = SecretsManager(
    token='REGION:ONE_TIME_TOKEN',
    server_public_key='<url-safe-base64-EC-P256-public-key>',
    server_public_key_id='<key-id>',
    config=FileKeyValueStorage('ksm-config.json'),
)
```

**Config file** — add `serverPublicKey` and `serverPublicKeyId` to an existing bound `ksm-config.json` before the first call. These two fields supplement the bound configuration, they do not replace it:

```json
{
  "serverPublicKey": "<url-safe-base64-EC-P256-public-key>",
  "serverPublicKeyId": "<key-id>"
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.keeper.io/keeperpam/secrets-manager/developer-sdk-library/python-sdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
