API Documentation
REST API Connector
The Cumulocity Python API (c8y_api
module) provides a convenience wrapper
around the standard Cumulocity REST API (see also the
OpenAPI documentation).
The CumulocityRestApi
class provides the fundamental wrapping around
authentication and basic get
, post
, put
, delete
commands.
The CumulocityApi
class is your entrypoint into higher level functions,
grouped by contexts like inventory
, users
, and measurements
.
Each of these contexts is documented in detail within the
Main API Classes section.
The CumulocityDeviceRegistry
class provides an additional entry point
for devices, wrapping the entire bootstrap mechanism. See also the
Device integration documentation.
- class c8y_api.CumulocityRestApi(base_url: str, tenant_id: str, username: str = None, password: str = None, tfa_token: str = None, auth: AuthBase = None, application_key: str = None)
Cumulocity base REST API.
Provides REST access to a Cumulocity instance.
- __init__(base_url: str, tenant_id: str, username: str = None, password: str = None, tfa_token: str = None, auth: AuthBase = None, application_key: str = None)
Build a CumulocityRestApi instance.
One of auth or username/password must be provided. The TFA token parameter is only sensible for basic authentication.
- Parameters:
base_url (str) – Cumulocity base URL, e.g. https://cumulocity.com
tenant_id (str) – The ID of the tenant to connect to
username (str) – Username
password (str) – User password
tfa_token (str) – Currently valid two-factor authorization token
auth (AuthBase) – Authentication details
application_key (str) – Application ID to include in requests (for billing/metering purposes).
- prepare_request(method: str, resource: str, json: dict = None, additional_headers: Dict[str, str] = None) PreparedRequest
Prepare an HTTP request.
- Parameters:
method (str) – One of ‘GET’, ‘POST’, ‘PUT’, ‘DELETE’
resource (str) – Path to the HTTP resource
json (dict) – JSON body (nested dict) to send with the request
additional_headers (dict) – Additional non-standard headers to include in the request
- Returns:
A PreparedRequest instance
- get(resource: str, params: dict = None, accept: str = None, ordered: bool = False) dict
Generic HTTP GET wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
params (dict) – Additional request parameters
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
ordered (bool) – Whether the result JSON needs to be ordered (default is False)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 is accepted).
- get_file(resource: str, params: dict = None) bytes
Generic HTTP GET wrapper.
Used for downloading binary data, i.e. reading binaries from Cumulocity.
- Parameters:
resource (str) – Resource path
params (dict) – Additional request parameters
- Returns:
The binary data as bytes.
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 is accepted).
- post(resource: str, json: dict, accept: str = None, content_type: str = None) dict
Generic HTTP POST wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
json (dict) – JSON body (nested dict)
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str|None) – Custom Content-Type header to use (default is application/json)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 and 201 are accepted).
- post_file(resource: str, file: str | BinaryIO, object: dict = None, accept: str = None, content_type: str = None)
Generic HTTP POST wrapper.
Used for posting binary data, i.e. creating binary objects in Cumulocity.
- Parameters:
resource (str) – Resource path
file (str|BinaryIO) – File-like object or a file path
object (dict) – File metadata, stored within Cumulocity
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
The JSON response (nested dict)
- Raises:
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 201 is accepted).
- put(resource: str, json: dict, params: dict = None, accept: str = None, content_type: str = None) dict
Generic HTTP PUT wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
json (dict) – JSON body (nested dict)
params (dict) – Additional request parameters
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str|None) – Custom Content-Type header to use (default is application/json)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 is accepted).
- put_file(resource: str, file: str | BinaryIO, accept: str = None, content_type: str = None)
Generic HTTP PUT wrapper.
Used for put’ing binary data, i.e. updating binaries in Cumulocity.
- Parameters:
resource (str) – Resource path
file (str|BinaryIO) – File-like object or a file path
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 201 is accepted).
- delete(resource: str, json: dict = None, params: dict = None)
Generic HTTP POST wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
json (dict) – JSON body (nested dict)
params (dict) – Additional request parameters
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 and 204 are accepted).
- class c8y_api.CumulocityApi(base_url: str, tenant_id: str, username: str = None, password: str = None, tfa_token: str = None, auth: AuthBase = None, application_key: str = None)
Main Cumulocity API.
Provides usage centric access to a Cumulocity instance.
- __init__(base_url: str, tenant_id: str, username: str = None, password: str = None, tfa_token: str = None, auth: AuthBase = None, application_key: str = None)
Build a CumulocityRestApi instance.
One of auth or username/password must be provided. The TFA token parameter is only sensible for basic authentication.
- Parameters:
base_url (str) – Cumulocity base URL, e.g. https://cumulocity.com
tenant_id (str) – The ID of the tenant to connect to
username (str) – Username
password (str) – User password
tfa_token (str) – Currently valid two-factor authorization token
auth (AuthBase) – Authentication details
application_key (str) – Application ID to include in requests (for billing/metering purposes).
- property measurements: Measurements
Provide access to the Measurements API.
- property group_inventory: DeviceGroupInventory
Provide access to the Device Group Inventory API.
- property devicegroups: DeviceGroupInventory
Provide access to the Device Group Inventory API.
- property binaries
Provide access to the Binary API.
- property device_inventory: DeviceInventory
Provide access to the Device Inventory API.
- property global_roles: GlobalRoles
Provide access to the Global Roles API.
- property inventory_roles: InventoryRoles
Provide access to the Inventory Roles API.
- property applications: Applications
Provide access to the Applications API.
- property operations: Operations
Provide access to the Operation API.
- property bulk_operations: BulkOperations
Provide access to the BulkOperation API.
- property tenant_options: TenantOptions
Provide access to the Tenant Options API.
- property notification2_subscriptions: Subscriptions
Provide access to the Notification 2.0 Subscriptions API.
- property audit_records: AuditRecords
Provide access to the Audit API.
- class c8y_api.CumulocityDeviceRegistry(base_url, tenant_id, username, password)
Special CumulocityRESTAPI instance handling device registration.
https://cumulocity.com/guides/users-guide/device-management/#connecting-devices
- class Credentials(tenant_id: str, username: str, password: str)
Bundles authentication information.
- __init__(tenant_id: str, username: str, password: str) None
- __init__(base_url, tenant_id, username, password)
Build a CumulocityRestApi instance.
One of auth or username/password must be provided. The TFA token parameter is only sensible for basic authentication.
- Parameters:
base_url (str) – Cumulocity base URL, e.g. https://cumulocity.com
tenant_id (str) – The ID of the tenant to connect to
username (str) – Username
password (str) – User password
tfa_token (str) – Currently valid two-factor authorization token
auth (AuthBase) – Authentication details
application_key (str) – Application ID to include in requests (for billing/metering purposes).
- classmethod default()
Return the default (bootstrap) instance.
- await_credentials(device_id: str, timeout: str = '60m', pause: str = '1s') Credentials
Wait for device credentials.
The device must have requested credentials already. This function awaits the request confirmation and returns the device-specific credentials generated by the Cumulocity platform.
- Parameters:
device_id (str) – The external ID of the device (i.e. IMEI - NOT the Cumulocity ID)
timeout (str) – How long to wait for the request to be confirmed. This is a formatted string in the form <int><unit>, accepted units are ‘h’ (hours), ‘m’ (minutes), ‘s’ (seconds) and ‘ms’ (milliseconds). A reasonable value for this depends on application.
pause (str) – How long to pause between request confirmation checks This is a formatted string, see timeout parameter.
- Returns:
Credentials object holding the device credentials
- Raises:
TimeoutError – if the request was not confirmed in time.
See also: https://cumulocity.com/guides/users-guide/device-management/#connecting-devices
- await_connection(device_id: str, timeout: str = '60m', pause: str = '1s') CumulocityApi
Wait for device credentials and build corresponding API connection.
The device must have requested credentials already. This function awaits the request confirmation and returns a CumulocityAPI instance for the device-specific credentials.
- Parameters:
device_id (str) – The external ID of the device (i.e. IMEI - NOT the Cumulocity ID)
timeout (str) – How long to wait for the request to be confirmed. This is a formatted string in the form <int><unit>, accepted units are ‘h’ (hours), ‘m’ (minutes), ‘s’ (seconds) and ‘ms’ (milliseconds). A reasonable value for this depends on application.
pause (str) – How long to pause between request confirmation checks This is a formatted string, see timeout parameter.
- Returns:
Device-specific CumulocityAPI instance
- Raises:
TimeoutError – if the request was not confirmed in time.
See also: https://cumulocity.com/guides/users-guide/device-management/#connecting-devices
Application Helpers
The Cumulocity Python API (c8y_api
module) is designed to be
particularly useful for developing Cumulocity microservices. For this,
the module provides two helper classes that take care of microservice
specific authentication.
The SimpleCumulocityApp
class should be used for single tenant
microservices. It automatically reads the microservice’s environment
to determines the microservice access credentials.
The MultiTenantCumulocityApp
class should be used for multi-tenant
microservices which need to handle requests for arbitrary Cumulocity
tenants. It reads the microservice’s environment to determine the
necessary bootstrap credentials and provides additional functions to
dynamically obtain CumulocityApi
instances for specific tenants.
- class c8y_api.app.SimpleCumulocityApp(application_key: str = None, cache_size: int = 100, cache_ttl: int = 3600)
Application-like Cumulocity API.
The SimpleCumulocityApp class is intended to be used as base within a single-tenant microservice hosted on Cumulocity. It evaluates the environment to the resolve the authentication information automatically.
Note: This class should be used in Cumulocity microservices using the PER_TENANT authentication mode only. It will not function in environments using the MULTITENANT mode.
The SimpleCumulocityApp class is an enhanced version of the standard CumulocityApi class. All Cumulocity functions can be used directly. Additionally, it can be used to provide CumulocityApi instances for specific named users via the get_user_instance function.
- __init__(application_key: str = None, cache_size: int = 100, cache_ttl: int = 3600)
Create a new tenant specific instance.
- Parameters:
application_key (str|None) – An application key to include in all requests for tracking purposes.
cache_size (int|None) – The maximum number of cached user instances (if user instances are created at all).
cache_ttl (int|None) – An maximum cache time for user instances (if user instances are created at all).
- Returns:
A new CumulocityApp instance
- property applications: Applications
Provide access to the Applications API.
- property audit_records: AuditRecords
Provide access to the Audit API.
- property binaries
Provide access to the Binary API.
- property bulk_operations: BulkOperations
Provide access to the BulkOperation API.
- clear_user_cache(username: str = None)
Manually clean the user sessions cache.
- Parameters:
username (str) – Name of a specific user to remove or None to clean the cache completely
- delete(resource: str, json: dict = None, params: dict = None)
Generic HTTP POST wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
json (dict) – JSON body (nested dict)
params (dict) – Additional request parameters
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 and 204 are accepted).
- property device_inventory: DeviceInventory
Provide access to the Device Inventory API.
- property devicegroups: DeviceGroupInventory
Provide access to the Device Group Inventory API.
- get(resource: str, params: dict = None, accept: str = None, ordered: bool = False) dict
Generic HTTP GET wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
params (dict) – Additional request parameters
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
ordered (bool) – Whether the result JSON needs to be ordered (default is False)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 is accepted).
- get_file(resource: str, params: dict = None) bytes
Generic HTTP GET wrapper.
Used for downloading binary data, i.e. reading binaries from Cumulocity.
- Parameters:
resource (str) – Resource path
params (dict) – Additional request parameters
- Returns:
The binary data as bytes.
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 is accepted).
- get_user_instance(headers: dict = None) CumulocityApi
Return a user-specific CumulocityApi instance.
The instance will have user access, based on the Authorization header provided in the headers dict. The instance will be built on demand, previously created instances are cached.
- Parameters:
headers (dict) – A dictionary of HTTP header entries. The user access is based on the Authorization header within.
- Returns:
A CumulocityApi instance authorized for a named user.
- property global_roles: GlobalRoles
Provide access to the Global Roles API.
- property group_inventory: DeviceGroupInventory
Provide access to the Device Group Inventory API.
- property inventory_roles: InventoryRoles
Provide access to the Inventory Roles API.
- property measurements: Measurements
Provide access to the Measurements API.
- property notification2_subscriptions: Subscriptions
Provide access to the Notification 2.0 Subscriptions API.
- property operations: Operations
Provide access to the Operation API.
- post(resource: str, json: dict, accept: str = None, content_type: str = None) dict
Generic HTTP POST wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
json (dict) – JSON body (nested dict)
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str|None) – Custom Content-Type header to use (default is application/json)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 and 201 are accepted).
- post_file(resource: str, file: str | BinaryIO, object: dict = None, accept: str = None, content_type: str = None)
Generic HTTP POST wrapper.
Used for posting binary data, i.e. creating binary objects in Cumulocity.
- Parameters:
resource (str) – Resource path
file (str|BinaryIO) – File-like object or a file path
object (dict) – File metadata, stored within Cumulocity
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
The JSON response (nested dict)
- Raises:
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 201 is accepted).
- prepare_request(method: str, resource: str, json: dict = None, additional_headers: Dict[str, str] = None) PreparedRequest
Prepare an HTTP request.
- Parameters:
method (str) – One of ‘GET’, ‘POST’, ‘PUT’, ‘DELETE’
resource (str) – Path to the HTTP resource
json (dict) – JSON body (nested dict) to send with the request
additional_headers (dict) – Additional non-standard headers to include in the request
- Returns:
A PreparedRequest instance
- put(resource: str, json: dict, params: dict = None, accept: str = None, content_type: str = None) dict
Generic HTTP PUT wrapper, dealing with standard error returning a JSON body object.
- Parameters:
resource (str) – Resource path
json (dict) – JSON body (nested dict)
params (dict) – Additional request parameters
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str|None) – Custom Content-Type header to use (default is application/json)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 200 is accepted).
- put_file(resource: str, file: str | BinaryIO, accept: str = None, content_type: str = None)
Generic HTTP PUT wrapper.
Used for put’ing binary data, i.e. updating binaries in Cumulocity.
- Parameters:
resource (str) – Resource path
file (str|BinaryIO) – File-like object or a file path
accept (str|None) – Custom Accept header to use (default is application/json). Specify ‘’ to send no Accept header.
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
The JSON response (nested dict)
- Raises:
KeyError – if the resources is not found (404)
SyntaxError – if the request cannot be processes (5xx)
ValueError – if the response is not ok for other reasons (only 201 is accepted).
- property tenant_options: TenantOptions
Provide access to the Tenant Options API.
- class c8y_api.app.MultiTenantCumulocityApp(application_key: str = None, cache_size: int = 100, cache_ttl: int = 3600)
Multi-tenant enabled Cumulocity application wrapper.
The MultiTenantCumulocityApp class is intended to be used as base within a multi-tenant microservice hosted on Cumulocity. It evaluates the environment to the resolve the bootstrap authentication information automatically.
Note: This class is intended to be used in Cumulocity microservices using the MULTITENANT authentication mode. It will not function in PER_TENANT environments.
The MultiTenantCumulocityApp class serves as a factory. It provides access to tenant-specific CumulocityApi instances via the get_tenant_instance function. A special bootstrap CumulocityApi instance is available via the bootstrap_instance property.
- __init__(application_key: str = None, cache_size: int = 100, cache_ttl: int = 3600)
- get_subscribers() list[str]
Query the subscribed tenants.
- Returns:
A list of tenant ID.
- get_tenant_instance(tenant_id: str = None, headers: dict = None) CumulocityApi
Provide access to a tenant-specific instance in a multi-tenant application setup.
- Parameters:
tenant_id (str) – ID of the tenant to get access to
headers (dict) – Inbound request headers, the tenant ID is resolved from the Authorization header
- Returns:
A CumulocityApi instance authorized for a tenant user
- clear_user_cache(username: str = None)
Manually clean the user sessions cache.
- Parameters:
username (str) – Name of a specific user to remove or None to clean the cache completely
- get_user_instance(headers: dict = None) CumulocityApi
Return a user-specific CumulocityApi instance.
The instance will have user access, based on the Authorization header provided in the headers dict. The instance will be built on demand, previously created instances are cached.
- Parameters:
headers (dict) – A dictionary of HTTP header entries. The user access is based on the Authorization header within.
- Returns:
A CumulocityApi instance authorized for a named user.
Main API Classes
The Cumulocity Python API’s main API classes provide access to various contexts within the Cumulocity REST API. Use it to read existing data or modify in bulk.
See also the Object Models section for object creation and object-oriented access in general.
- class c8y_api.model.Inventory(c8y)
Provides access to the Inventory API.
This class can be used for get, search for, create, update and delete managed objects within the Cumulocity database.
See also: https://cumulocity.com/api/#tag/Inventory-API
- get(id) ManagedObject
Retrieve a specific managed object from the database.
- Parameters:
object (ID of the managed) –
- Returns:
A ManagedObject instance
- Raises:
KeyError – if the ID is not defined within the database
- get_all(expression: str = None, type: str = None, fragment: str = None, name: str = None, owner: str = None, query: str = None, text: str = None, ids: List[str | int] = None, limit: int = None, page_size: int = 1000) List[ManagedObject]
Query the database for managed objects and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
- Returns:
List of ManagedObject instances
- get_count(expression: str = None, type: str = None, fragment: str = None, name: str = None, owner: str = None, query: str = None, text: str = None, ids: List[str | int] = None) int
Calculate the number of potential results of a database query.
This function uses the same parameters as the select function.
- Returns:
Number of potential results
- select(expression: str = None, type: str = None, fragment: str = None, name: str = None, owner: str = None, query: str = None, text: str = None, ids: List[str | int] = None, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[ManagedObject]
Query the database for managed objects and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (within reason).
- Parameters:
expression (str) – Arbitrary filter expression which will be passed to Cumulocity without change; all other filters are ignored if this is provided
type (str) – Managed object type
fragment (str) – Name of a present custom/standard fragment
name (str) – Name of the managed object Note: The Cumulocity REST API does not support filtering for names directly; this is a convenience parameter which will translate all filters into a query string.
owner (str) – Username of the object owner
query (str) – Complex query to execute; all other filters are ignored if such a custom query is provided
text (str) – Text value of any object property.
ids (List[str|int]) – Specific object ID to select.
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of events which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator for ManagedObject instances
- create(*objects: ManagedObject)
Create managed objects within the database.
- Parameters:
*objects (ManagedObject) – collection of ManagedObject instances
- update(*objects: ManagedObject)
Write changes to the database.
- Parameters:
*objects (ManagedObject) – collection of ManagedObject instances
See also function ManagedObject.update which parses the result.
- apply_to(object_model: ManagedObject | dict, *object_ids)
Apply a change to multiple already existing objects.
Applies the details of a model object to a set of already existing managed objects.
Note: This will take the full details, not just the updates.
- Parameters:
object_model (ManagedObject|dict) – ManagedObject instance holding the change structure (e.g. a specific fragment) or simply a dictionary representing the diff JSON.
*object_ids (str) – a collection of ID of already existing managed objects within the database
- get_latest_availability(mo_id) Availability
Retrieve the latest availability information of a managed object.
- Parameters:
mo_id (str) – Device (managed object) ID
- Returns:
DeviceAvailability object
- get_supported_measurements(mo_id) [<class 'str'>]
Retrieve all supported measurements names of a specific managed object.
- Parameters:
mo_id (str) – Managed object ID
- Returns:
List of measurement fragment names.
- get_supported_series(mo_id) [<class 'str'>]
Retrieve all supported measurement series names of a specific managed object.
- Parameters:
mo_id (str) – Managed object ID
- Returns:
List of series names.
- class c8y_api.model.DeviceInventory(c8y)
Provides access to the Device Inventory API.
This class can be used for get, search for, create, update and delete device objects within the Cumulocity database.
See also: https://cumulocity.com/api/#tag/Inventory-API
- request(id: str)
Create a device request.
- Parameters:
id (str) – Unique ID of the device (e.g. Serial, IMEI); this is
ID. (_not_ the database) –
- accept(id: str)
Accept a device request.
- Parameters:
id (str) – Unique ID of the device (e.g. Serial, IMEI); this is
ID. (_not_ the database) –
- get(id: str) Device
Retrieve a specific device object.
- Parameters:
id (str) – ID of the device object
- Returns:
A Device instance
- Raises:
KeyError – if the ID is not defined within the database
- select(expression: str = None, type: str = None, name: str = None, owner: str = None, query: str = None, text: str = None, ids: List[str | int] = None, limit: int = None, page_size: int = 100, page_number: int = None) Generator[Device]
Query the database for devices and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (within reason).
Note: this variant doesn’t allow filtering by fragment because the c8y_IsDevice fragment is automatically filtered.
- Parameters:
expression (str) – Arbitrary filter expression which will be passed to Cumulocity without change; all other filters are ignored if this is provided
type (str) – Device type
name (str) – Name of the device Note: The Cumulocity REST API does not support filtering for names directly; this is a convenience parameter which will translate all filters into a query string.
owner (str) – Username of the object owner
query (str) – Complex query to execute; all other filters are ignored if such a custom query is provided
text (str) – Text value of any object property.
ids (List[str|int]) – Specific object ID to select.
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of events which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator for Device objects
- get_all(expression: str = None, type: str = None, name: str = None, owner: str = None, query: str = None, text: str = None, ids: List[str | int] = None, limit: int = None, page_size: int = 100, page_number: int = None) List[Device]
Query the database for devices and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
- Returns:
List of Device objects
- get_count(type: str = None, name: str = None, owner: str = None, query: str = None, text: str = None, ids: List[str | int] = None) int
Calculate the number of potential results of a database query.
This function uses the same parameters as the select function.
- Returns:
Number of potential results
- delete(*devices: Device)
Delete one or more devices and the corresponding within the database.
The objects can be specified as instances of a database object (then, the id field needs to be defined) or simply as ID (integers or strings).
Note: In contrast to the regular delete function defined in class ManagedObject, this version also removes the corresponding device user from database.
- Parameters:
*devices (Device) – Device objects within the database specified (with defined ID).
- class c8y_api.model.Binaries(c8y: CumulocityRestApi)
Provides access to the Identity API.
See also: https://cumulocity.com/api/#tag/Binaries
- read_file(id: str) bytes
Read the binary content of a specific binary.
- Parameters:
id (str) – The database ID of the binary object.
- Returns:
The binary attachment’s content as bytes
- upload(file: str | BinaryIO, name: str, type: str) Binary
Upload a file.
- Parameters:
file (str | file-like) – File to upload
name (str) – Virtual name of the file
type (str) – Mimetype of the file
- Returns:
A Binary instance referencing the uploaded file.
- Raises:
FileNotFoundError – if the file refers to an invalid path.
- create(*binaries: Binary)
Create binaries, i.e. upload files.
Each of the binaries must have a file set. The binaries are created one by one, in case of an error the state is unclear.
- Parameters:
*binaries (Binary) – Binaries to upload
- Returns:
The number of successfully created binaries.
- Raises:
FileNotFoundError – if one of the file attributes within the binaries refers to an invalid file path
- update(id: str, file: str | BinaryIO, type: str = None)
Update a binary attachment.
- Parameters:
id (str) – ID of an existing Binary within Cumulocity
file (str|file-like) – File to upload
type – Content type of the file (defaults to ‘application/octet-stream’)
- Raises:
FileNotFoundError – if the file refers to an invalid path.
- class c8y_api.model.Identity(c8y: CumulocityRestApi)
Provides access to the Identity API.
- create(external_id, external_type, managed_object_id)
Create a new External ID within the database.
- Parameters:
external_id (str) – A string to be used as ID for external use
external_type (str) – Type of the external ID, e.g. _com_cumulocity_model_idtype_SerialNumber_
managed_object_id (str) – Valid database ID of a managed object within Cumulocity
- delete(external_id, external_type)
Remove an External ID from the database.
- Parameters:
external_id (str) – A string to be used as ID for external use
external_type (str) – Type of the external ID, e.g. _com_cumulocity_model_idtype_SerialNumber_
- get(external_id, external_type)
Obtain a specific External ID from the database.
- Parameters:
external_id (str) – A string to be used as ID for external use
external_type (str) – Type of the external ID, e.g. _com_cumulocity_model_idtype_SerialNumber_
- Returns:
ExternalID object
- get_id(external_id, external_type)
Read the ID of the referenced managed object by its external ID.
- Parameters:
external_id (str) – A string to be used as ID for external use
external_type (str) – Type of the external ID, e.g. _com_cumulocity_model_idtype_SerialNumber_
- Returns:
A database ID (string)
- get_object(external_id, external_type)
Read a managed object by its external ID reference.
- Parameters:
external_id (str) – A string to be used as ID for external use
external_type (str) – Type of the external ID, e.g. _com_cumulocity_model_idtype_SerialNumber_
- Returns:
ManagedObject instance
- get_all(object_id: str) [<class 'c8y_api.model.identity.ExternalId'>]
Read all external ID for a managed object.
- Parameters:
object_id (str) – Valid database ID of a managed object within Cumulocity
- Returns:
A list of ExternalID instances (can be empty)
- class c8y_api.model.Measurements(c8y: CumulocityRestApi)
A wrapper for the standard Measurements API.
This class can be used for get, search for, create, update and delete measurements within the Cumulocity database.
See also: https://cumulocity.com/guides/reference/measurements/#measurement
- class AggregationType
Series aggregation types.
- get(measurement_id: str | int) Measurement
Read a specific measurement from the database.
- Parameters:
measurement_id (str|int) – database ID of a measurement
- Returns:
Measurement object
- Raises:
KeyError – if the ID cannot be resolved.
- select(type: str = None, source: str | int = None, fragment: str = None, value: str = None, series: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = None, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[Measurement]
Query the database for measurements and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (within reason).
- Parameters:
type (str) – Alarm type
source (str|int) – Database ID of a source device
fragment (str) – Name of a present custom/standard fragment
value (str) – Type/Name of a present value fragment
series (str) – Name of a present series within a value fragment
before (datetime|str) – Datetime object or ISO date/time string. Only measurements assigned to a time before this date are returned.
after (datetime|str) – Datetime object or ISO date/time string. Only measurements assigned to a time after this date are returned.
min_age (timedelta) – Timedelta object. Only measurements of at least this age are returned.
max_age (timedelta) – Timedelta object. Only measurements with at most this age are returned.
reverse (bool) – Invert the order of results, starting with the most recent one.
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of measurements which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Iterable of matching Measurement objects
- Return type:
Generator[Measurement]
- get_all(type: str = None, source: str | int = None, fragment: str = None, value: str = None, series: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = None, limit: int = None, page_size: int = 1000, page_number: int = None) List[Measurement]
Query the database for measurements and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
- Returns:
List of matching Measurement objects
- get_last(type: str = None, source: str | int = None, fragment: str = None, value: str = None, series: str = None, before: str | datetime = None, min_age: timedelta = None) Measurement
Query the database and return the last matching measurement.
This function is a special variant of the select function. Only the last matching result is returned.
- Returns:
Last matching Measurement object
- get_series(source: str = None, aggregation: str = None, series: str | Sequence[str] = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse=False) Series
Query the database for a list of series and their values.
- Parameters:
source (str) – Database ID of a source device
aggregation (str) – Aggregation type
series (str|Sequence[str]) – Series’ to query
before (datetime|str) – Datetime object or ISO date/time string. Only measurements assigned to a time before this date are included.
after (datetime|str) – Datetime object or ISO date/time string. Only measurements assigned to a time after this date are included.
min_age (timedelta) – Timedelta object. Only measurements of at least this age are included.
max_age (timedelta) – Timedelta object. Only measurements with at most this age are included.
reverse (bool) – Invert the order of results, starting with the most recent one.
- Returns:
A Series object which wraps the raw JSON result but can also be used to conveniently collect the series’ values.
See also: https://cumulocity.com/api/core/#operation/getMeasurementSeriesResource
- delete_by(type: str = None, source: str | int = None, fragment: str = None, value: str = None, series: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None)
Query the database and delete matching measurements.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (within reason).
Args: See ‘select’ function
- create(*measurements)
Bulk create a collection of measurements within the database.
- Parameters:
*measurements (Measurement) – Collection of Measurement objects.
- class c8y_api.model.Events(c8y)
Provides access to the Events API.
This class can be used for get, search for, create, update and delete events within the Cumulocity database.
See also: https://cumulocity.com/api/#tag/Events
- build_attachment_path(event_id: str) str
Build the attachment path of a specific event.
- Parameters:
event_id (int|str) – Database ID of the event
- Returns:
The relative path to the event attachment within Cumulocity.
- get(event_id: str) Event
Retrieve a specific object from the database.
- Parameters:
event_id (str) – The database ID of the event
- Returns:
An Event instance representing the object in the database.
- select(type: str = None, source: str = None, fragment: str = None, before: str | datetime = None, after: str | datetime = None, created_before: str | datetime = None, created_after: str | datetime = None, updated_before: str | datetime = None, updated_after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[Event]
Query the database for events and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filter’s specification. Filters can be combined (within reason).
- Parameters:
type (str) – Event type
source (str) – Database ID of a source device
fragment (str) – Name of a present custom/standard fragment
before (str|datetime) – Datetime object or ISO date/time string. Only events assigned to a time before this date are returned.
after (str|datetime) – Datetime object or ISO date/time string. Only events assigned to a time after this date are returned.
created_before (str|datetime) – Datetime object or ISO date/time string. Only events changed at a time before this date are returned.
created_after (str|datetime) – Datetime object or ISO date/time string. Only events changed at a time after this date are returned.
updated_before (str|datetime) – Datetime object or ISO date/time string. Only events changed at a time before this date are returned.
updated_after (str|datetime) – Datetime object or ISO date/time string. Only events changed at a time after this date are returned.
min_age (timedelta) – Minimum age for selected events.
max_age (timedelta) – Maximum age for selected events.
reverse (bool) – Invert the order of results, starting with the most recent one.
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of events which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator for Event objects
- get_all(type: str = None, source: str = None, fragment: str = None, before: str | datetime = None, after: str | datetime = None, created_before: str | datetime = None, created_after: str | datetime = None, updated_before: str | datetime = None, updated_after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) List[Event]
Query the database for events and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
See select for a documentation of arguments.
- Returns:
List of Event objects
- create(*events: Event)
Create event objects within the database.
- Note: If not yet defined, this will set the event date to now in
each of the given event objects.
- Parameters:
*events (Event) – Collection of Event instances
- update(*events: Event)
Write changes to the database.
- Parameters:
*events (Event) – Collection of Event instances
- apply_to(event: Event | dict, *event_ids: str)
Apply changes made to a single instance to other objects in the database.
- Parameters:
event (Event|dict) – Event used as model for the update or simply a dictionary representing the diff JSON.
*event_ids (str) – Collection of ID of the events to update
- delete_by(type: str = None, source: str = None, fragment: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None)
Query the database and delete matching events.
All parameters are considered to be filters, limiting the result set to objects which meet the filter’s specification. Filters can be combined (within reason).
- Parameters:
type (str) – Event type
source (str) – Database ID of a source device
fragment (str) – Name of a present custom/standard fragment
before (str|datetime) – Datetime object or ISO date/time string. Only events assigned to a time before this date are returned.
after (str|datetime) – Datetime object or ISO date/time string. Only events assigned to a time after this date are returned.
min_age (timedelta) – Minimum age for selected events.
max_age (timedelta) – Maximum age for selected events.
- create_attachment(event_id: str, file: str | BinaryIO, content_type: str = None) dict
Add an event’s binary attachment.
- Parameters:
event_id (str) – The database ID of the event
file (str|BinaryIO) – File-like object or a file path
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
Attachment details as JSON object (dict).
- update_attachment(event_id: str, file: str | BinaryIO, content_type: str = None) dict
Update an event’s binary attachment.
- Parameters:
event_id (str) – The database ID of the event
file (str|BinaryIO) – File-like object or a file path
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
Attachment details as JSON object (dict).
- download_attachment(event_id: str) bytes
Read an event’s binary attachment.
- Parameters:
event_id (str) – The database ID of the event
- Returns:
The event’s binary attachment as bytes.
- delete_attachment(event_id: str)
Remove an event’s binary attachment.
- Parameters:
event_id (str) – The database ID of the event
- class c8y_api.model.Alarms(c8y)
A wrapper for the standard Alarms API.
This class can be used for get, search for, create, update and delete alarms within the Cumulocity database.
See also: https://cumulocity.com/api/#tag/Alarms
- get(id: str) Alarm
Retrieve a specific object from the database.
- Parameters:
id (str) – The database ID of the object
- Returns:
An Alarm instance representing the object in the database.
- select(type: str = None, source: str = None, fragment: str = None, status: str = None, severity: str = None, resolved: str = None, before: str | datetime = None, after: str | datetime = None, created_before: str | datetime = None, created_after: str | datetime = None, updated_before: str | datetime = None, updated_after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[Alarm]
Query the database for alarms and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (as defined in the Cumulocity REST API).
- Parameters:
type (str) – Alarm type
source (str) – Database ID of a source device
fragment (str) – Name of a present custom/standard fragment
status (str) – Alarm status
severity (str) – Alarm severity
resolved (str) – Whether the alarm status is CLEARED
before (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time before this date are returned.
after (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time after this date are returned
created_before (str|datetime) – Datetime object or ISO date/time string. Only alarms changed at a time before this date are returned.
created_after (str|datetime) – Datetime object or ISO date/time string. Only alarms changed at a time after this date are returned.
updated_before (str|datetime) – Datetime object or ISO date/time string. Only alarms changed at a time before this date are returned.
updated_after (str|datetime) – Datetime object or ISO date/time string. Only alarms changed at a time after this date are returned.
min_age (timedelta) – Matches only alarms of at least this age
max_age (timedelta) – Matches only alarms with at most this age
reverse (bool) – Invert the order of results, starting with the most recent one
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of alarms which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator of Alarm objects
- get_all(type: str = None, source: str = None, fragment: str = None, status: str = None, severity: str = None, resolved: str = None, before: str | datetime = None, after: str | datetime = None, created_before: str | datetime = None, created_after: str | datetime = None, updated_before: str | datetime = None, updated_after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) List[Alarm]
Query the database for alarms and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
See select for a documentation of arguments.
- Returns:
List of Alarm objects
- count(type: str = None, source: str = None, fragment: str = None, status: str = None, severity: str = None, resolved: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None) int
Count the number of certain alarms.
- Parameters:
type (str) – Alarm type
source (str) – Database ID of a source device
fragment (str) – Name of a present custom/standard fragment
status (str) – Alarm status
severity (str) – Alarm severity
resolved (str) – Whether the alarm status is CLEARED
before (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time before this date are returned.
after (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time after this date are returned
min_age (timedelta) – Matches only alarms of at least this age
max_age (timedelta) – Matches only alarms with at most this age
- Returns:
Number of matching alarms in Cumulocity.
- create(*alarms)
Create alarm objects within the database.
- Parameters:
*alarms (Alarm) – Collection of Alarm instances
- update(*alarms)
Write changes to the database.
- Parameters:
*alarms (Alarm) – Collection of Alarm instances
- apply_to(alarm: Alarm | dict, *alarm_ids: str)
Apply changes made to a single instance to other objects in the database.
- Parameters:
alarm (Alarm|dict) – Object serving as model for the update or simply a dictionary representing the diff JSON.
*alarm_ids (str) – A collection of database IDS of alarms
- apply_by(alarm: Alarm, type: str = None, source: str = None, fragment: str = None, status: str = None, severity: str = None, resolved: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None)
Apply changes made to a single instance to other objects in the database.
- Parameters:
alarm (Alarm) – Object serving as model for the update
type (str) – Alarm type
source (str) – Database ID of a source device
fragment (str) – Name of a present custom/standard fragment
status (str) – Alarm status
severity (str) – Alarm severity
resolved (str) – Whether the alarm status is CLEARED
before (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time before this date are returned.
after (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time after this date are returned
min_age (timedelta) – Matches only alarms of at least this age
max_age (timedelta) – Matches only alarms with at most this age
See also: https://cumulocity.com/api/#operation/putAlarmCollectionResource
- delete(*alarms)
Delete alarm objects within the database.
Note: within Cumulocity alarms are identified by type and source. These fields must be defined within the provided objects for this operation to function.
- Parameters:
*alarms (Alarm) – Collection of Alarm instances.
- delete_by(type: str = None, source: str = None, fragment: str = None, status: str = None, severity: str = None, resolved: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None)
Query the database and delete matching alarms.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (as defined in the Cumulocity REST API).
- Parameters:
type (str) – Alarm type
source (str) – Database ID of a source device
fragment (str) – Name of a present custom/standard fragment
status (str) – Alarm status
severity (str) – Alarm severity
resolved (str) – Whether the alarm status is CLEARED
before (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time before this date are returned.
after (str|datetime) – Datetime object or ISO date/time string. Only alarms assigned to a time after this date are returned
min_age (timedelta) – Matches only alarms of at least this age
max_age (timedelta) – Matches only alarms with at most this age
- class c8y_api.model.Subscriptions(c8y: CumulocityRestApi)
Provides access to the Notification 2.0 Subscriptions API.
This class can be used for get, search for, create, and delete Notification2 subscriptions within the Cumulocity database.
- get(subscription_id: str) Subscription
Retrieve a specific subscription from the database.
- Parameters:
subscription_id (str) – Subscription ID
- Returns:
A Subscription instance
- Raises:
KeyError – if the given ID is not defined within the database
- select(context: str = None, source: str = None, subscription: str = None, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[Subscription]
Query the database for subscriptions and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters’ specification. Filters can be combined (within reason).
- Parameters:
context (str) – Subscription context.
source (str) – Managed object ID the subscription is for.
subscription (str) – The subscription name.
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of objects which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator for Subscription instances
- get_all(context: str = None, source: str = None, subscription: str = None, limit: int = None, page_size: int = 1000, page_number: int = None) List[Subscription]
Query the database for subscriptions and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
- Returns:
List of Subscription instances.
- create(*subscriptions: Subscription) None
Create subscriptions within the database.
- Parameters:
*subscriptions (TenantOption) – Collection of Subscription instances
- delete_by(context: str = None, source: str = None) None
Delete subscriptions within the database.
- Parameters:
context (str) – Subscription context
source (str) – Managed object ID the subscription is for.
- class c8y_api.model.Users(c8y)
Provides access to the User API.
See also: https://cumulocity.com/api/#tag/Users
- get(username)
Retrieve a specific user.
- Parameters:
username (str) – The ID of the user (usually the mail address)
- Returns:
A User instance
- select(username: str = None, groups: str | int | GlobalRole | List[str] | List[int] | List[GlobalRole] = None, page_size: int = 5)
Lazily select and yield User instances.
The result can be limited by username (prefix) and/or group membership.
- Parameters:
username (str) – A user’s username or a prefix thereof
groups (int, [int], str, [str], GlobalRole, [GlobalRole]) – a scalar or list of int (actual group ID), string (group names), or actual Group instances
page_size (int) – Number of results fetched per request
- Returns:
Generator of Group instances
- get_all(username: str = None, groups: str | int | GlobalRole | List[str] | List[int] | List[GlobalRole] = None, page_size: int = 1000)
Select and retrieve User instances as list.
The result can be limited by username (prefix) and/or group membership.
- Parameters:
username (str) – A user’s username or a prefix thereof
groups – a scalar or list of int (actual group ID), string (group names), or actual Group instances
page_size (int) – Maximum number of entries fetched per requests;
setting (this is a performance) –
- Returns:
List of User
- create(*users)
Create users within the database.
- Parameters:
*users (User) – Collection of User instances
- set_password(username: str, new_password: str)
Set the password of a user.
- Parameters:
username (str) – Username of a Cumulocity user
new_password (str) – The new password to set
- set_owner(user_id: str, owner_id: str | None)
Set the owner of a given user.
- Parameters:
user_id (str) – The user to set an owner for
owner_id (str) – The ID of the owner user; Can be None to unassign/remove the current owner
- set_delegate(user_id: str, delegate_id: str | None)
Set the delegate of a given user.
- Parameters:
user_id (str) – The user to set an owner for
delegate_id (str) – The ID of the delegate user; Can be None to unassign/remove the current owner
- class c8y_api.model.GlobalRoles(c8y)
Provides access to the Global Role API.
Notes
Global Roles are called ‘groups’ in the Cumulocity Standard REST API; However, ‘global roles’ is the official concept name and therefore used for consistency with the Cumulocity realm.
See also: https://cumulocity.com/api/#tag/Groups
- reset_caches()
Reset internal caching.
Caches are used for lookups of global roles by name.
- get(role_id: int | str) GlobalRole
Retrieve a specific global role.
Note: The C8Y REST API does not support direct query by name. Hence, searching by name will actually retrieve all available groups and return the matching ones. These groups will be cached internally for subsequent calls.
See also method
reset_caches
- Parameters:
role_id (int|str) – An actual global role ID as int/string or a global role name
- Returns:
A GlobalRole instance for the ID/name.
- select(username: str = None, page_size: int = 5) Generator[GlobalRole]
Iterate over global roles.
- Parameters:
username (str) – Retrieve global roles assigned to a specified user If omitted, all available global roles are returned
page_size (int) – Maximum number of entries fetched per requests; this is a performance setting
- Returns:
Generator of GlobalRole instances
- get_all(username: str = None, page_size: int = 1000) List[GlobalRole]
Retrieve global roles.
- Parameters:
username (str) – Retrieve global roles assigned to a specified user If omitted, all available global roles are returned
page_size (int) – Maximum number of entries fetched per requests; this is a performance setting
- Returns:
List of GlobalRole instances
- assign_users(role_id: int | str, *usernames: str)
Add users to a global role.
- Parameters:
role_id (int|str) – Technical ID of the global role
*usernames (str) – Iterable of usernames to assign
- unassign_users(role_id: int | str, *usernames: str)
Remove users from a global role.
- Parameters:
role_id (int|str) – Technical ID of the global role
*usernames (str) – Iterable of usernames to unassign
- assign_permissions(role_id: int | str, *permissions: str)
Add permissions to a global role.
- Parameters:
role_id (int|str) – Technical ID of the global role
*permissions (str) – Iterable of permission ID to assign
- unassign_permissions(role_id: int | str, *permissions: str)
Remove permissions from a global role.
- Parameters:
role_id (int|str) – Technical ID of the global role
*permissions (str) – Iterable of permission ID to assign
- class c8y_api.model.Operations(c8y: CumulocityRestApi)
A wrapper for the standard Operation API.
This class can be used for get, search for, create, update and delete operations within the Cumulocity database.
See also: https://cumulocity.com/api/core/#tag/Operations
- get(operation_id: str | int) Operation
Read a specific operation from the database.
- Parameters:
operation_id (str|int) – database ID of an operation
- Returns:
Operation object
- Raises:
KeyError – if the ID cannot be resolved.
- select(agent_id: str = None, device_id: str = None, status: str = None, bulk_id: str = None, fragment: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[Operation]
Query the database for operations and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (within reason).
- Parameters:
agent_id (str) – Database ID of agent
device_id (str) – Database ID of device
status (str) – Status of operation
bulk_id (str) – The bulk operation ID that this object belongs to
fragment (str) – Name of a present custom/standard fragment
before (datetime|str) – Datetime object or ISO date/time string. Only operations assigned to a time before this date are returned.
after (datetime|str) – Datetime object or ISO date/time string. Only operations assigned to a time after this date are returned.
min_age (timedelta) – Timedelta object. Only operation of at least this age are returned.
max_age (timedelta) – Timedelta object. Only operations with at most this age are returned.
reverse (bool) – Invert the order of results, starting with the most recent one.
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of operations which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Iterable of matching Operation objects
- Return type:
Generator[Operation]
- get_all(agent_id: str = None, device_id: str = None, status: str = None, bulk_id: str = None, fragment: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) List[Operation]
Query the database for operations and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
- Returns:
List of matching Operation objects
- get_last(agent_id: str = None, device_id: str = None, status: str = None, bulk_id: str = None, fragment: str = None, before: str | datetime = None, min_age: timedelta = None) Operation
Query the database and return the last matching operation.
This function is a special variant of the select function. Only the last matching result is returned.
- Returns:
Last matching Operation object
- delete_by(agent_id: str = None, device_id: str = None, status: str = None, bulk_id: str = None, fragment: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None)
Query the database and delete matching operations.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (as defined in the Cumulocity REST API).
- Parameters:
agent_id (str) – Database ID of agent
device_id (str) – Database ID of device
status (str) – Status of operation
bulk_id (str) – The bulk operation ID that this object belongs to
fragment (str) – Name of a present custom/standard fragment
before (datetime|str) – Datetime object or ISO date/time string. Only operations assigned to a time before this date are selected.
after (datetime|str) – Datetime object or ISO date/time string. Only operation assigned to a time after this date are selected.
min_age (timedelta) – Timedelta object. Only operation of at least this age are returned.
max_age (timedelta) – Timedelta object. Only operations with at most this age are returned. # build a base query
- class c8y_api.model.BulkOperations(c8y: CumulocityRestApi)
A wrapper for the standard Bulk Operation API.
This class can be used for get, search for, create, update and delete bulk operations within the Cumulocity database.
See also: https://cumulocity.com/api/core/#tag/Bulk-operations
- get(operation_id: str | int) BulkOperation
Read a specific bulk operation from the database.
- Parameters:
operation_id (str|int) – database ID of a bulk operation
- Returns:
BulkOperation object
- Raises:
KeyError – if the ID cannot be resolved.
- select(limit: int = None, page_size: int = 1000, page_number: int = None) Generator[BulkOperation]
Query the database for operations and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters’ specification. Filters can be combined (within reason).
- Parameters:
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of operations which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Iterable of matching BulkOperation objects
- Return type:
Generator[BulkOperation]
- get_all(limit: int = None, page_size: int = 1000, page_number: int = None) List[BulkOperation]
Query the database for bulk operations and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
- Returns:
List of matching BulkOperation objects
- class c8y_api.model.Applications(c8y: CumulocityRestApi)
Provides access to the Application API.
This class can be used for get, search for, create, update and delete applications within the Cumulocity database.
See also: https://cumulocity.com/api/#tag/Application-API
- get(application_id: str) Application
Retrieve a specific object from the database.
- Parameters:
application_id (str) – The database ID of the application
- Returns:
An Application instance representing the object in the database.
- get_current() Application
Retrieve the current application.
Note: Requires boostrap permissions.
- Returns:
An Application instance.
- get_current_settings() List[ApplicationSetting]
Query the database for the current application’s settings.
Note: Requires boostrap permissions.
- Returns:
List of ApplicationSetting instances.
- get_current_subscriptions() List[ApplicationSubscription]
Query the database for subscriptions of the current application.
Note: Requires boostrap permissions.
- Returns:
List of ApplicationSubscription instances.
- select(name: str = None, type: str = None, owner: str = None, user: str = None, tenant: str = None, subscriber: str = None, provided_for: str = None, limit: int = None, page_size: int = 100, page_number: int = None) Generator[Application]
Query the database for applications and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters’ specification. Filters can be combined (within reason).
- Parameters:
name (str) – Name of an application (no wildcards allowed)
type (str) – Application type (e.g. HOSTED)
owner (str) – ID of a Cumulocity user which owns the application
user (str) – ID of a Cumulocity user which has general access
tenant (str) – ID of a Cumulocity tenant which either owns the application or is subscribed to it
subscriber (str) – ID of a Cumulocity tenant which is subscribed to the application (and may own it)
provided_for (str) – ID of a Cumulocity tenant which is subscribed to the application but does not own it
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of events which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
A Generator for Application objects.
- get_all(name: str = None, type: str = None, owner: str = None, user: str = None, tenant: str = None, subscriber: str = None, provided_for: str = None, limit: int = None, page_size: int = 100, page_number: int = None) List[Application]
Query the database for applications and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
See select for a documentation of arguments.
- Returns:
List of Application objects
- upload_attachment(application_id: str, file: str | BinaryIO)
Upload application binary for a registered application.
- Parameters:
application_id (str) – The Cumulocity object ID of the application
file – File path or file-like object to upload.
- class c8y_api.model.TenantOptions(c8y: CumulocityRestApi)
Provides access to the Tenant Options API.
This class can be used for get, search for, create, update and delete tenant options within the Cumulocity database.
See also: https://cumulocity.com/api/latest/#tag/Options
- build_object_path(category: str, key: str) str
Build the path to a specific object of this resource.
Note: this function overrides with different arguments because tenant options, unlike other objects, are not identified by ID but category/key.
- Parameters:
category (str) – Option category
key (str) – Option key (name)
- Returns:
The relative path to the object within Cumulocity.
- select(category: str = None, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[TenantOption]
Query the database for tenant options and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters specification. Filters can be combined (within reason).
- Parameters:
category (str) – Option category
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of objects which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator for TenantObject instances
- get_all(category: str = None, limit: int = None, page_size: int = 1000, page_number: int = None) List[TenantOption]
Query the database for tenant options and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
- Returns:
List of TenantObject instances
- get_all_mapped(category: str = None) dict[str, str]
Query the database for tenant options and return the results as a dictionary.
This result dictionary does not specify option categories hence it is best used with the category filter unless the keys are unique by themselves.
- Parameters:
category (str) – Option category
- Returns:
Dictionary of option keys to values.
- get(category: str, key: str) TenantOption
Retrieve a specific option from the database.
- Parameters:
category (str) – Option category
key (str) – Option key (name)
- Returns:
A TenantOption instance
- Raises:
KeyError – if the given combination of category and key
is not defined within the database –
- get_value(category: str, key: str) str
Retrieve the value of a specific option from the database.
- Parameters:
category (str) – Option category
key (str) – Option key (name)
- Returns:
The value of the specified option
- Raises:
KeyError – if the given combination of category and key
is not defined within the database –
- set_value(category: str, key: str, value: str)
Create an option within the database.
This is a shortcut function to avoid unnecessary instantiation of the TenantOption class.
- Parameters:
category (str) – Option category
key (str) – Option key (name)
value (str) – Option value
- create(*options: TenantOption) None
Create options within the database.
- Parameters:
*options (TenantOption) – Collection of TenantObject instances
- update(*options: TenantOption) None
Update options within the database.
- Parameters:
*options (TenantOption) – Collection of TenantObject instances
- update_by(category: str, options: dict[str, str]) None
Update options within the database.
- Parameters:
category (str) – Option category
options (dict) – A dictionary of option keys and values
- delete(*options: TenantOption) None
Delete options within the database.
- Parameters:
*options (TenantOption) – Collection of TenantObject instances
- delete_by(category: str, key: str) None
Delete specific option within the database.
- Parameters:
category (str) – Option category
key (str) – Option key (name)
- class c8y_api.model.AuditRecords(c8y)
Provides access to the Audit API.
This class can be used for get, search for, create, update and delete records within the Cumulocity database.
See also: https://cumulocity.com/api/core/#tag/Audits
- get(record_id: str) AuditRecord
Retrieve a specific object from the database.
- Parameters:
record_id (str) – The database ID of the audit record
- Returns:
An AuditRecord instance representing the object in the database.
- select(type: str = None, source: str = None, application: str = None, user: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) Generator[AuditRecord]
Query the database for audit records and iterate over the results.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
All parameters are considered to be filters, limiting the result set to objects which meet the filters’ specification. Filters can be combined (within reason).
- Parameters:
type (str) – Audit record type
source (str) – Database ID of a source device
application (str) – Application from which the audit was carried out.
user (str) – The user who carried out the activity.
before (str|datetime) – Datetime object or ISO date/time string. Only records assigned to a time before this date are returned.
after (str|datetime) – Datetime object or ISO date/time string. Only records assigned to a time after this date are returned.
min_age (timedelta) – Minimum age for selected records.
max_age (timedelta) – Maximum age for selected records.
reverse (bool) – Invert the order of results, starting with the most recent one.
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of objects which are read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator for AuditRecord objects
- get_all(type: str = None, source: str = None, application: str = None, user: str = None, before: str | datetime = None, after: str | datetime = None, min_age: timedelta = None, max_age: timedelta = None, reverse: bool = False, limit: int = None, page_size: int = 1000, page_number: int = None) List[AuditRecord]
Query the database for audit records and return the results as list.
This function is a greedy version of the select function. All available results are read immediately and returned as list.
See select for a documentation of arguments.
- Returns:
List of AuditRecord objects
- create(*records: AuditRecord)
Create audit record objects within the database.
- Note: If not yet defined, this will set the record date to now in
each of the given objects.
- Parameters:
*records (AuditRecord) – Collection of AuditRecord instances
- class c8y_api.model.Tokens(c8y: CumulocityRestApi)
Provides access to the Notification 2.0 token generation API.
This class can be used for get, search for, create, and delete Notification2 subscriptions within the Cumulocity database.
- See also: https://cumulocity.com/api/#tag/Tokens
- generate(subscription: str, expires: int = 60, subscriber: str = None, signed: bool = None, shared: bool = None, non_persistent: bool = None) str
Generate a new access token.
- Parameters:
subscription (str) – Subscription name.
expires (int) – Expiration time in minutes.
subscriber (str) – Subscriber ID (name). A UUID based default will be used if None.
signed (bool) – Whether the token should be signed.
shared (bool) – Whether the token is used to create a shared consumer.
non_persistent (bool) – Whether the token refers to the non-persistent variant of the named subscription.
- Returns:
JWT access token as string.
- renew(token: str) str
Renew a token.
- Parameters:
token – Currently valid token to be renewed.
- unsubscribe(token: str)
Invalidate a token and unsubscribe a subscriber.
- Parameters:
token (str) – Subscribed token
- build_websocket_uri(token: str, consumer: str = None)
Build websocket access URL.
- Parameters:
token (str) – Subscriber access token
consumer (str) – Optional consumer ID (to allow ‘sticky’ connections after interrupt).
- Returns:
//) URL to access the subscriber channel.
- Return type:
A websocket (ws(s)
- class c8y_api.model.InventoryRoles(c8y)
Provides access to the InventoryRole API.
This class can be used for get, search for, create, update and delete inventory roles within the Cumulocity database.
See also: https://cumulocity.com/api/#tag/Inventory-Roles
- get(role_id: str | int) InventoryRole
Get a specific inventory role object.
- Parameters:
role_id (str|int) – Cumulocity ID of the inventory role
- Returns:
An InventoryRole instance for this ID
- Raises:
SyntaxError – if the ID is not defined.
Note: In contrast to other API the InventoryRole API does not raise an KeyError (i.e. 404) for undefined ID but a SyntaxError (HTTP 500).
- select(limit: int = None, page_size: int = 1000, page_number: int = None) Generator[InventoryRole]
Get all defined inventory roles.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
Note: The InventoryRole API does not support filters.
- Parameters:
limit (int) – Limit the number of results to this number.
page_size (int) – Define the number of objects read (and parsed in one chunk). This is a performance related setting.
page_number (int) – Pull a specific page; this effectively disables automatic follow-up page retrieval.
- Returns:
Generator for InventoryRole objects
- get_all(limit: int = None, page_size: int = 1000, page_number: int = None) List[InventoryRole]
Get all defined inventory roles.
This function is a greedy version of the
select
function. All available results are read immediately and returned as list.See
select
for a documentation of arguments.- Returns:
List of InventoryRole objects
- select_assignments(username: str) Generator[InventoryRoleAssignment]
Get all inventory role assignments of a user.
This function is implemented in a lazy fashion - results will only be fetched from the database as long there is a consumer for them.
- Parameters:
username (str) – Username of a Cumulocity user
- Returns:
Generator for InventoryRoleAssignment objects
- get_all_assignments(username: str) List[InventoryRoleAssignment]
Get all inventory role assignments of a user.
This function is a greedy version of the
select_assignments
function. All available results are read immediately and returned as list.See
select_assignments
for a documentation of arguments.- Returns:
List of InventoryRoleAssignment objects
- create(*roles: InventoryRole)
Create objects within the database.
- Parameters:
*roles (InventoryRole) – Collection of InventoryRole instances
- update(*roles: InventoryRole)
Write changes to the database.
- Parameters:
*roles (InventoryRole) – Collection of InventoryRole instances
Object Models
The Cumulocity Python API’s object model provides object-oriented access to the Cumulocity REST API. Use it to create and modify single objects within the Database.
These objects can also be used directly within the Main API Classes to modify data in bulk.
- class c8y_api.model.ManagedObject(c8y: CumulocityRestApi = None, type: str = None, name: str = None, owner: str = None, **kwargs)
Represent a managed object within the database.
Instances of this class are returned by functions of the corresponding Inventory API. Use this class to create new or update managed objects.
Within Cumulocity a managed object is used to hold virtually any additional (apart from measurements, events and alarms) information. This custom information is modelled in fragments, named elements of any structure.
Fragments are modelled as standard Python fields and can be accessed directly if the names & structures are known:
x = mo.c8y_CustomFragment.values.x
Managed objects can be changed and such updates are written as differences to the database. The API does the tracking of these differences automatically - just use the ManagedObject class like any other Python class.
mo.owner = ‘admin@cumulocity.com’ mo.c8y_CustomFragment.region = ‘EMEA’ mo.add_fragment(‘c8y_CustomValue’, value=12, uom=’units’)
Note: This does not work if a fragment is actually a field, not a structure own its own. A direct assignment to such a value fragment, like
mo.c8y_CustomReferences = [1, 2, 3]
is currently not supported nicely as it will not be recognised as an update. A manual update flagging is required:
mo.c8y_CustomReferences = [1, 2, 3] mo.flag_update(‘c8y_CustomReferences’)
See also https://cumulocity.com/guides/reference/inventory/#managed-object
- class Resource
Inventory sub-resources.
- AVAILABILITY = 'availability'
- SUPPORTED_MEASUREMENTS = 'supportedMeasurements'
- SUPPORTED_SERIES = 'supportedSeries'
- class Fragment
Standard fragments.
- SUPPORTED_MEASUREMENTS = 'c8y_SupportedMeasurements'
- SUPPORTED_SERIES = 'c8y_SupportedSeries'
- __init__(c8y: CumulocityRestApi = None, type: str = None, name: str = None, owner: str = None, **kwargs)
Create a new ManagedObject instance.
Custom fragments can be added to the object using kwargs or after creation using += or [] syntax.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
type (str) – ManagedObject type
name (str) – ManagedObject name
owner (str) – User ID of the owning user (can be left None to automatically assign to the connection user upon creation)
kwargs – Additional arguments are treated as custom fragments
- Returns:
ManagedObject instance
- child_assets
List of NamedObject references to child assets.
- type
Updatable property.
- name
Updatable property.
- owner
Updatable property.
- property creation_datetime
Convert the object’s creation to a Python datetime object.
- Returns:
Standard Python datetime object
- property update_datetime
Convert the object’s creation to a Python datetime object.
- Returns:
Standard Python datetime object
- classmethod from_json(json: dict) ManagedObject
Build a new ManagedObject instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing a managed object within Cumulocity
- Returns:
ManagedObject object
- to_json(only_updated=False) dict
Create a representation of this object in Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the object. It is used for object creation and update within Cumulocity, so for example the ‘id’ field is never included.
- Parameters:
only_updated (bool) – Whether the result should be limited to changed fields only (for object updates). Default: False
- Returns:
A JSON (nested dict) object.
- create() ManagedObject
Create a new representation of this object within the database.
This function can be called multiple times to create multiple instances of this object with different ID.
- Returns:
A fresh ManagedObject instance representing the created object within the database. This instance can be used to get at the ID of the new managed object.
See also function Inventory.create which doesn’t parse the result.
- update() ManagedObject
Write changes to the database.
- Returns:
A fresh ManagedObject instance representing the updated object within the database.
See also function Inventory.update which doesn’t parse the result.
- apply_to(other_id: str | int) ManagedObject
Apply the details of this object to another object in the database.
Note: This will take the full details, not just the updates.
- Parameters:
other_id (str|int) – Database ID of the event to update.
- Returns:
A fresh ManagedObject instance representing the updated object within the database.
See also function Inventory.apply_to which doesn’t parse the result.
- delete()
Delete this object within the database.
The database ID must be defined for this to function.
See also function Inventory.delete to delete multiple objects.
- add_child_asset(child: ManagedObject | str | int)
Link a child asset to this managed object.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (ManagedObject|str|int) – Child asset or its object ID
- add_child_device(child: ManagedObject | str | int)
Link a child device to this managed object.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (ManagedObject|str|int) – Child device or its object ID
- add_child_addition(child: ManagedObject | str | int)
Link a child addition to this managed object.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (ManagedObject|str|int) – Child addition or its object ID
- unassign_child_asset(child: ManagedObject | str | int)
Remove the link to a child asset.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (ManagedObject|str|int) – Child device or its object ID
- unassign_child_device(child: Device | str | int)
Remove the link to a child device.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (Device|str|int) – Child device or its object ID
- unassign_child_addition(child: ManagedObject | str | int)
Remove the link to a child addition.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (ManagedObject|str|int) – Child device or its object ID
- get_latest_availability() Availability
Retrieve the latest availability information of this object.
- Returns:
DeviceAvailability object
- get_supported_measurements() datetime | str
Retrieve all supported measurement names of this managed object.
- Returns:
List of measurement fragment names.
- get_supported_series() datetime | str
Retrieve all supported measurement series names of this managed object.
- Returns:
List of measurement series names.
- class c8y_api.model.Device(c8y: CumulocityRestApi = None, type: str = None, name: str = None, owner: str = None, **kwargs)
Represent an instance of a Device object within Cumulocity.
Instances of this class are returned by functions of the corresponding DeviceInventory API. Use this class to create new or update Device objects.
Device objects are regular managed objects with additional standardized fragments and fields.
- __init__(c8y: CumulocityRestApi = None, type: str = None, name: str = None, owner: str = None, **kwargs)
Create a new Device instance.
A Device object will always have a c8y_IsDevice fragment. Additional custom fragments can be added using kwargs or after creation, using += or [] syntax.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
type (str) – Device type
name (str) – Device name
owner (str) – User ID of the owning user (can be left None to automatically assign to the connection user upon creation)
kwargs – Additional arguments are treated as custom fragments
- Returns:
Device instance
- classmethod from_json(json: dict) Device
Build a new ManagedObject instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing a managed object within Cumulocity
- Returns:
ManagedObject object
- to_json(only_updated=False) dict
Create a representation of this object in Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the object. It is used for object creation and update within Cumulocity, so for example the ‘id’ field is never included.
- Parameters:
only_updated (bool) – Whether the result should be limited to changed fields only (for object updates). Default: False
- Returns:
A JSON (nested dict) object.
- get_username() str
Return the device username.
- Returns:
Username of the device’s user.
- class c8y_api.model.DeviceGroup(c8y=None, root: bool = False, name: str = None, owner: str = None, **kwargs)
Represent a device group within Cumulocity.
Instances of this class are returned by functions of the corresponding DeviceGroupInventory API. Use this class to create new or update DeviceGroup objects.
DeviceGroup objects are regular managed objects with additional standardized fragments and fields.
- See also https://cumulocity.com/guides/reference/inventory/#managed-object
https://cumulocity.com/guides/users-guide/device-management/#grouping-devices
- ROOT_TYPE = 'c8y_DeviceGroup'
- CHILD_TYPE = 'c8y_DeviceSubGroup'
- __init__(c8y=None, root: bool = False, name: str = None, owner: str = None, **kwargs)
Build a new DeviceGroup object.
The type of a device group will always be either c8y_DeviceGroup or c8y_DeviceSubGroup (depending on it’s level). This is handled by the API.
A DeviceGroup object will always have a c8y_IsDeviceGroup fragment. Additional custom fragments can be added using kwargs or after creation, using += or [] syntax.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
root (bool) – Whether the group is a root group (default is False)
name (str) – Device name
owner (str) – User ID of the owning user (can be left None to automatically assign to the connection user upon creation)
kwargs – Additional arguments are treated as custom fragments
- Returns:
DeviceGroup instance
- classmethod from_json(json: dict) DeviceGroup
Build a new DeviceGroup instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing a device group within Cumulocity
- Returns:
DeviceGroup instance
- create_child(name: str, owner: str = None, **kwargs) DeviceGroup
Create and assign a child group.
This change is written to the database immediately.
- Parameters:
name (str) – Device name
owner (str) – User ID of the owning user (can be left None to automatically assign to the connection user upon creation)
kwargs – Additional arguments are treated as custom fragments
- Returns:
The newly created DeviceGroup object
- create() DeviceGroup
Create a new representation of this object within the database.
This operation will create the group and all added child groups within the database.
- Returns:
A fresh DeviceGroup instance representing the created object within the database. This instance can be used to get at the ID of the new object.
See also function DeviceGroupInventory.create which doesn’t parse the result.
- update() DeviceGroup
Write changed to the database.
Note: Removing child groups is currently not supported.
- Returns:
A fresh DeviceGroup instance representing the updated object within the database.
- delete()
Delete this device group.
The child groups (if there are any) are left dangling. This is equivalent to using the cascade=false parameter in the Cumulocity REST API.
- delete_tree()
Delete this device group and its children.
This is equivalent to using the cascade=true parameter in the Cumulocity REST API.
- assign_child_group(child: DeviceGroup | str | int)
Link a child group to this device group.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (DeviceGroup|str|int) – Child device or its object ID
- unassign_child_group(child: DeviceGroup | str | int)
Remove the link to a child group.
This operation is executed immediately. No additional call to the update method is required.
- Parameters:
child (DeviceGroup|str|int) – Child device or its object ID
- class c8y_api.model.ExternalId(c8y: CumulocityRestApi = None, external_id: str = None, external_type: str = None, managed_object_id: str = None)
Represents an instance of an ExternalID in Cumulocity.
Instances of this class are returned by functions of the corresponding Identity API. Use this class to create or remove external ID.
See also: https://cumulocity.com/api/#tag/External-IDs
- __init__(c8y: CumulocityRestApi = None, external_id: str = None, external_type: str = None, managed_object_id: str = None)
Create a new ExternalId object.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs
manipulation (to be set for direct) –
external_id (str) – A string to be used as ID for external use
external_type (str) – Type of the external ID, e.g. _com_cumulocity_model_idtype_SerialNumber_
managed_object_id (str) – Valid database ID of a managed object within Cumulocity
- Returns:
ExternalId object
- classmethod from_json(json: dict) ExternalId
Build a new ExternalId instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON structure of an external ID object
- Returns:
ExternalId object
- to_json(only_updated: bool = False) dict
Create a representation of this object in Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the object. It is used for object creation and update within Cumulocity, so for example the ‘id’ field is never included.
- Parameters:
only_updated (bool) – Whether the result should be limited to changed fields only (for object updates). Default: False
- Returns:
A JSON (nested dict) object.
- create() ExternalId
Store the external ID to the database.
- Returns:
self reference
- delete()
Remove the external ID from the database.
- Returns:
self reference
- get_id()
Read the referenced managed object ID from database.
- Returns:
Database ID referenced by the external_id and external_type of this instance.
- get_object() ManagedObject
Read the referenced managed object from database.
- Returns:
ManagedObject instance.
- class c8y_api.model.Binary(c8y: CumulocityRestApi = None, type: str = None, name: str = None, owner: str = None, content_type: str = None, file: str | BinaryIO = None, **kwargs)
Represents a binary object/file within the Database.
See also: https://cumulocity.com/api/#tag/Binaries
- __init__(c8y: CumulocityRestApi = None, type: str = None, name: str = None, owner: str = None, content_type: str = None, file: str | BinaryIO = None, **kwargs)
Create a new ManagedObject instance.
Custom fragments can be added to the object using kwargs or after creation using += or [] syntax.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
type (str) – ManagedObject type
name (str) – ManagedObject name
owner (str) – User ID of the owning user (can be left None to automatically assign to the connection user upon creation)
kwargs – Additional arguments are treated as custom fragments
- Returns:
ManagedObject instance
- property content_type: str
Content type set for this binary.
- classmethod from_json(json: dict) Binary
Build a new Binary instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing a managed object within Cumulocity
- Returns:
Binary object
- create() Binary
Create a new representation of this object within the database.
This function can be called multiple times to create multiple instances of this object with different ID.
- Returns:
A fresh Binary instance representing the created object within the database. This instance can be used to get at the ID of the new object.
- Raises:
FileNotFoundError – if the file refers to an invalid path.
See also function Binaries.create which doesn’t parse the result.
- update() Binary
Update the binary attachment.
- Returns:
The Binary managed object.
- Returns:
A fresh Binary instance representing the created object within the database.
- Raises:
FileNotFoundError – if the file refers to an invalid path.
Note: The binary metadata cannot be updated using this method. Only the binary attachment is updated.
- read_file() bytes
Read the content of the binary attachment.
- Returns:
The binary attachment’s content as bytes.
- class c8y_api.model.Measurement(c8y=None, type=None, source=None, time: str | datetime = None, **kwargs)
Represents an instance of a measurement object in Cumulocity.
Instances of this class are returned by functions of the corresponding Measurements API. Use this class to create new or update existing measurements.
See also: https://cumulocity.com/guides/reference/measurements/#measurement
- __init__(c8y=None, type=None, source=None, time: str | datetime = None, **kwargs)
Create a new Measurement object.
- Parameters:
c8y (CumulocityRestApi) – to be set for direct manipulation (create, delete)
type (str) –
source (str) –
time (str|datetime) – Datetime string or Python datetime object. A given datetime string needs to be in standard ISO format incl. timezone: YYYY-MM-DD’T’HH:MM:SS.SSSZ as it is returned by the Cumulocity REST API. A given datetime object needs to be timezone aware. For manual construction it is recommended to specify a datetime object as the formatting of a timestring is never checked for performance reasons.
kwargs – All additional named arguments are interpreted as custom fragments e.g. for data points.
- Returns:
Measurement object
- classmethod from_json(json) Measurement
Build a new Measurement instance from Cumulocity JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) JSON object (nested dictionary) – representing a measurement within Cumulocity
- Returns:
Measurement object
- to_json(only_updated=False) dict
Convert the instance to JSON.
The JSON format produced by this function is what is used by the Cumulocity REST API.
Note: Measurements cannot be updated, hence this function does not feature an only_updated argument.
- Returns:
JSON object (nested dictionary)
- property datetime: Type[datetime] | None
Convert the measurement’s time to a Python datetime object.
- Returns:
The measurement’s time
- Return type:
(datetime)
- create() Measurement
Store the Measurement within the database.
- Returns: A fresh Measurement object representing what was
created within the database (including the ID).
- update() Measurement
Not implemented for Measurements.
- delete()
Delete the Measurement within the database.
- class c8y_api.model.Event(c8y: CumulocityRestApi = None, type: str = None, time: str | datetime = None, source: str = None, text: str = None, **kwargs)
Represent an instance of an event object in Cumulocity.
Instances of this class are returned by functions of the corresponding Events API. Use this class to create new or update Event objects.
See also: https://cumulocity.com/api/#tag/Events
- __init__(c8y: CumulocityRestApi = None, type: str = None, time: str | datetime = None, source: str = None, text: str = None, **kwargs)
Create a new Event object.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
type (str) – Event type
time (str|datetime) – Date/time of the event. Can be provided as timezone-aware datetime object or formatted string (in standard ISO format incl. timezone: YYYY-MM-DD’T’HH:MM:SS.SSSZ as it is returned by the Cumulocity REST API). Use ‘now’ to set to current datetime in UTC.
source (str) – ID of the device which this event is raised by
text (str) – Event test/description
kwargs – Additional arguments are treated as custom fragments
- text
Updatable property.
- property datetime: datetime
Convert the event’s time to a Python datetime object.
- Returns:
Standard Python datetime object
- property creation_datetime: datetime
Convert the event’s creation time to a Python datetime object.
- Returns:
Standard Python datetime object
- property updated_datetime: datetime
Convert the alarm’s last updated time to a Python datetime object.
- Returns:
Standard Python datetime object for the alarm’s last updated time.
- classmethod from_json(json: dict) Event
Create an object instance from Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the JSON. It is used for object creation and update within Cumulocity.
- Parameters:
json (dict) – The JSON to parse.
- Returns:
A CumulocityObject instance.
- to_json(only_updated: bool = False) dict
Create a representation of this object in Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the object. It is used for object creation and update within Cumulocity, so for example the ‘id’ field is never included.
- Parameters:
only_updated (bool) – Whether the result should be limited to changed fields only (for object updates). Default: False
- Returns:
A JSON (nested dict) object.
- create() Event
Create the Event within the database.
- Returns:
A fresh Event object representing what was created within the database (including the ID).
- update() Event
Update the Event within the database.
Note: This will only send changed fields to increase performance.
- Returns:
A fresh Event object representing what the updated state within the database (including the ID).
- delete()
Delete the Event within the database.
- apply_to(other_id: str) Event
- Apply changes made to this object to another object in the
database.
- Parameters:
other_id (str) – Database ID of the event to update.
- Returns:
A fresh Event instance representing the updated object within the database.
See also function Events.apply_to which doesn’t parse the result.
- has_attachment() bool
Check whether the event has a binary attachment.
Event objects that have an attachment feature a c8y_IsBinary fragment. This function checks the presence of that fragment.
Note: This does not query the database. Hence, the information might be outdated if a binary was attached _after_ the event object was last read from the database.
- Returns:
True if the event object has an attachment, False otherwise.
- download_attachment() bytes
Read the binary attachment.
- Returns:
The event’s binary attachment as bytes.
- create_attachment(file: str | BinaryIO, content_type: str = None) dict
Create the binary attachment.
- Parameters:
file (str|BinaryIO) – File-like object or a file path
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
Attachment details as JSON object (dict).
- update_attachment(file: str | BinaryIO, content_type: str = None) dict
Update the binary attachment.
- Parameters:
file (str|BinaryIO) – File-like object or a file path
content_type (str) – Content type of the file sent (default is application/octet-stream)
- Returns:
Attachment details as JSON object (dict).
- delete_attachment()
Remove the binary attachment.
- class c8y_api.model.Alarm(c8y: CumulocityRestApi = None, type: str = None, time: str | datetime = None, source: str = None, text: str = None, status: str = None, severity: str = None, **kwargs)
Represent an instance of an alarm object in Cumulocity.
Instances of this class are returned by functions of the corresponding Alarms API. Use this class to create new or update Alarm objects.
See also: https://cumulocity.com/api/#tag/Alarms
- class Severity
Alarm severity levels.
- MAJOR = 'MAJOR'
- CRITICAL = 'CRITICAL'
- MINOR = 'MINOR'
- WARNING = 'WARNING'
- class Status
Alarm statuses.
- ACTIVE = 'ACTIVE'
- ACKNOWLEDGED = 'ACKNOWLEDGED'
- CLEARED = 'CLEARED'
- __init__(c8y: CumulocityRestApi = None, type: str = None, time: str | datetime = None, source: str = None, text: str = None, status: str = None, severity: str = None, **kwargs)
Create a new Alarm object.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
type (str) – Alarm type
time (str|datetime) – Date/time of the alarm. Can be provided as timezone-aware datetime object or formatted string (in standard ISO format incl. timezone: YYYY-MM-DD’T’HH:MM:SS.SSSZ as it is returned by the Cumulocity REST API). Use ‘now’ to set to current datetime in UTC.
source (str) – ID of the device which this Alarm is raised by
text (str) – Alarm test/description
status (str) – Alarm status
severity (str) – Alarm severity
kwargs – Additional arguments are treated as custom fragments
- text
Updatable property
- status
Updatable property.
- severity
Updatable property.
- property datetime: datetime
Convert the alarm’s time to a Python datetime object.
- Returns:
Standard Python datetime object for the alarm’s time.
- property creation_datetime: datetime
Convert the alarm’s creation time to a Python datetime object.
- Returns:
Standard Python datetime object for the alarm’s creation time.
- property updated_datetime: datetime
Convert the alarm’s last updated time to a Python datetime object.
- Returns:
Standard Python datetime object for the alarm’s last updated time.
- property first_occurrence_datetime: datetime
Convert the first occurrence time to a Python datetime object.
- Returns:
Standard Python datetime object for the first occurrence time.
- classmethod from_json(json: dict) Alarm
Build a new Alarm instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing a managed object within Cumulocity
- Returns:
Alarm object
- to_json(only_updated=False) dict
Convert the instance to JSON.
The JSON format produced by this function is what is used by the Cumulocity REST API.
- Parameters:
only_updated (bool) – Whether only updated fields should be included in the generated JSON
- Returns:
JSON object (nested dictionary)
- create() Alarm
Create the Alarm within the database.
- Returns:
A fresh Alarm instance representing the created object within the database. This instance can be used to get at the ID of the new Alarm object.
- update() Alarm
Update the Alarm within the database.
Note: This will only send changed fields to increase performance.
- Returns:
A fresh Alarm instance representing the updated object within the database.
- apply_to(other_id: str) Alarm
Apply changes made to this object to another object in the database.
- Parameters:
other_id (str) – Database ID of the Alarm to update.
- Returns:
A fresh Alarm instance representing the updated object within the database.
- delete()
Delete this object within the database.
An alarm is identified through its type and source. These fields must be defined for this to function. This is always the case if the instance was built by the API.
See also functions Alarms.delete and Alarms.delete_by
- class c8y_api.model.Series
A wrapper for a series result.
See also: Measurements.get_series function
This class wraps the raw JSON result but can also be used to read result specs and collect result values conveniently.
See also: https://cumulocity.com/api/core/#operation/getMeasurementSeriesResource
- class SeriesSpec(unit: str, type: str, name: str)
Series specifications.
- unit: str
- type: str
- name: str
- property series
Return the complete series name.
- __init__(unit: str, type: str, name: str) None
- property truncated
Whether the result was truncated (i.e. the query returned more than 5000 values).
- property specs: Sequence[SeriesSpec]
Return specifications for all enclosed series.
- collect(series: str | Sequence[str] = None, value: str = None, timestamps: bool | str = None) List | List[tuple]
Collect series results.
- Parameters:
series (str|Sequence[str]) – Which series’ values to collect. If multiple series are collected each element in the result will be a tuple. If omitted, all available series are collected.
value (str) – Which value (min/max) to collect. If omitted, both values will be collected, grouped as 2-tuples.
timestamps (bool|str) – Whether each element in the result list will be prepended with the corresponding timestamp. If True, the timestamp string will be included; Use ‘datetime’ or ‘epoch’ to parse the timestamp string.
- Returns:
A simple list or list of tuples (potentially nested) depending on the parameter combination.
- class c8y_api.model.Subscription(c8y: CumulocityRestApi = None, name: str = None, context: str = None, source_id: str = None, api_filter: List[str] = None, type_filter: str = None, fragments: List[str] = None, non_persistent: bool = None)
Represent a Notification 2.0 subscription within the database.
Instances of this class are returned by functions of the corresponding Subscriptions API. Use this class to create new options.
See also: https://cumulocity.com/api/#tag/Subscriptions
- class ApiFilter
Notification API filter types.
- ANY = '*'
- ALARMS = 'alarms'
- ALARMS_WITH_CHILDREN = 'alarmsWithChildren'
- EVENTS = 'events'
- EVENTS_WITH_CHILDREN = 'eventsWithChildren'
- MANAGED_OBJECTS = 'managedobjects'
- MEASUREMENTS = 'measurements'
- OPERATIONS = 'operations'
- __init__(c8y: CumulocityRestApi = None, name: str = None, context: str = None, source_id: str = None, api_filter: List[str] = None, type_filter: str = None, fragments: List[str] = None, non_persistent: bool = None)
Create a new Subscription instance.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
name (str) – Subscription name
context (str) – Subscription context.
source_id (str) – Managed object ID the subscription is for.
api_filter (List[str]) – List of APIs/resources to subscribe for.
type_filter (str) – Object type the subscription is for.
non_persistent (bool) – Whether the subscription is non-persistent.
- Returns:
Subscription instance
- classmethod from_json(json: dict) Subscription
Create a Subscription instance from Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the JSON. It is used for object creation and update within Cumulocity.
- Parameters:
json (dict) – The JSON to parse.
- Returns:
A Subscription instance.
- create() Subscription
Create a new subscription within the database.
- Returns:
A fresh Subscription instance representing the created subscription within the database.
See also function Subscriptions.create which doesn’t parse the result.
- class c8y_api.model.Availability
Cumulocity availability status labels
- class ConnectionStatus
Connection status labels
- CONNECTED = 'CONNECTED'
- DISCONNECTED = 'DISCONNECTED'
- __init__()
- property last_message_date: datetime
Return the last message date as Python datetime object.
- property interval_minutes: int
Return the required update interval in minutes as integer.
- classmethod from_json(object_json: dict) Availability
Parse from Cumulocity JSON.
- Parameters:
object_json (dict) – Cumulocity JSON representation
- Returns:
A new Availability instance.
- class c8y_api.model.Fragment(name: str, **kwargs)
Represent a custom fragment within database objects.
This class is used by other classes to represent custom fragments within their data model.
For example, every measurement contains such a fragment, holding the actual data points:
"pt_current": { "CURR": { "unit": "A", "value": 50 } }
A fragment has a name (pt_current in above example) and can virtually define any substructure.
- __init__(name: str, **kwargs)
Create a new fragment.
- Parameters:
name (str) – Name of the fragment
**kwargs – Named elements of the fragment. Each element can either be a simple value of a complex substructure modelled as nested dictionary.
- has(name: str) bool
Check whether a specific element is defined.
- Parameters:
name (str) – Name of the element
- Returns:
True if the element is present, False otherwise
- class c8y_api.model.NamedObject(id: str = None, name: str = None)
Represent a named object within the database.
This class is used to model Cumulocity references.
- __init__(id: str = None, name: str = None)
Create a new instance.
- Parameters:
id (str) – Database ID of the object
name (str) – Name of the object
- classmethod from_json(object_json: dict) NamedObject
Build a new instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API. :param object_json: JSON object (nested dictionary) :type object_json: dict :param representing a named object within Cumulocity:
- Returns:
NamedObject instance
- to_json() dict
Convert the instance to JSON.
The JSON format produced by this function is what is used by the Cumulocity REST API.
- Returns:
JSON object (nested dictionary)
- class c8y_api.model.User(c8y: CumulocityRestApi = None, username: str = None, email: str = None, enabled: bool = True, display_name: str = None, password: str = None, first_name: str = None, last_name: str = None, phone: str = None, tfa_enabled: bool = None, require_password_reset: bool = None)
Represents a User object within Cumulocity.
Notes
Only a limited set of properties are actually updatable. Others must be set explicitly using the corresponding API (for example: global roles, permissions, owner, etc.)
- __init__(c8y: CumulocityRestApi = None, username: str = None, email: str = None, enabled: bool = True, display_name: str = None, password: str = None, first_name: str = None, last_name: str = None, phone: str = None, tfa_enabled: bool = None, require_password_reset: bool = None)
Create a new User instance.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete).
username (str) – The user’s username.
email (str) – The user’s email address.
enabled (bool) – Whether the user is enabled.
display_name (str) – The user’s display name
password (str) – The initial password for the user. If omitted, a newly created user will be sent a password reset link (for human users).
first_name (str) – The user’s first name.
last_name (str) – The user’s last name.
phone (str) – The user’s phone number.
tfa_enabled (bool) – Whether 2nd factor login is enabled.
require_password_reset (bool) – Whether the password must be reset by the user after the next login.
- display_name
Updatable property.
- email
Updatable property.
- phone
Updatable property.
- first_name
Updatable property.
- last_name
Updatable property.
- enabled
Updatable property.
- tfa_enabled
Updatable property.
- require_password_reset
Updatable property.
- property last_password_change: datetime
Get the last password change time.
- property last_password_change_datetime: datetime
Get the last password change time.
- classmethod from_json(json: dict) User
Create an object instance from Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the JSON. It is used for object creation and update within Cumulocity.
- Parameters:
json (dict) – The JSON to parse.
- Returns:
A CumulocityObject instance.
- create() User
Create the User within the database.
- Returns:
A fresh User object representing what was created within the database (including the ID).
- update() User
Update the User within the database.
- Returns:
A fresh User object representing what the updated state within the database (including the ID).
- delete()
Delete the User within the database.
- update_password(new_password: str)
Update the password.
This operation is executed immediately. No additional call to the
update
function required.- Parameters:
new_password (str) – The new password to set
- set_owner(user_id: str)
Set the owner for this user.
This operation is executed immediately. No additional call to the
update
function required.- Parameters:
user_id (str) – ID of the owner to set; can be None to remove a currently set owner.
- set_delegate(user_id: str)
Set the delegate for this user.
This operation is executed immediately. No additional call to the
update
function required.- Parameters:
user_id (str) – ID of the delegate to set; can be
None
to remove a currently set delegate.
- assign_global_role(role_id: str)
Assign a global role.
This operation is executed immediately. No call to
update
is required.- Parameters:
role_id (str) – Object ID of an existing global role
- unassign_global_role(role_id)
Unassign a global role.
This operation is executed immediately. No call to
update
is required.- Parameters:
role_id (str) – Object ID of an assigned global role
- retrieve_global_roles() List[GlobalRole]
Retrieve user’s global roles.
This operation is executed immediately. No call to
update
is required.- Returns:
A list of assigned global roles.
- retrieve_inventory_role_assignments()
Retrieve the user’s inventory roles.
This operation is executed immediately. No call to
update
is required.- Returns:
A list of assigned inventory roles.
- assign_inventory_roles(object_id: str | int, *roles: str | int | InventoryRole)
Assign an inventory role.
This operation is executed immediately. No call to
update
is required.- Parameters:
object_id (str) – Object ID of an existing managed object (i.e. device group)
*roles (str|int|InventoryRole) – Existing InventoryRole objects resp. the ID of existing inventory roles
- unassign_inventory_roles(*assignment_ids: str)
Unassign an inventory role.
This operation is executed immediately. No call to
update
is required.- Parameters:
*assignment_ids (str) – Object ID of existing inventory role assignments (for this user)
- class c8y_api.model.GlobalRole(c8y=None, name=None, description=None)
Represents a Global Role object within Cumulocity.
Notes
Global Roles are called ‘groups’ in the Cumulocity Standard REST API; However, ‘global roles’ is the official concept name and therefore used for consistency with the Cumulocity realm.
Only a limited set of properties are actually updatable. Others must be set explicitly using the corresponding API (for example: permissions).
See also: https://cumulocity.com/api/#tag/Groups
- __init__(c8y=None, name=None, description=None)
- name
Updatable property.
- description
Updatable property.
- classmethod from_json(json: dict) GlobalRole
Create an object instance from Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the JSON. It is used for object creation and update within Cumulocity.
- Parameters:
json (dict) – The JSON to parse.
- Returns:
A CumulocityObject instance.
- create() GlobalRole
Create the GlobalRole within the database.
- Returns:
A fresh GlobalRole object representing what was created within the database (including the ID).
- update() GlobalRole
Update the GlobalRole within the database.
- Returns:
A fresh GlobalRole object representing what the updated state within the database (including the ID).
- delete()
Delete the GlobalRole within the database.
- add_permissions(*permissions: str)
Add permissions to a global role.
This operation is executed immediately.
- Parameters:
*permissions (str) – An Iterable of permission ID
- remove_permissions(*permissions)
Remove permissions from a global role.
This operation is executed immediately.
- Parameters:
*permissions (str) – An Iterable of permission ID
- add_users(*users: str)
Add users to a global role.
This operation is executed immediately.
- Parameters:
*users (str) – An Iterable of usernames
- remove_users(*users: str)
Remove users from a global role.
This operation is executed immediately.
- Parameters:
*users (str) – An Iterable of usernames
- class c8y_api.model.Permission(level: str = '*', scope: str = '*', type: str = '*')
Represents a Permission object within Cumulocity.
Notes
Permissions are not created/deleted but only assigned to users or global roles
See also: https://cumulocity.com/api/#tag/Roles
- class Scope
Permission scopes.
- ANY = '*'
- ALARM = 'ALARM'
- AUDIT = 'AUDIT'
- EVENT = 'EVENT'
- MEASUREMENT = 'MEASUREMENT'
- MANAGED_OBJECT = 'MANAGED_OBJECT'
- OPERATION = 'OPERATION'
- __init__(level: str = '*', scope: str = '*', type: str = '*')
Create a new Permission instance.
- Parameters:
level (str) – One of ADMIN, READ, * (default)
scope (str) – One of ALARM, AUDIT, EVENT, MEASUREMENT, MANAGED_OBJECT, OPERATION, or * (default)
type (str) – Type on which to restrict or * (default)
- classmethod from_json(json: dict) Permission
Create an object instance from Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the JSON. It is used for object creation and update within Cumulocity.
- Parameters:
json (dict) – The JSON to parse.
- Returns:
A CumulocityObject instance.
- to_json(only_updated=False) dict
Create a representation of this object in Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the object. It is used for object creation and update within Cumulocity, so for example the ‘id’ field is never included.
- Parameters:
only_updated (bool) – Whether the result should be limited to changed fields only (for object updates). Default: False
- Returns:
A JSON (nested dict) object.
- class c8y_api.model.ReadPermission(scope='*', type='*')
Represents a read permission within Cumulocity.
- __init__(scope='*', type='*')
Create a new Permission instance.
- Parameters:
level (str) – One of ADMIN, READ, * (default)
scope (str) – One of ALARM, AUDIT, EVENT, MEASUREMENT, MANAGED_OBJECT, OPERATION, or * (default)
type (str) – Type on which to restrict or * (default)
- class c8y_api.model.WritePermission(scope='*', type='*')
Represents a write permission within Cumulocity.
- __init__(scope='*', type='*')
Create a new Permission instance.
- Parameters:
level (str) – One of ADMIN, READ, * (default)
scope (str) – One of ALARM, AUDIT, EVENT, MEASUREMENT, MANAGED_OBJECT, OPERATION, or * (default)
type (str) – Type on which to restrict or * (default)
- class c8y_api.model.AnyPermission(scope='*', type='*')
Represents a read/write permission within Cumulocity.
- __init__(scope='*', type='*')
Create a new Permission instance.
- Parameters:
level (str) – One of ADMIN, READ, * (default)
scope (str) – One of ALARM, AUDIT, EVENT, MEASUREMENT, MANAGED_OBJECT, OPERATION, or * (default)
type (str) – Type on which to restrict or * (default)
- class c8y_api.model.Operation(c8y=None, device_id=None, description=None, status=None, **kwargs)
Represents an instance of an operation object in Cumulocity.
Instances of this class are returned by functions of the corresponding Operation API. Use this class to create new or update existing operation.
See also: https://cumulocity.com/api/core/#tag/Operations
- class Status
Operation statuses.
- PENDING = 'PENDING'
- EXECUTING = 'EXECUTING'
- SUCCESSFUL = 'SUCCESSFUL'
- FAILED = 'FAILED'
- __init__(c8y=None, device_id=None, description=None, status=None, **kwargs)
Create a new Operation object.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
device_id (str) – Device ID which this operation is for
kwargs – All additional named arguments are interpreted as custom fragments e.g. for data points.
- Returns:
Operation object
- description
Updatable property.
- status
Updatable property.
- property creation_datetime: datetime
Convert the operation’s creation time to a Python datetime object.
- Returns:
Standard Python datetime object for the operation’s creation time.
- classmethod from_json(json) Operation
Build a new Operation instance from Cumulocity JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing an operation within Cumulocity
- Returns:
Operation object
- to_json(only_updated: bool = False) dict
Create a representation of this object in Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the object. It is used for object creation and update within Cumulocity, so for example the ‘id’ field is never included.
- Parameters:
only_updated (bool) – Whether the result should be limited to changed fields only (for object updates). Default: False
- Returns:
A JSON (nested dict) object.
- property datetime: Type[datetime] | None
Convert the measurement’s time to a Python datetime object.
- Returns:
The measurement’s time
- Return type:
(datetime)
- class c8y_api.model.BulkOperation(c8y=None, group_id: str = None, failed_parent_id: str = None, start_time: str | datetime = None, creation_ramp: float = None, operation_prototype: dict = None, **kwargs)
Represents an instance of a bulk operation object in Cumulocity.
Instances of this class are returned by functions of the corresponding Bulk Operation API. Use this class to create new or update existing operation.
See also: https://cumulocity.com/api/core/#tag/Bulk-operations
- class Status
Bulk Operation statuses.
- ACTIVE = 'ACTIVE'
- IN_PROGRESS = 'IN_PROGRESS'
- COMPLETED = 'COMPLETED'
- DELETED = 'DELETED'
- class GeneralStatus
Bulk Operation general statuses.
- SCHEDULED = 'PENDING'
- EXECUTING = 'EXECUTING'
- EXECUTING_WITH_ERRORS = 'EXECUTING_WITH_ERRORS'
- SUCCESSFUL = 'SUCCESSFUL'
- FAILED = 'FAILED'
- CANCELED = 'CANCELED'
- COMPLETED_SUCCESSFULLY = 'COMPLETED SUCCESSFULLY'
- COMPLETED_WITH_FAILURES = 'COMPLETED WITH FAILURES'
- __init__(c8y=None, group_id: str = None, failed_parent_id: str = None, start_time: str | datetime = None, creation_ramp: float = None, operation_prototype: dict = None, **kwargs)
Create a new Operation object.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
device_id (str) – Device ID which this operation is for
kwargs – All additional named arguments are interpreted as custom fragments e.g. for data points.
- Returns:
Operation object
- group_id
Updatable property.
- failed_parent_id
Updatable property.
- start_time
Updatable property.
- creation_ramp
Updatable property.
- property operation_prototype: _DictWrapper
- property start_datetime: datetime
Convert the operation’s start time to a Python datetime object.
- Returns:
Standard Python datetime object for the operation’s start time.
- classmethod from_json(json) BulkOperation
Build a new Operation instance from Cumulocity JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing an operation within Cumulocity
- Returns:
Operation object
- create() BulkOperation
Store the Bulk Operation within the database.
- Returns: A fresh BulkOperation object representing what was
created within the database (including the ID).
- update() BulkOperation
Update the BulkOperation within the database.
- Returns: A fresh BulkOperation object representing the updated
object within the database (including the ID).
- class c8y_api.model.Application(c8y: CumulocityRestApi = None, name: str = None, key: str = None, type: str = None, availability: str = None, context_path: str = None, manifest: dict = None, roles: List[str] = None, required_roles: List[str] = None, breadcrumbs: bool = None, content_security_policy: str = None, dynamic_options_url: str = None, global_title: str = None, legacy: bool = None, right_drawer: bool = None, upgrade: bool = None)
Represent an instance of an application object in Cumulocity.
Instances of this class are returned by functions of the corresponding API. Use this class to create new or update objects.
See also: https://cumulocity.com/api/#tag/Application-API
- EXTERNAL_TYPE = 'EXTERNAL'
- HOSTED_TYPE = 'HOSTED'
- MICROSERVICE_TYPE = 'MICROSERVICE'
- PRIVATE_AVAILABILITY = 'PRIVATE'
- MARKET_AVAILABILITY = 'MARKET'
- __init__(c8y: CumulocityRestApi = None, name: str = None, key: str = None, type: str = None, availability: str = None, context_path: str = None, manifest: dict = None, roles: List[str] = None, required_roles: List[str] = None, breadcrumbs: bool = None, content_security_policy: str = None, dynamic_options_url: str = None, global_title: str = None, legacy: bool = None, right_drawer: bool = None, upgrade: bool = None)
Create a new Application object.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
name (str) – Name of the application
key (str) – Key to identify the application
type (str) – Type of the application
availability (str) – Application access level for tenants
context_path (str) – The path where the application is accessible
manifest (dict) – Microservice or web application manifest
roles (str) – List of roles provided by the application
required_roles (str) – List of roles required by the application
breadcrumbs (bool) – Whether the (web) application uses breadcrumbs
content_security_policy (str) – The content security policy of the application
dynamic_options_url (str) – A URL to a JSON object with dynamic content options
global_title (str) – The global title of the application
legacy (bool) – Whether the (web) application is of legacy type
right_drawer (bool) – Whether the (web) application uses the right hand context menu
upgrade (bool) – Whether the (web) application uses both Angular and AngularJS
- name
Updatable property.
- type
Updatable property.
- key
Updatable property.
- availability
Updatable property.
- context_path
Updatable property.
- roles
Updatable property.
- required_roles
Updatable property.
- breadcrumbs
Updatable property.
- content_security_policy
Updatable property.
- dynamic_options_url
Updatable property.
- global_title
Updatable property.
- legacy
Updatable property.
- right_drawer
Updatable property.
- upgrade
Updatable property.
- classmethod from_json(json: dict) Application
Create an object instance from Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the JSON. It is used for object creation and update within Cumulocity.
- Parameters:
json (dict) – The JSON to parse.
- Returns:
A CumulocityObject instance.
- create() Application
Create the Application within the database.
- Returns:
A fresh Application object representing what was created within the database (including the ID).
- update() Application
Update the Application within the database.
Note: This will only send changed fields to increase performance.
- Returns:
A fresh Application object representing what the updated state within the database (including the ID).
- delete()
Delete the Application within the database.
- class c8y_api.model.TenantOption(c8y: CumulocityRestApi = None, category: str = None, key: str = None, value: str = None)
Represent a tenant option within the database.
Instances of this class are returned by functions of the corresponding Tenant Option API. Use this class to create new or update options.
See also https://cumulocity.com/guides/latest/reference/tenants/#option
- __init__(c8y: CumulocityRestApi = None, category: str = None, key: str = None, value: str = None)
Create a new TenantOption instance.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
category (str) – Option category
key (str) – Option key (name)
value (str) – Option value
- Returns:
TenantObject instance
- value
Updatable property.
- classmethod from_json(json: dict) TenantOption
Build a new TenantOption instance from JSON.
The JSON is assumed to be in the format as it is used by the Cumulocity REST API.
- Parameters:
json (dict) – JSON object (nested dictionary) representing a tenant option within Cumulocity
- Returns:
TenantOption object
- create() TenantOption
Create a new representation of this option within the database.
- Returns:
A fresh TenantOption instance representing the created option within the database.
See also function TenantOptions.create which doesn’t parse the result.
- update() TenantOption
Write changes to the database.
- Returns:
A fresh TenantOption instance representing the updated object within the database.
See also function TenantOptions.update which doesn’t parse the result.
- delete() None
Delete the option within the database.
See also function TenantOptions.delete to delete multiple objects.
- class c8y_api.model.AuditRecord(c8y: CumulocityRestApi = None, type: str = None, time: str | datetime = None, source: str = None, activity: str = None, text: str = None, severity: str = None, application: str = None, user: str = None, **kwargs)
Represents an Audit Record object within Cumulocity.
Instances of this class are returned by functions of the corresponding Audits API. Use this class to create new or update AuditRecord objects.
See also: https://cumulocity.com/api/core/#tag/Audits
- class Severity
Audit severity levels.
- MAJOR = 'MAJOR'
- CRITICAL = 'CRITICAL'
- MINOR = 'MINOR'
- WARNING = 'WARNING'
- INFORMATION = 'information'
- __init__(c8y: CumulocityRestApi = None, type: str = None, time: str | datetime = None, source: str = None, activity: str = None, text: str = None, severity: str = None, application: str = None, user: str = None, **kwargs)
Create a new AuditRecord object.
- Parameters:
c8y (CumulocityRestApi) – Cumulocity connection reference; needs to be set for direct manipulation (create, delete)
type (str) – Audit records type
time (str|datetime) – Date/time of the audit records Can be provided as timezone-aware datetime object or formatted string (in standard ISO format incl. timezone: YYYY-MM-DD’T’HH:MM:SS.SSSZ as it is returned by the Cumulocity REST API). Use ‘now’ to set to current datetime in UTC.
source (str) – The managed object ID to which the audit is associated
activity (str) – Summary of the action that was carried out
text (str) – Details of the action that was carried out
severity (str) – Severity of the audit record.
application (str) – The application from which the record was created.
user (str) – The user who carried out the activity
kwargs – Additional arguments are treated as custom fragments
- property datetime: datetime
Convert the audit record’s time to a Python datetime object.
- Returns:
Standard Python datetime object
- property creation_datetime: datetime
Convert the audit record’s creation time to a Python datetime object.
- Returns:
Standard Python datetime object
- classmethod from_json(json: dict) AuditRecord
Create an object instance from Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the JSON. It is used for object creation and update within Cumulocity.
- Parameters:
json (dict) – The JSON to parse.
- Returns:
A CumulocityObject instance.
- to_json(only_updated: bool = False) dict
Create a representation of this object in Cumulocity JSON format.
Caveat: this function is primarily for internal use and does not return a full representation of the object. It is used for object creation and update within Cumulocity, so for example the ‘id’ field is never included.
- Parameters:
only_updated (bool) – Whether the result should be limited to changed fields only (for object updates). Default: False
- Returns:
A JSON (nested dict) object.
- create() AuditRecord
Create the AuditRecord within the database.
- Returns:
A fresh AuditRecord object representing what was created within the database (including the ID).
Measurement Additions
The Cumulocity Python API’s measurements API (see also classes
Measurements
and Measurement
) includes the following additions
to allow easy creation of standard measurement values including units.
Effectively, each of the value classes represent a value fragment, e.g. Celsius
:
{"unit": "°C", "value": 22.8}
These values can easily be combined, e.g. when constructing a measurement:
m = Measurement(type='cx_LevelMeasurement', source=device_id, time='now',
cx_Levels={
'oil': Liters(8.4),
'gas': Liters(223.18),
'h2o': Liters(1.2),
'bat': Percentage(85)
})
- class c8y_api.model.Units
Predefined, common units.
- Grams = 'g'
- Kilograms = 'kg'
- Kelvin = 'K'
- Celsius = '°C'
- Fahrenheit = '°F'
- Meters = 'm'
- Centimeters = 'cm'
- Millimeters = 'mm'
- Liters = 'l'
- CubicMeters = 'm3'
- Count = '#'
- Percent = '%'
- class c8y_api.model.Celsius(value)
Temperature datapoint (Celsius).
- class c8y_api.model.Centimeters(value)
Length datapoint (Centimeters).
- class c8y_api.model.Count(value)
Discrete number datapoint (number/count).
- class c8y_api.model.CubicMeters(value)
Volume datapoint (Cubic Meters).
- class c8y_api.model.Grams(value)
Weight datapoint (Grams).
- class c8y_api.model.Kelvin(value)
Temperature datapoint (Kelvin).
- class c8y_api.model.Kilograms(value)
Weight datapoint (Kilograms).
- class c8y_api.model.Liters(value)
Volume datapoint (Liters).
- class c8y_api.model.Meters(value)
Length datapoint (Meters).
- class c8y_api.model.Percentage(value)
Percent value datapoint.
- class c8y_api.model.Value(value, unit)
Generic datapoint.