Skip to main content

Python client for the CoCalc API

Project description

CoCalc Python API Client

PyPI version Python 3.9+

This is a Python package that provides an API client for CoCalc, enabling programmatic access to CoCalc's features including project management, Jupyter execution, file operations, messaging, and organization management.

Installation

pip install cocalc-api

Quick Start

import cocalc_api

# Initialize hub client with your API key
hub = cocalc_api.Hub(api_key="your-api-key")

# Ping the server
response = hub.system.ping()
print(f"Server time: {response['now']}")

# List your projects
projects = hub.projects.get()
for project in projects:
    print(f"Project: {project['title']} ({project['project_id']})")

Features

Hub Client (Account-Level Operations)

The Hub class provides access to account-level operations:

  • System: Server ping, user search, account name resolution
  • Projects: Project management (create, start, stop, add/remove collaborators)
  • Jupyter: Execute code using Jupyter kernels in any project or anonymously
  • Database: Direct PostgreSQL database queries for advanced operations
  • Messages: Send and receive messages between users
  • Organizations: Manage organizations, users, and temporary access tokens
  • Sync: Access file edit history and synchronization features

Project Client (Project-Specific Operations)

The Project class provides project-specific operations:

  • System: Execute shell commands and Jupyter code within a specific project

MCP Server

The CoCalc API includes a Model Context Protocol (MCP) server that allows LLMs (like Claude) to interact with CoCalc projects through a standardized protocol.

For detailed setup instructions and usage guide, see src/cocalc_api/mcp/README.md.

Authentication

The client supports two types of API keys:

  1. Account API Keys: Provide full access to all hub functionality
  2. Project API Keys: Limited to project-specific operations

Get your API key from CoCalc Account Settings under "API Keys".

Architecture

Package Structure

src/cocalc_api/
├── __init__.py          # Package exports (Hub, Project classes)
├── hub.py              # Hub client for account-level operations
├── project.py          # Project client for project-specific operations
├── api_types.py        # TypedDict definitions for API responses
└── util.py             # Utility functions and decorators

Design Patterns

  • Decorator-based Methods: Uses @api_method() decorator to automatically convert method calls to API requests
  • TypedDict Responses: All API responses use TypedDict for type safety
  • Error Handling: Centralized error handling via handle_error() utility
  • HTTP Client: Uses httpx for HTTP requests with authentication
  • Nested Namespaces: API organized into logical namespaces (system, projects, jupyter, etc.)

Development

Requirements

  • Python 3.9+
  • uv package manager

Setup

# Install dependencies
make install
# or: uv sync --dev && uv pip install -e .

# Format Python code
make format
# or: uv run yapf --in-place --recursive src/

# Run code quality checks
make check
# or: uv run ruff check src/ && uv run mypy src/ && uv run pyright src/

# Serve documentation locally
make serve-docs
# or: uv run mkdocs serve

# Build documentation
make build-docs

Code Quality

This project uses multiple tools for code quality:

  • YAPF: Python code formatter
  • Ruff: Fast Python linter
  • MyPy: Static type checking
  • Pyright: Additional static type checking
  • MkDocs: Documentation generation

Documentation Standards

All docstrings follow the Google Style Guide for Python docstrings. This includes:

  • Clear one-line summary
  • Detailed description when needed
  • Properly formatted Args:, Returns:, Raises:, and Examples: sections
  • Type information consistent with function signatures
  • Consistent capitalization and punctuation

Example:

def example_function(param1: str, param2: Optional[int] = None) -> dict[str, Any]:
    """
    Brief description of the function.

    Longer description if needed, explaining the function's behavior,
    side effects, or important usage notes.

    Args:
        param1 (str): Description of the first parameter.
        param2 (Optional[int]): Description of the optional parameter.

    Returns:
        dict[str, Any]: Description of the return value.

    Raises:
        ValueError: When this exception might be raised.

    Examples:
        >>> result = example_function("hello", 42)
        >>> print(result)
        {'status': 'success', 'data': 'hello'}
    """

License

MIT License. See the LICENSE file for details.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cocalc_api-0.5.1.tar.gz (47.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cocalc_api-0.5.1-py3-none-any.whl (37.7 kB view details)

Uploaded Python 3

File details

Details for the file cocalc_api-0.5.1.tar.gz.

File metadata

  • Download URL: cocalc_api-0.5.1.tar.gz
  • Upload date:
  • Size: 47.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.6

File hashes

Hashes for cocalc_api-0.5.1.tar.gz
Algorithm Hash digest
SHA256 84582a4fd4937d1e8a4206aa318d7bbccc211272326499085c12e2be7d315105
MD5 cba2bdba3ca147b11b0185994ead1988
BLAKE2b-256 3cf3dc87aa113e0d0faf7f9e9c2abb66166fc3e0a8e4eb5c7712bcb7bec7cdef

See more details on using hashes here.

File details

Details for the file cocalc_api-0.5.1-py3-none-any.whl.

File metadata

  • Download URL: cocalc_api-0.5.1-py3-none-any.whl
  • Upload date:
  • Size: 37.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.6

File hashes

Hashes for cocalc_api-0.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 7e22fcdd032a354ce15ebf3e267bf458e4964ca50bf64c40300fe24e339ee0ec
MD5 14db226b9ab6e3bfedd4958a10eeacc7
BLAKE2b-256 db3b5b66e4daf18122748a4f82753628ecace562c76d2cfb0c63145448026a8a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page