### Install cognite-sdk with optional dependencies Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/index.rst Install the cognite-sdk with optional dependencies like pandas and geo. ```bash pip install "cognite-sdk[pandas, geo]" ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Clone the SDK repository and install all dependencies using poetry. This sets up the project and its virtual environment. ```bash git clone https://github.com/cognitedata/cognite-sdk-python cd cognite-sdk-python ``` ```bash poetry install -E all poetry env activate ``` -------------------------------- ### Install Core Cognite SDK Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/README.md Installs the core version of the cognite-sdk package using pip. This is for users who do not require any optional dependencies. ```bash pip install cognite-sdk ``` -------------------------------- ### Install cognite-sdk with pip Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/index.rst Use this command to install or upgrade the cognite-sdk package using pip. ```bash pip install --upgrade cognite-sdk ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Install pre-commit hooks to ensure code quality and consistency by running checks on every commit. ```bash pre-commit install ``` -------------------------------- ### Install cognite-sdk with uv Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/index.rst Use this command to add the cognite-sdk package to your project using uv. ```bash uv add cognite-sdk ``` -------------------------------- ### Install cognite-sdk with poetry Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/index.rst Use this command to add the cognite-sdk package to your project using poetry. ```bash poetry add cognite-sdk ``` -------------------------------- ### Install and Use Custom Event Loop (uvloop) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/settings.rst Substitute Python's default asyncio event loop with a custom implementation like uvloop by installing a custom loop policy before the first API call. ```python import uvloop uvloop.install() # equivalent to asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) from cognite.client import CogniteClient client = CogniteClient(...) # background loop will now be a uvloop ``` -------------------------------- ### Initialize CogniteClient with Default Configuration Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Creates a CogniteClient instance using default configurations. This method is suitable for basic setups where default URLs and authentication methods are acceptable. ```python from cognite.client import CogniteClient from cognite.client.credentials import Token # Example using default configuration client = CogniteClient.default(project="my-project", cdf_cluster="us") ``` -------------------------------- ### Install Cognite SDK with Pandas and Geo extras using pip Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/extensions_and_optional_dependencies.rst Install the Cognite SDK with specific optional dependencies like pandas and geo using pip. This command ensures that libraries required for enhanced data manipulation and geospatial analysis are included. ```bash $ pip install "cognite-sdk[pandas, geo]" ``` -------------------------------- ### Get Client Configuration Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Returns the configuration object associated with the current client instance. ```python @property def config(self) -> ClientConfig: """Returns a config object containing the configuration for the current client. Returns: ClientConfig: The configuration object. """ return self.__async_client._config ``` -------------------------------- ### Install Cognite SDK with Pandas and Geo extras using Poetry Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/extensions_and_optional_dependencies.rst Add the Cognite SDK to your project using Poetry, specifying optional features such as pandas and geo. This command manages dependencies and enables the use of these extended functionalities within your application. ```bash $ poetry add cognite-sdk -E pandas -E geo ``` -------------------------------- ### Synchronous HTTP GET Request Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Performs a synchronous GET request to a specified API path. This method wraps the asynchronous client's GET request. ```python def get( self, url: str, params: dict[str, Any] | None = None, headers: dict[str, Any] | None = None, ) -> CogniteHTTPResponse: """Perform a GET request to an arbitrary path in the API.""" return run_sync(self.__async_client.get(url, params=params, headers=headers)) ``` -------------------------------- ### Get Asynchronous Client Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Returns the underlying asynchronous Cognite client instance. ```python def get_async_client(self) -> AsyncCogniteClient: """Returns the underlying async client. Returns: AsyncCogniteClient: The async client instance. """ return self.__async_client ``` -------------------------------- ### Start Vision Extraction Job Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/contextualization.rst Initiates an asynchronous job to extract features like asset tag and people detection from image files in CDF. Requires importing CogniteClient and VisionFeature. ```python from cognite.client import CogniteClient from cognite.client.data_classes.contextualization import VisionFeature client = CogniteClient() extract_job = client.vision.extract( features=[VisionFeature.ASSET_TAG_DETECTION, VisionFeature.PEOPLE_DETECTION], file_ids=[1, 2], ) ``` -------------------------------- ### Get SDK Version Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Retrieves the current version of the Cognite Python SDK. ```python @property def version(self) -> str: """Returns the current SDK version. Returns: str: The current SDK version """ from cognite.client import __version__ return __version__ ``` -------------------------------- ### Instantiate Client from Configuration File (YAML) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/quickstart.rst Use this code to instantiate a client using a configuration file. The SDK supports loading configurations from YAML or JSON strings, allowing for flexible credential management. Ensure sensitive information like API keys and tenant IDs are handled securely, preferably through environment variables. ```yaml # cognite-sdk-config.yaml client: project: "my-project" client_name: "my-special-client" base_url: "https://${MY_CLUSTER}.cognitedata.com" credentials: client_credentials: token_url: "https://login.microsoftonline.com/${MY_TENANT_ID}/oauth2/v2.0/token" client_id: "${MY_CLIENT_ID}" client_secret: "${MY_CLIENT_SECRET}" scopes: ["https://api.cognitedata.com/.default"] global: max_retries: 10 max_retry_backoff: 10 ``` ```python import os from pathlib import Path from string import Template import yaml from cognite.client import CogniteClient, global_config file_path = Path("cognite-sdk-config.yaml") # Read in yaml file and substitute environment variables in the file string env_sub_template = Template(file_path.read_text()) file_env_parsed = env_sub_template.substitute(dict(os.environ)) # Load yaml file string into a dictionary to parse global and client configurations cognite_config = yaml.safe_load(file_env_parsed) # If you want to set a global configuration it must be done before creating the client global_config.apply_settings(cognite_config["global"]) client = CogniteClient.load(cognite_config["client"]) ``` -------------------------------- ### Initialize Client with Configuration Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/settings.rst Instantiate an AsyncCogniteClient or CogniteClient by passing a ClientConfig object. This allows for custom settings like base URL, project, cluster, and credentials. ```python from cognite.client import AsyncCogniteClient, CogniteClient, ClientConfig from cognite.client.credentials import Token my_config = ClientConfig( client_name="my-client", project="myproj", cluster="westeurope-1", # or pass the full 'base_url' credentials=Token("verysecret"), ) # Async client (recommended for new code) async_client = AsyncCogniteClient(my_config) # Sync client (for backward compatibility) sync_client = CogniteClient(my_config) ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Build the HTML documentation files locally by navigating to the 'docs' directory and running the 'make html' command. ```bash cd docs make html ``` -------------------------------- ### Async and Sync Client Initialization Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/index.rst Demonstrates how to initialize both the new asynchronous client (AsyncCogniteClient) and the traditional synchronous client (CogniteClient). The async client is new in v8 and enables native async/await patterns. ```python # Async client (new in v8!) from cognite.client import AsyncCogniteClient async def main(): client = AsyncCogniteClient() tss = await client.time_series.list() # Sync client (still supported) from cognite.client import CogniteClient client = CogniteClient() tss = client.time_series.list() ``` -------------------------------- ### Initialize CogniteClient with Client Credentials Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Demonstrates initializing the CogniteClient using a configuration dictionary with client credentials. Ensure the OAUTH_CLIENT_SECRET environment variable is set. ```python from cognite.client import CogniteClient import os config = { "client_name": "abcd", "project": "cdf-project", "base_url": "https://api.cognitedata.com/", "credentials": { "client_credentials": { "client_id": "abcd", "client_secret": os.environ["OAUTH_CLIENT_SECRET"], "token_url": "https://login.microsoftonline.com/xyz/oauth2/v2.0/token", "scopes": ["https://api.cognitedata.com/.default"], }}, }, } client = CogniteClient.load(config) ``` -------------------------------- ### Instantiate Async Client Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/quickstart.rst Initialize an asynchronous Cognite client for use with async/await syntax. This is recommended for web applications and concurrent operations. ```python import asyncio from cognite.client import AsyncCogniteClient, ClientConfig from cognite.client.credentials import OAuthClientCredentials import os # Configuration is the same as for the sync client creds = OAuthClientCredentials( token_url="https://login.microsoftonline.com//oauth2/v2.0/token", client_id="my-client-id", client_secret=os.environ["MY_CLIENT_SECRET"], scopes=["https://api.cognitedata.com/.default"] ) cnf = ClientConfig( client_name="my-async-client", base_url="https://api.cognitedata.com", project="my-project", credentials=creds ) async def main(): client = AsyncCogniteClient(cnf) # All API methods are now awaitable assets = await client.assets.list(limit=10) # Run concurrent operations with asyncio.gather ts_task = client.time_series.list(limit=10) events_task = client.events.list(limit=10) time_series, events = await asyncio.gather(ts_task, events_task) asyncio.run(main()) ``` -------------------------------- ### Sync Instances to SQLite Database Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/data_modeling/instances.rst Demonstrates using the `subscribe` method to create a live, local replica of instances from a specific space in a SQLite database. It includes setting up the database schema, retrieving existing cursors, defining a query, and processing incoming data batches. ```python import asyncio import json import sqlite3 from typing import Optional from cognite.client import AsyncCogniteClient from cognite.client.config import ClientConfig from cognite.client.data_classes.data_modeling import ( QueryResult, QuerySync, NodeResultSetExpressionSync, SelectSync, SubscriptionContext, ) from cognite.client.data_classes.filters import Equals def sqlite_connection(db_name: str) -> sqlite3.Connection: return sqlite3.connect(db_name) def bootstrap_sqlite(db_name: str) -> None: """Sets up the initial database schema if it doesn't exist.""" with sqlite_connection(db_name) as connection: connection.execute( """ CREATE TABLE IF NOT EXISTS instance ( space TEXT, external_id TEXT, data JSON, PRIMARY KEY(space, external_id) ) """ ) connection.execute( """ CREATE TABLE IF NOT EXISTS cursor ( space TEXT PRIMARY KEY, cursor TEXT ) """ ) connection.commit() async def sync_space_to_sqlite( async_client: AsyncCogniteClient, db_name: str, space_to_sync: str ) -> SubscriptionContext: """ Sets up and starts a subscription to sync a space to a local SQLite database. """ # 1. Read the last known cursor from the database. # This is a blocking call, so we run it in a thread. def _get_cursor() -> Optional[str]: with sqlite_connection(db_name) as connection: result = connection.execute( "SELECT cursor FROM cursor WHERE space = ?", (space_to_sync,) ).fetchone() if result: print(f"Found existing cursor for space {space_to_sync!r}") return result[0] return None existing_cursor = await asyncio.to_thread(_get_cursor) query = QuerySync( with_={ "nodes": NodeResultSetExpressionSync( filter=Equals(property=["node", "space"], value=space_to_sync) ) }, select={"nodes": SelectSync()}, cursors={"nodes": existing_cursor}, ) # 2. Define the callback that will process each batch of results. # The callback itself does not have to be async, but it is preferable. async def _sync_batch_to_sqlite(result: QueryResult) -> None: def _write_to_db() -> tuple[int, int]: # 3. Prepare all data in memory before opening the database # connection to minimize lock time. inserts, deletes = [], [] for node in result["nodes"]: if node.deleted_time is None: inserts.append( (node.space, node.external_id, json.dumps(node.dump())) ) else: deletes.append((node.space, node.external_id)) ``` -------------------------------- ### CogniteClient.default Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Creates a CogniteClient instance with default configurations. It uses the provided project, cluster, credentials, and an optional client name to set up the client. ```APIDOC ## CogniteClient.default ### Description Creates a CogniteClient instance with default configurations. It uses the provided project, cluster, credentials, and an optional client name to set up the client. ### Method ```python CogniteClient.default(project: str, cdf_cluster: str, credentials: CredentialProvider, client_name: str | None = None) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **project** (str) - Required - The CDF project. * **cdf_cluster** (str) - Required - The CDF cluster where the CDF project is located. * **credentials** (CredentialProvider) - Required - Credentials. e.g. Token, ClientCredentials. * **client_name** (str | None) - Optional - A user-defined name for the client. Used to identify the number of unique applications/scripts running on top of CDF. If this is not set, the getpass.getuser() is used instead, meaning the username you are logged in with is used. ### Returns CogniteClient: An CogniteClient instance with default configurations. ``` -------------------------------- ### Wait for Vision Job Completion and Get Results Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/contextualization.rst Waits for an initiated Vision extraction job to complete and retrieves the prediction results. The results can then be processed. ```python extract_job.wait_for_completion() for item in extract_job.items: predictions = item.predictions # do something with the predictions ``` -------------------------------- ### Set Global Client Configuration Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/settings.rst Configure default client settings globally using `global_config.default_client_config`. These settings must be applied before client instantiation to take effect. Includes options for disabling checks, gzip, SSL, and setting retry parameters. ```python from cognite.client import global_config, ClientConfig from cognite.client.credentials import Token global_config.default_client_config = ClientConfig( client_name="my-client", project="myproj", cluster="westeurope-1", # or pass the full 'base_url' credentials=Token("verysecret"), ) global_config.disable_pypi_version_check = True global_config.disable_gzip = False global_config.disable_ssl = False global_config.max_retries = 10 global_config.max_retry_backoff = 10 global_config.max_connection_pool_size = 10 global_config.status_forcelist = {429, 502, 503, 504} ``` -------------------------------- ### Run Unit Tests Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Initiate unit tests by running pytest from the root directory. Ensure you have the necessary credentials configured. ```bash pytest tests/tests_unit ``` -------------------------------- ### Configure Global Client Settings Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/quickstart.rst Set up global client configuration using OAuth credentials. This is useful for applications that need to authenticate with CDF using OAuth. Ensure sensitive information like client secrets are loaded from environment variables. ```python from cognite.client import CogniteClient, ClientConfig, global_config from cognite.client.credentials import OAuthClientCredentials import os # This value will depend on the cluster your CDF project runs on cluster = "api" base_url = f"https://{cluster}.cognitedata.com" tenant_id = "my-tenant-id" client_id = "my-client-id" # client secret should not be stored in-code, so we load it from an environment variable client_secret = os.environ["MY_CLIENT_SECRET"] creds = OAuthClientCredentials( token_url=f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token", client_id=client_id, client_secret=client_secret, scopes=[f"{base_url}/.default"] ) cnf = ClientConfig( client_name="my-special-client", base_url=base_url, project="my-project", credentials=creds ) global_config.default_client_config = cnf client = CogniteClient() ``` -------------------------------- ### Simulators API Entry Point Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/simulators.rst Access the Simulators API module through the AsyncCogniteClient. ```APIDOC ## Accessing the Simulators API To interact with simulator functionalities, use the `simulators` attribute of the `AsyncCogniteClient`. ### Method Signature ```python AsyncCogniteClient.simulators ``` ### Description This provides an entry point to all simulator-related operations, including managing integrations, models, routines, runs, and logs. ``` -------------------------------- ### Run Code Generation Script (Verify Mode) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Use the `verify` mode of the code generation script to ensure all sync source code files are up-to-date and check for stale files. This is primarily for CI. ```sh python scripts/sync_client_codegen/main.py verify ``` -------------------------------- ### List Spaces (Sync) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/quickstart.rst Synchronously list all available spaces in your Data Modeling project. This uses a standard CogniteClient. ```python from cognite.client import CogniteClient client = CogniteClient() spaces = client.data_modeling.spaces.list(limit=None) ``` -------------------------------- ### List Spaces (Async) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/quickstart.rst Asynchronously list all available spaces in your Data Modeling project. This requires an AsyncCogniteClient. ```python from cognite.client import AsyncCogniteClient async def list_spaces(): client = AsyncCogniteClient() spaces = await client.data_modeling.spaces.list(limit=None) ``` -------------------------------- ### Create Default CogniteClient Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Factory method to create a CogniteClient with default configuration, including base URL derived from project and cluster. ```python @classmethod def default( cls, project: str, cdf_cluster: str, credentials: CredentialProvider, client_name: str | None = None, ) -> CogniteClient: """ Create an CogniteClient with default configuration. The default configuration creates the URLs based on the project and cluster: * Base URL: ``"https://{{cdf_cluster}}.cognitedata.com/"`` ``` -------------------------------- ### Client Configuration Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/cognite_client.rst Both asynchronous and synchronous clients share the same configuration options, managed via the ClientConfig class. ```APIDOC ## Client Configuration Both `AsyncCogniteClient` and `CogniteClient` share the same configuration via :ref:`ClientConfig `. ### ClientConfig .. autoclass:: cognite.client.config.ClientConfig :members: :member-order: bysource ### GlobalConfig .. autoclass:: cognite.client.config.GlobalConfig :members: :member-order: bysource ``` -------------------------------- ### Configure Environment Variables for Testing Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Set essential environment variables in a .env file for integration tests. This includes client name, project, base URL, and authentication flow details. ```bash COGNITE_CLIENT_NAME=python-sdk-integration-tests- COGNITE_PROJECT=python-sdk-contributor COGNITE_BASE_URL=https://api.cognitedata.com LOGIN_FLOW=interactive COGNITE_TOKEN_SCOPES=https://api.cognitedata.com/.default COGNITE_AUTHORITY_URL=https://login.microsoftonline.com/dff7763f-e2f5-4ffd-9b8a-4ba4bafba5ea COGNITE_CLIENT_ID=6b0b4266-ffa4-4b9b-8e13-ddbbc8a19ea6 ``` ```bash # 2) Client credentials flow. To run tests which require client credentials to be set # (such as transformations). #LOGIN_FLOW=client_credentials #COGNITE_TOKEN_SCOPES=https://api.cognitedata.com/.default #COGNITE_TOKEN_URL=https://login.microsoftonline.com/dff7763f-e2f5-4ffd-9b8a-4ba4bafba5ea/oauth2/v2.0/token #COGNITE_CLIENT_ID=6b0b4266-ffa4-4b9b-8e13-ddbbc8a19ea6 #COGNITE_CLIENT_SECRET=... ``` ```bash # 3) Client certificate flow. To run with client certificate auth. #LOGIN_FLOW=client_certificate #COGNITE_TOKEN_SCOPES=https://api.cognitedata.com/.default #COGNITE_AUTHORITY_URL=https://login.microsoftonline.com/dff7763f-e2f5-4ffd-9b8a-4ba4bafba5ea #COGNITE_CLIENT_ID=14fd282e-f77a-457d-add5-928ec2bcbf04 #COGNITE_CERT_THUMBPRINT=... #COGNITE_CERTIFICATE=aadappcert.pem ``` -------------------------------- ### Initialize CogniteClient with Client Credentials Flow Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Creates a CogniteClient using OAuth client credentials for authentication with Azure Active Directory (Entra ID). This is ideal for service-to-service authentication. ```python from cognite.client import CogniteClient client = CogniteClient.default_oauth_client_credentials( project="my-project", cdf_cluster="us", tenant_id="my-tenant-id", client_id="my-client-id", client_secret="my-client-secret", ) ``` -------------------------------- ### Run Code Generation Script (Run Mode) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Use the `run` mode to update sync source code files from async source files. Specify files individually or use `--all-files` to process all files and perform cleanup. ```sh python scripts/sync_client_codegen/main.py run --files FILE1 FILE2 ... ``` ```sh python scripts/sync_client_codegen/main.py run --all-files ``` -------------------------------- ### Load CogniteClient Configuration from Dictionary Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Loads a CogniteClient configuration from a Python dictionary. This allows for dynamic configuration loading based on application needs. ```python from cognite.client import CogniteClient config_dict = { "project": "my-project", "cdf_cluster": "us", "client_name": "my-client", "credentials": { "type": "token", "token": "my-secret-token" } } client = CogniteClient.load(config_dict) ``` -------------------------------- ### Accessing Unit Systems Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/unit_catalog.rst Allows retrieval and management of unit systems. ```APIDOC ## Accessing Unit Systems ### Description This object provides access to unit system functionalities. ### Method `AsyncCogniteClient.units.systems` ### Endpoint N/A (SDK method) ### Parameters None ``` -------------------------------- ### Accessing Sequences Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/sequences.rst This section covers how to access the sequences client object, which is the entry point for all sequence-related operations. ```APIDOC ## Accessing Sequences ### Description Provides access to the sequences client for managing sequence metadata and data. ### Method Attribute access on the Cognite client object. ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```python # Assuming 'client' is an initialized CogniteClient instance sequences_client = client.sequences ``` ### Response An object representing the Sequences API client. ``` -------------------------------- ### Run Integration Tests Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Execute integration tests using pytest. This requires appropriate credentials to be set up in the environment. ```bash pytest tests/tests_integration ``` -------------------------------- ### Initialize CogniteClient with Interactive OAuth Flow Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Creates a CogniteClient using the interactive OAuth flow for authentication with Azure Active Directory (Entra ID). This method is suitable for user-driven applications where interactive login is required. ```python from cognite.client import CogniteClient client = CogniteClient.default_oauth_interactive( project="my-project", cdf_cluster="us", tenant_id="my-tenant-id", client_id="my-client-id", ) ``` -------------------------------- ### CogniteClient.load Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Loads a CogniteClient object from a configuration dictionary or a YAML/JSON string. This allows for flexible client initialization using pre-defined settings. ```APIDOC ## CogniteClient.load ### Description Load a cognite client object from a YAML/JSON string or dict. This allows for flexible client initialization using pre-defined settings. ### Method ```python CogniteClient.load(config: dict[str, Any] | str) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **config** (dict[str, Any] | str) - Required - A dictionary or YAML/JSON string containing configuration values defined in the CogniteClient class. ### Returns CogniteClient: A cognite client object. ### Examples Create a cognite client object from a dictionary input: ```python client_config = { "project": "my-project", "cdf_cluster": "api", "client_id": "my-client-id", "client_secret": "my-client-secret", "tenant_id": "my-tenant-id" } client = CogniteClient.load(client_config) ``` ``` -------------------------------- ### Synchronous CogniteClient Initialization Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Initializes the synchronous CogniteClient, which internally uses an asynchronous client. This is where all synchronous API clients are instantiated. ```python class CogniteClient: """Main entrypoint into the Cognite Python SDK. All Cognite Data Fusion APIs are accessible through this synchronous client. For the asynchronous client, see :class:`~cognite.client._cognite_client.AsyncCogniteClient`. Args: config (ClientConfig | None): The configuration for this client. """ def __init__(self, config: ClientConfig | None = None) -> None: self.__async_client = async_client = AsyncCogniteClient(config) # Initialize all sync. APIs: {nested_apis_init} ``` -------------------------------- ### Run Documentation Tests Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Execute all tests defined within the documentation, including those using the sphinx doctest extension and pytest fixtures. ```bash pytest docs ``` -------------------------------- ### Enable Debug Logging for Client Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/settings.rst Instantiate a CogniteClient with debug logging enabled to inspect HTTP requests, responses, and retry behavior. Debug logging can also be toggled dynamically. ```python from cognite.client import CogniteClient, ClientConfig from cognite.client.credentials import Token client = CogniteClient( ClientConfig( client_name="my-client", project="myproj", cluster="api", # or pass the full 'base_url' credentials=Token("verysecret"), debug=True, ) ) print(client.config.debug) # True, requests, responses, and retries are logged to stderr client.config.debug = False # disable debug logging client.config.debug = True # enable debug logging again ``` -------------------------------- ### CogniteClient.default_oauth_client_credentials Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Initializes a CogniteClient using the client credentials flow for OAuth. This method sets up default URLs and scopes based on the provided Azure tenant and client information. ```APIDOC ## CogniteClient.default_oauth_client_credentials ### Description Create an CogniteClient with default configuration using a client credentials flow. The default configuration creates the URLs based on the project and cluster. ### Method ```python CogniteClient.default_oauth_client_credentials(project: str, cdf_cluster: str, tenant_id: str, client_id: str, client_secret: str, client_name: str | None = None) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **project** (str) - Required - The CDF project. * **cdf_cluster** (str) - Required - The CDF cluster where the CDF project is located. * **tenant_id** (str) - Required - The Azure tenant ID. * **client_id** (str) - Required - The Azure client ID. * **client_secret** (str) - Required - The Azure client secret. * **client_name** (str | None) - Optional - A user-defined name for the client. Used to identify the number of unique applications/scripts running on top of CDF. If this is not set, the getpass.getuser() is used instead, meaning the username you are logged in with is used. ### Returns CogniteClient: An CogniteClient instance with default configurations. ### Configuration Details * Base URL: ``"https://{{cdf_cluster}}.cognitedata.com/"`` * Token URL: ``"https://login.microsoftonline.com/{{tenant_id}}/oauth2/v2.0/token"`` * Scopes: ``[f"https://{{cdf_cluster}}.cognitedata.com/.default"]`` ``` -------------------------------- ### CogniteMissingClientError Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/exceptions.rst Exception raised when the Cognite client is not properly initialized. ```APIDOC ## CogniteMissingClientError ### Description Raised when an operation is attempted before the Cognite client has been successfully initialized with the necessary credentials and configuration. This indicates that the SDK is not ready to communicate with the Cognite API. ### Usage ```python try: # If client is not initialized, this might be raised cognite_client.assets.list() except cognite.client.exceptions.CogniteMissingClientError as e: print(f"Client not initialized: {e}") ``` ``` -------------------------------- ### Transformations API Entry Point Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/transformations.rst The main entry point for accessing all transformations-related functionalities. ```APIDOC ## Transformations API This API provides access to all transformation-related functionalities. ### Method Access via `client.transformations` ### Endpoint N/A (SDK method) ### Description Use this to interact with transformations, schedules, notifications, jobs, and schema definitions. ``` -------------------------------- ### Custom Token Provider Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/quickstart.rst Create a custom token provider for the client configuration. This allows for dynamic token generation or retrieval. ```python from cognite.client import CogniteClient, ClientConfig from cognite.client.credentials import Token def token_provider(): ... # Your token retrieval logic here cnf = ClientConfig( client_name="my-special-client", base_url="https://.cognitedata.com", project="my-project", credentials=Token(token_provider) ) client = CogniteClient(cnf) ``` -------------------------------- ### Simulator Models Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/simulators.rst Manage simulator models and their revisions using the `models` submodule. ```APIDOC ## Simulator Models The `models` submodule is used for managing simulator models. ### Access ```python AsyncCogniteClient.simulators.models ``` ### Description This module provides functionalities for creating, retrieving, updating, and deleting simulator models, as well as managing their revisions. ``` -------------------------------- ### Extraction Pipelines Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/data_ingestion.rst Manage extraction pipelines, their runs, and configurations using the SDK. ```APIDOC ## Extraction Pipelines ### Description Manage and interact with extraction pipelines, including their execution status and configurations. ### Methods - `AsyncCogniteClient.extraction_pipelines` - `AsyncCogniteClient.extraction_pipelines.runs` - `AsyncCogniteClient.extraction_pipelines.config` ### Data Classes Refer to `cognite.client.data_classes.extractionpipelines` for data class definitions. ``` -------------------------------- ### Simulator Routines Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/simulators.rst Manage simulator routines using the `routines` submodule. ```APIDOC ## Simulator Routines The `routines` submodule is dedicated to managing simulator routines. ### Access ```python AsyncCogniteClient.simulators.routines ``` ### Description This module offers functionalities for creating, retrieving, updating, and deleting simulator routines, including managing their revisions. ``` -------------------------------- ### CogniteClient.default_oauth_interactive Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Initializes a CogniteClient using the interactive OAuth flow. This is suitable for user-based authentication and configures default URLs and scopes based on the Azure tenant and client details. ```APIDOC ## CogniteClient.default_oauth_interactive ### Description Create an CogniteClient with default configuration using the interactive flow. The default configuration creates the URLs based on the tenant_id and cluster. ### Method ```python CogniteClient.default_oauth_interactive(project: str, cdf_cluster: str, tenant_id: str, client_id: str, client_name: str | None = None) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **project** (str) - Required - The CDF project. * **cdf_cluster** (str) - Required - The CDF cluster where the CDF project is located. * **tenant_id** (str) - Required - The Azure tenant ID. * **client_id** (str) - Required - The Azure client ID. * **client_name** (str | None) - Optional - A user-defined name for the client. Used to identify the number of unique applications/scripts running on top of CDF. If this is not set, the getpass.getuser() is used instead, meaning the username you are logged in with is used. ### Returns CogniteClient: An CogniteClient instance with default configurations. ### Configuration Details * Base URL: ``"https://{{cdf_cluster}}.cognitedata.com/"`` * Authority URL: ``"https://login.microsoftonline.com/{{tenant_id}}"`` * Scopes: ``[f"https://{{cdf_cluster}}.cognitedata.com/.default"]`` ``` -------------------------------- ### Simulator Integrations Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/simulators.rst Manage simulator integrations using the `integrations` submodule. ```APIDOC ## Simulator Integrations The `integrations` submodule allows for the management of simulator integrations. ### Access ```python AsyncCogniteClient.simulators.integrations ``` ### Description This module provides methods to interact with and manage simulator integrations. ``` -------------------------------- ### Simulator Logs Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/simulators.rst Access and manage simulator logs using the `logs` submodule. ```APIDOC ## Simulator Logs The `logs` submodule allows for retrieving logs associated with simulators. ### Access ```python AsyncCogniteClient.simulators.logs ``` ### Description This module provides methods to fetch and analyze logs generated by simulator operations, aiding in debugging and monitoring. ``` -------------------------------- ### Auto Accessor Method Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/_templates/custom-accessor-template.rst This snippet shows how the `autoaccessormethod` directive is used to document accessor methods. It dynamically generates documentation based on the object name and module. ```APIDOC .. autoaccessormethod:: {{ objname }} ``` -------------------------------- ### monkeypatch_async_cognite_client Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/testing.rst A context manager to temporarily replace the `AsyncCogniteClient` with a mock. ```APIDOC ## monkeypatch_async_cognite_client ### Description This context manager allows you to monkeypatch the `AsyncCogniteClient` with a mock during the execution of an asynchronous test. This is useful for isolating components that depend on the asynchronous Cognite client. ### Function Signature cognite.client.testing.monkeypatch_async_cognite_client() ``` -------------------------------- ### Raw Data Management Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/data_ingestion.rst Manage raw data including databases, tables, and rows using the SDK. ```APIDOC ## Raw Data Management ### Description Provides access to manage raw data structures within Cognite. ### Methods - `AsyncCogniteClient.raw.databases` - `AsyncCogniteClient.raw.tables` - `AsyncCogniteClient.raw.rows` ### Data Classes Refer to `cognite.client.data_classes.raw` for data class definitions. ``` -------------------------------- ### Generate Code Coverage Reports Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Generate HTML and XML code coverage reports for unit tests. The coverage will focus on the 'cognite' package and 'tests' directory. ```bash pytest tests/tests_unit --cov-report html \ --cov-report xml \ --cov cognite tests ``` -------------------------------- ### monkeypatch_cognite_client Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/testing.rst A context manager to temporarily replace the `CogniteClient` with a mock. ```APIDOC ## monkeypatch_cognite_client ### Description This context manager allows you to monkeypatch the `CogniteClient` with a mock during the execution of a test. This is useful for isolating components that depend on the Cognite client. ### Function Signature cognite.client.testing.monkeypatch_cognite_client() ``` -------------------------------- ### Run Code Generation Script with Verbose Mode Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Enable verbose mode by passing `-v` before the subcommand (`run` or `verify`) for debugging purposes during code generation. ```sh python scripts/sync_client_codegen/main.py -v [run, verify] ... ``` -------------------------------- ### Sources Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/hosted_extractors.rst Access methods for managing hosted extractor sources. ```APIDOC ## AsyncCogniteClient.hosted_extractors.sources ### Description Provides access to methods for managing hosted extractor sources. ### Method Access to the `sources` attribute of the `hosted_extractors` client. ### Endpoint N/A (SDK method) ### Parameters N/A ``` -------------------------------- ### CogniteClientMock Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/testing.rst Provides a mock object for `cognite.client.CogniteClient` to facilitate unit testing. ```APIDOC ## CogniteClientMock ### Description Use this class as a mock for `cognite.client.CogniteClient` in your unit tests. It utilizes `create_autospec` with `spec_set=True` for enhanced type safety and call signature checking. ### Class cognite.client.testing.CogniteClientMock ``` -------------------------------- ### Run Static Checks Manually Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/CONTRIBUTING.md Manually trigger all static checks, including slower ones, using pre-commit. Use `--hook-stage manual` to include checks that are typically run in CI. ```bash pre-commit run --all-files ``` ```bash pre-commit run --all-files --hook-stage manual ``` -------------------------------- ### CogniteClient (sync) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/cognite_client.rst The synchronous client for backward compatibility. This client wraps the asynchronous client internally and provides a familiar synchronous interface. ```APIDOC ## CogniteClient (sync) ### Description The synchronous client for backward compatibility (wraps the async client internally). ### Usage ```python from cognite.client import CogniteClient client = CogniteClient(... ``` ``` -------------------------------- ### Access Underlying API Client (Deprecated) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/scripts/sync_client_codegen/sync_client_template.txt Provides access to the underlying API client. This method is deprecated and will be removed in v9. It returns the async API client, and direct calls require 'await'. Use client.post(), client.get(), or client.put() for synchronous requests. ```python @property def api_client(self) -> APIClient: """Returns the underlying API client used for HTTP requests. .. deprecated:: 8.0 Use :meth:`post`, :meth:`get`, or :meth:`put` instead. Will be removed in v9. .. warning:: This returns the **async** API client. Calling its methods directly requires ``await`` and will not work in a synchronous context. Use :meth:`post`, :meth:`get`, or :meth:`put` instead. Returns: APIClient: The async API client instance. """ import warnings warnings.warn( "'api_client' is deprecated and will be removed in v9. " "Use client.post(), client.get(), or client.put() instead.", FutureWarning, stacklevel=2, ) warnings.warn( "'api_client' returns the underlying async API client. Calling its methods directly requires " "'await' and will not work in a synchronous context. " "Use client.post(), client.get(), or client.put() for synchronous HTTP requests instead.", UserWarning, stacklevel=2, ) return self.__async_client._api_client ``` -------------------------------- ### CogniteAPIError Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/exceptions.rst Base exception for API-related errors from Cognite. ```APIDOC ## CogniteAPIError ### Description This is the base exception class for all errors that originate from the Cognite API. It is raised when the Cognite API returns an error status code or an error message. ### Usage ```python try: # Code that might raise a CogniteAPIError cognite_client.some_operation() except cognite.client.exceptions.CogniteAPIError as e: print(f"An API error occurred: {e}") ``` ``` -------------------------------- ### Filter Nodes and Edges by Base Properties Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/filters.rst Use Prefix and Equals filters to query base instance properties like externalId and space for nodes and edges. ```python from cognite.client.data_classes.filters import Prefix, Equals # Filter nodes where externalId starts with "SomeCustomer" flt = Prefix(("node", "externalId"), "SomeCustomer") # Filter edges in a specific space flt = Equals(("edge", "space"), "my_space") ``` -------------------------------- ### Simulation Runs Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/simulators.rst Manage simulation runs using the `runs` submodule. ```APIDOC ## Simulation Runs The `runs` submodule is used for managing simulation runs. ### Access ```python AsyncCogniteClient.simulators.runs ``` ### Description This module provides functionalities to initiate, monitor, and manage the lifecycle of simulation runs. ``` -------------------------------- ### Relationships (legacy) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/data_organization.rst Access legacy relationship functionalities through the client. ```APIDOC ## Relationships (legacy) ### Description Access legacy relationship functionalities through the client. ### Method `client.relationships` ### Endpoint N/A (SDK method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Simulator Data Classes Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/simulators.rst Overview of data classes used within the Simulators API. ```APIDOC ## Simulator Data Classes The `cognite.client.data_classes.simulators` module contains the data classes used for representing simulator-related entities. ### Module ```python import cognite.client.data_classes.simulators ``` ### Description This module defines the structure for various simulator objects, including models, routines, runs, and their associated data. These classes are used for data exchange with the API and for structuring data within your application. ``` -------------------------------- ### Mappings Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/hosted_extractors.rst Access methods for managing hosted extractor mappings. ```APIDOC ## AsyncCogniteClient.hosted_extractors.mappings ### Description Provides access to methods for managing hosted extractor mappings. ### Method Access to the `mappings` attribute of the `hosted_extractors` client. ### Endpoint N/A (SDK method) ### Parameters N/A ``` -------------------------------- ### AsyncCogniteClient Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/cognite_client.rst The primary asynchronous client using native async/await patterns. This client is recommended for new applications leveraging asynchronous programming. ```APIDOC ## AsyncCogniteClient ### Description The primary asynchronous client using native `async/await` patterns (new in v8). ### Usage ```python from cognite.client import AsyncCogniteClient client = AsyncCogniteClient(... ``` ``` -------------------------------- ### CredentialProvider Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/credential_providers.rst Base class for all credential providers. Users typically do not instantiate this directly but rather use one of its subclasses. ```APIDOC class cognite.client.credentials.CredentialProvider ``` -------------------------------- ### Data Sets Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/data_organization.rst Manage data sets using the client. ```APIDOC ## Data Sets ### Description Manage data sets using the client. ### Method `client.data_sets` ### Endpoint N/A (SDK method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Annotations (legacy) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/data_organization.rst Access legacy annotation functionalities through the client. ```APIDOC ## Annotations (legacy) ### Description Access legacy annotation functionalities through the client. ### Method `client.annotations` ### Endpoint N/A (SDK method) ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Retrieve Latest Datapoint (v7 vs v8) Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/MIGRATION_GUIDE.md Compares how to retrieve the latest datapoint using the Cognite Python SDK before and after version 8. Note the change in timestamp type and the direct access to value. ```python # Before (v7) if dps := client.time_series.data.retrieve_latest(id=123): ts = dps[0].timestamp # int (ms) val = dps[0].value # After (v8) if dp := client.time_series.data.retrieve_latest(id=123): ts = dp.timestamp # datetime (UTC) val = dp.value ``` -------------------------------- ### Agents Module Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/agents.rst Access to agent-related functionalities within the Cognite SDK. ```APIDOC ## Agents Module This module provides access to agent-related functionalities within the Cognite SDK. ### Accessing the Agents Module To interact with agents, you can access the `agents` attribute of an initialized `CogniteClient` or `AsyncCogniteClient` instance. ```python from cognite.client import CogniteClient # Assuming you have initialized your client client = CogniteClient(config=...) # Access the agents module agents_api = client.agents ``` ### Agent Data Classes The `cognite.client.data_classes.agents` module contains the data classes used for representing and manipulating agent-related information. Refer to the `automethods-template.rst` for specific method signatures and usage examples. ``` -------------------------------- ### Configure Concurrency Limits Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/settings.rst Set global concurrency limits for different operation types before making any API requests. These settings are frozen after the first API call. ```python from cognite.client import global_config # Configure concurrency limits before making any API requests settings = global_config.concurrency_settings settings.general.read = 8 settings.general.write = 4 settings.general.delete = 2 # Data modeling has additional operation types due to its large API interface: settings.data_modeling.search = 2 settings.data_modeling.read_schema = 2 settings.data_modeling.write_schema = 1 # Files separates metadata writes from content transfers, plus a global open_files limit: settings.files.upload = 4 settings.files.download = 4 settings.files.open_files = 20 # global: shared across all projects in this process ``` -------------------------------- ### Workflows Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/data_workflows.rst Access methods for managing workflows. ```APIDOC ## Workflows This section provides access to methods for managing workflows. ### Method Signature ```python AsyncCogniteClient.workflows ``` ``` -------------------------------- ### List 3D Sectors Source: https://github.com/cognitedata/cognite-sdk-python/blob/master/docs/source/3d.rst Lists all sectors associated with a 3D model. ```APIDOC ## List 3D Sectors ### Description Lists all sectors associated with a 3D model. ### Method `list_sectors` ### Parameters - **model_id** (int) - Required - The ID of the 3D model. - **revision_id** (int) - Required - The ID of the 3D revision. ```