Skip to content

Project Specific API

You can execute shell commands and code using a Jupyter kernel. Create an instance of this API using cocalc_api.Project and pass in the project_id in addition to the API key. This works with both project-specific API keys and account level API keys.

>>> import cocalc_api
>>> project = cocalc_api.Project(api_key="sk-...", project_id='...')
Source code in src/cocalc_api/project.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class System:

    def __init__(self, parent: "Project"):
        self._parent = parent

    @api_method("system.ping")
    def ping(self) -> PingResponse:
        """
        Ping the project.

        Returns:
            PingResponse: JSON object containing the current server time.

        Examples:
            Ping a project. The api_key can be either an account api key or a project
            specific api key (in which case the project_id option is optional):

            >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
            >>> project.ping()
            {'now': 1756489740133}

        """
        ...  # pragma: no cover

    @api_method("system.test")
    def test(self) -> dict[str, Any]:
        """
        Test the API key and get the project_id.

        Returns:
            dict: JSON object containing project_id and server_time.

        """
        ...  # pragma: no cover

    @api_method("system.exec", timeout_seconds=True)
    def exec(
        self,
        command: str,
        args: Optional[list[str]] = None,
        path: Optional[str] = None,
        cwd: Optional[str] = None,
        timeout: Optional[int] = None,
        max_output: Optional[int] = None,
        bash: Optional[bool] = None,
        env: Optional[dict[str, Any]] = None,
        async_call: Optional[bool] = None,
        compute_server_id: Optional[int] = None,
    ) -> ExecuteCodeOutput:
        """
        Execute an arbitrary shell command in the project.

        Args:
            command (str): Command to run; can be a program name (e.g., "ls") or absolute path, or a full bash script.
            args (Optional[list[str]]): Optional arguments to the command.
            path (Optional[str]): Path (relative to HOME directory) where command will be run.
            cwd (Optional[str]): Absolute path where code executed from (if path not given).
            timeout (Optional[int]): Optional timeout in SECONDS.
            max_output (Optional[int]): Bound on size of stdout and stderr; further output ignored.
            bash (Optional[bool]): If True, ignore args and evaluate command as a bash command.
            env (Optional[dict[str, Any]]): If given, added to exec environment.
            compute_server_id (Optional[int]): Compute server to run code on (instead of home base project).

        Returns:
            ExecuteCodeOutput: Result of executing the command.

        Notes:
            The returned `ExecuteCodeOutput` has the following fields:

            - `stdout` (str): Output written to stdout.
            - `stderr` (str): Output written to stderr.
            - `exit_code` (int): Exit code of the process.

        Examples:
            >>> import cocalc_api
            >>> project = cocalc_api.Project(api_key="sk-...",
            ...                              project_id='6e75dbf1-0342-4249-9dce-6b21648656e9')
            >>> project.system.exec(command="echo 'hello from cocalc'")
            {'stdout': 'hello from cocalc\\n', 'stderr':'', 'exit_code': 0}
        """
        ...  # pragma: no cover

    @api_method("system.jupyterExecute", timeout_seconds=True)
    def jupyter_execute(
        self,
        input: str,
        kernel: str,
        history: Optional[list[str]] = None,
        path: Optional[str] = None,
        timeout: Optional[int] = 90,
    ) -> list[dict[str, Any]]:  # type: ignore[empty-body]
        """
        Execute code using a Jupyter kernel.

        Args:
            input (str): Code to execute.
            kernel (str): Name of kernel to use. Get options using hub.jupyter.kernels().
            history (Optional[list[str]]): Array of previous inputs (they get evaluated every time, but without output being captured).
            path (Optional[str]): File path context for execution.
            timeout (Optional[int]): Timeout in SECONDS for the execute call (defaults to 90 seconds).

        Returns:
            list[dict[str, Any]]: List of output items. Each output item contains
                execution results with 'data' field containing output by MIME type
                (e.g., 'text/plain' for text output) or 'name'/'text' fields for
                stream output (stdout/stderr).

        Examples:
            Execute a simple sum using a Jupyter kernel:

            >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
            >>> result = project.system.jupyter_execute(input='sum(range(100))', kernel='python3')
            >>> result
            [{'data': {'text/plain': '4950'}}]

            Execute with history context:

            >>> result = project.system.jupyter_execute(
            ...     history=['a = 100'],
            ...     input='sum(range(a + 1))',
            ...     kernel='python3')
            >>> result
            [{'data': {'text/plain': '5050'}}]

            Print statements produce stream output:

            >>> result = project.system.jupyter_execute(input='print("Hello")', kernel='python3')
            >>> result
            [{'name': 'stdout', 'text': 'Hello\\n'}]
        """
        ...  # pragma: no cover

    @api_method("system.listJupyterKernels")
    def list_jupyter_kernels(self) -> list[dict[str, Any]]:  # type: ignore[empty-body]
        """
        List all running Jupyter kernels in the project.

        Returns:
            list[dict[str, Any]]: List of running kernels. Each kernel has:
                - pid (int): Process ID of the kernel
                - connectionFile (str): Path to the kernel connection file
                - kernel_name (str, optional): Name of the kernel (e.g., 'python3')

        Examples:
            List all running kernels:

            >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
            >>> kernels = project.system.list_jupyter_kernels()
            >>> kernels
            [{'pid': 12345, 'connectionFile': '/run/user/1000/jupyter/kernel-abc123.json', 'kernel_name': 'python3'}]
        """
        ...  # pragma: no cover

    @api_method("system.stopJupyterKernel")
    def stop_jupyter_kernel(self, pid: int) -> dict[str, bool]:  # type: ignore[empty-body]
        """
        Stop a specific Jupyter kernel by process ID.

        Args:
            pid (int): Process ID of the kernel to stop

        Returns:
            dict[str, bool]: Dictionary with 'success' key indicating if the kernel was stopped

        Examples:
            Stop a kernel by PID:

            >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
            >>> project.system.stop_jupyter_kernel(pid=12345)
            {'success': True}
        """
        ...  # pragma: no cover

exec(command, args=None, path=None, cwd=None, timeout=None, max_output=None, bash=None, env=None, async_call=None, compute_server_id=None)

Execute an arbitrary shell command in the project.

Parameters:

Name Type Description Default
command str

Command to run; can be a program name (e.g., "ls") or absolute path, or a full bash script.

required
args Optional[list[str]]

Optional arguments to the command.

None
path Optional[str]

Path (relative to HOME directory) where command will be run.

None
cwd Optional[str]

Absolute path where code executed from (if path not given).

None
timeout Optional[int]

Optional timeout in SECONDS.

None
max_output Optional[int]

Bound on size of stdout and stderr; further output ignored.

None
bash Optional[bool]

If True, ignore args and evaluate command as a bash command.

None
env Optional[dict[str, Any]]

If given, added to exec environment.

None
compute_server_id Optional[int]

Compute server to run code on (instead of home base project).

None

Returns:

Name Type Description
ExecuteCodeOutput ExecuteCodeOutput

Result of executing the command.

Notes

The returned ExecuteCodeOutput has the following fields:

  • stdout (str): Output written to stdout.
  • stderr (str): Output written to stderr.
  • exit_code (int): Exit code of the process.

Examples:

>>> import cocalc_api
>>> project = cocalc_api.Project(api_key="sk-...",
...                              project_id='6e75dbf1-0342-4249-9dce-6b21648656e9')
>>> project.system.exec(command="echo 'hello from cocalc'")
{'stdout': 'hello from cocalc\n', 'stderr':'', 'exit_code': 0}
Source code in src/cocalc_api/project.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@api_method("system.exec", timeout_seconds=True)
def exec(
    self,
    command: str,
    args: Optional[list[str]] = None,
    path: Optional[str] = None,
    cwd: Optional[str] = None,
    timeout: Optional[int] = None,
    max_output: Optional[int] = None,
    bash: Optional[bool] = None,
    env: Optional[dict[str, Any]] = None,
    async_call: Optional[bool] = None,
    compute_server_id: Optional[int] = None,
) -> ExecuteCodeOutput:
    """
    Execute an arbitrary shell command in the project.

    Args:
        command (str): Command to run; can be a program name (e.g., "ls") or absolute path, or a full bash script.
        args (Optional[list[str]]): Optional arguments to the command.
        path (Optional[str]): Path (relative to HOME directory) where command will be run.
        cwd (Optional[str]): Absolute path where code executed from (if path not given).
        timeout (Optional[int]): Optional timeout in SECONDS.
        max_output (Optional[int]): Bound on size of stdout and stderr; further output ignored.
        bash (Optional[bool]): If True, ignore args and evaluate command as a bash command.
        env (Optional[dict[str, Any]]): If given, added to exec environment.
        compute_server_id (Optional[int]): Compute server to run code on (instead of home base project).

    Returns:
        ExecuteCodeOutput: Result of executing the command.

    Notes:
        The returned `ExecuteCodeOutput` has the following fields:

        - `stdout` (str): Output written to stdout.
        - `stderr` (str): Output written to stderr.
        - `exit_code` (int): Exit code of the process.

    Examples:
        >>> import cocalc_api
        >>> project = cocalc_api.Project(api_key="sk-...",
        ...                              project_id='6e75dbf1-0342-4249-9dce-6b21648656e9')
        >>> project.system.exec(command="echo 'hello from cocalc'")
        {'stdout': 'hello from cocalc\\n', 'stderr':'', 'exit_code': 0}
    """
    ...  # pragma: no cover

jupyter_execute(input, kernel, history=None, path=None, timeout=90)

Execute code using a Jupyter kernel.

Parameters:

Name Type Description Default
input str

Code to execute.

required
kernel str

Name of kernel to use. Get options using hub.jupyter.kernels().

required
history Optional[list[str]]

Array of previous inputs (they get evaluated every time, but without output being captured).

None
path Optional[str]

File path context for execution.

None
timeout Optional[int]

Timeout in SECONDS for the execute call (defaults to 90 seconds).

90

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: List of output items. Each output item contains execution results with 'data' field containing output by MIME type (e.g., 'text/plain' for text output) or 'name'/'text' fields for stream output (stdout/stderr).

Examples:

Execute a simple sum using a Jupyter kernel:

>>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
>>> result = project.system.jupyter_execute(input='sum(range(100))', kernel='python3')
>>> result
[{'data': {'text/plain': '4950'}}]

Execute with history context:

>>> result = project.system.jupyter_execute(
...     history=['a = 100'],
...     input='sum(range(a + 1))',
...     kernel='python3')
>>> result
[{'data': {'text/plain': '5050'}}]

Print statements produce stream output:

>>> result = project.system.jupyter_execute(input='print("Hello")', kernel='python3')
>>> result
[{'name': 'stdout', 'text': 'Hello\n'}]
Source code in src/cocalc_api/project.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
@api_method("system.jupyterExecute", timeout_seconds=True)
def jupyter_execute(
    self,
    input: str,
    kernel: str,
    history: Optional[list[str]] = None,
    path: Optional[str] = None,
    timeout: Optional[int] = 90,
) -> list[dict[str, Any]]:  # type: ignore[empty-body]
    """
    Execute code using a Jupyter kernel.

    Args:
        input (str): Code to execute.
        kernel (str): Name of kernel to use. Get options using hub.jupyter.kernels().
        history (Optional[list[str]]): Array of previous inputs (they get evaluated every time, but without output being captured).
        path (Optional[str]): File path context for execution.
        timeout (Optional[int]): Timeout in SECONDS for the execute call (defaults to 90 seconds).

    Returns:
        list[dict[str, Any]]: List of output items. Each output item contains
            execution results with 'data' field containing output by MIME type
            (e.g., 'text/plain' for text output) or 'name'/'text' fields for
            stream output (stdout/stderr).

    Examples:
        Execute a simple sum using a Jupyter kernel:

        >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
        >>> result = project.system.jupyter_execute(input='sum(range(100))', kernel='python3')
        >>> result
        [{'data': {'text/plain': '4950'}}]

        Execute with history context:

        >>> result = project.system.jupyter_execute(
        ...     history=['a = 100'],
        ...     input='sum(range(a + 1))',
        ...     kernel='python3')
        >>> result
        [{'data': {'text/plain': '5050'}}]

        Print statements produce stream output:

        >>> result = project.system.jupyter_execute(input='print("Hello")', kernel='python3')
        >>> result
        [{'name': 'stdout', 'text': 'Hello\\n'}]
    """
    ...  # pragma: no cover

list_jupyter_kernels()

List all running Jupyter kernels in the project.

Returns:

Type Description
list[dict[str, Any]]

list[dict[str, Any]]: List of running kernels. Each kernel has: - pid (int): Process ID of the kernel - connectionFile (str): Path to the kernel connection file - kernel_name (str, optional): Name of the kernel (e.g., 'python3')

Examples:

List all running kernels:

>>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
>>> kernels = project.system.list_jupyter_kernels()
>>> kernels
[{'pid': 12345, 'connectionFile': '/run/user/1000/jupyter/kernel-abc123.json', 'kernel_name': 'python3'}]
Source code in src/cocalc_api/project.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
@api_method("system.listJupyterKernels")
def list_jupyter_kernels(self) -> list[dict[str, Any]]:  # type: ignore[empty-body]
    """
    List all running Jupyter kernels in the project.

    Returns:
        list[dict[str, Any]]: List of running kernels. Each kernel has:
            - pid (int): Process ID of the kernel
            - connectionFile (str): Path to the kernel connection file
            - kernel_name (str, optional): Name of the kernel (e.g., 'python3')

    Examples:
        List all running kernels:

        >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
        >>> kernels = project.system.list_jupyter_kernels()
        >>> kernels
        [{'pid': 12345, 'connectionFile': '/run/user/1000/jupyter/kernel-abc123.json', 'kernel_name': 'python3'}]
    """
    ...  # pragma: no cover

ping()

Ping the project.

Returns:

Name Type Description
PingResponse PingResponse

JSON object containing the current server time.

Examples:

Ping a project. The api_key can be either an account api key or a project specific api key (in which case the project_id option is optional):

>>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
>>> project.ping()
{'now': 1756489740133}
Source code in src/cocalc_api/project.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@api_method("system.ping")
def ping(self) -> PingResponse:
    """
    Ping the project.

    Returns:
        PingResponse: JSON object containing the current server time.

    Examples:
        Ping a project. The api_key can be either an account api key or a project
        specific api key (in which case the project_id option is optional):

        >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
        >>> project.ping()
        {'now': 1756489740133}

    """
    ...  # pragma: no cover

stop_jupyter_kernel(pid)

Stop a specific Jupyter kernel by process ID.

Parameters:

Name Type Description Default
pid int

Process ID of the kernel to stop

required

Returns:

Type Description
dict[str, bool]

dict[str, bool]: Dictionary with 'success' key indicating if the kernel was stopped

Examples:

Stop a kernel by PID:

>>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
>>> project.system.stop_jupyter_kernel(pid=12345)
{'success': True}
Source code in src/cocalc_api/project.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
@api_method("system.stopJupyterKernel")
def stop_jupyter_kernel(self, pid: int) -> dict[str, bool]:  # type: ignore[empty-body]
    """
    Stop a specific Jupyter kernel by process ID.

    Args:
        pid (int): Process ID of the kernel to stop

    Returns:
        dict[str, bool]: Dictionary with 'success' key indicating if the kernel was stopped

    Examples:
        Stop a kernel by PID:

        >>> import cocalc_api; project = cocalc_api.Project(api_key="sk-...", project_id='...')
        >>> project.system.stop_jupyter_kernel(pid=12345)
        {'success': True}
    """
    ...  # pragma: no cover

test()

Test the API key and get the project_id.

Returns:

Name Type Description
dict dict[str, Any]

JSON object containing project_id and server_time.

Source code in src/cocalc_api/project.py
69
70
71
72
73
74
75
76
77
78
@api_method("system.test")
def test(self) -> dict[str, Any]:
    """
    Test the API key and get the project_id.

    Returns:
        dict: JSON object containing project_id and server_time.

    """
    ...  # pragma: no cover