eAI
Article

Mock Server and Client for Cognite Python SDK

Anand George
#Cognite#SDK#Python#P&ID

When building integrations with the Cognite Python SDK, you might not always have access to a live Cognite Data Fusion (CDF) project — especially when prototyping, testing, or running demos offline. A mock server lets you simulate CDF’s API responses so you can develop confidently without touching production data.

Why Use a Mock Server?

Setting Up the Environment

You’ll need:

pip install cognite-sdk flask

Creating a Simple Mock Server

Here’s a minimal Flask-based mock server to mimic a subset of CDF APIs.

from flask import Flask, jsonify, request

app = Flask(__name__)

# Example asset data
mock_assets = [
    {"externalId": "PUMP-101", "name": "Feed Pump", "id": 1},
    {"externalId": "VALVE-202", "name": "Control Valve", "id": 2}
]

@app.route("/api/v1/projects/<project>/assets", methods=["GET"])
def list_assets(project):
    return jsonify({"items": mock_assets})

@app.route("/api/v1/projects/<project>/assets", methods=["POST"])
def create_asset(project):
    data = request.json
    mock_assets.append(data)
    return jsonify(data), 201

if __name__ == "__main__":
    app.run(port=5000)

This mock server responds to /assets GET and POST requests with predictable data.

Connecting the Cognite SDK to the Mock Server

When initializing the SDK, point it to your mock server instead of the real CDF API.

from cognite.client import CogniteClient

client = CogniteClient(
    api_key="dummy-api-key",
    project="mock-project",
    base_url="http://localhost:5000/api/v1"  # Override base URL
)

# List assets
assets = client.assets.list()
print(assets)

# Create a new asset
new_asset = client.assets.create({"externalId": "TANK-303", "name": "Storage Tank"})
print(new_asset)

Tips for More Realistic Mocks

  1. Match the API shape – Return JSON structures that mimic the real API.
  2. Simulate errors – Return 400/404/500 responses to test error handling.
  3. Use fixtures – Store mock responses in JSON files for maintainability.
  4. Parameter handling – Read query params from request.args in Flask to simulate filtering, paging, etc.

Automating Tests with Pytest

You can integrate this mock server into automated tests:

import pytest
from cognite.client import CogniteClient

@pytest.fixture
def client():
    return CogniteClient(api_key="test", project="mock-project", base_url="http://localhost:5000/api/v1")

def test_asset_list(client):
    assets = client.assets.list()
    assert len(assets) > 0
    assert assets[0].external_id == "PUMP-101"

Run with:

pytest

Wrapping Up

Using a mock server with the Cognite Python SDK allows you to:

When ready, you can simply change the base_url back to the real CDF endpoint and test against live data.

Read More: eAI: The Future of Digital Twins for P&IDs

Similar Posts

← Back to Blog