Skip to content

Commit 689fecf

Browse files
committed
cocalc-api: fix docstring style, check with pyright as well, fix/ignore missing return types, generate a better README
1 parent 0ae2c0b commit 689fecf

File tree

9 files changed

+415
-129
lines changed

9 files changed

+415
-129
lines changed

src/.claude/settings.json

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"Bash(git commit:*)",
1616
"Bash(git push:*)",
1717
"Bash(grep:*)",
18+
"Bash(make:*)",
1819
"Bash(node:*)",
1920
"Bash(npm show:*)",
2021
"Bash(npm view:*)",
@@ -23,18 +24,23 @@
2324
"Bash(pnpm audit:*)",
2425
"Bash(pnpm build:*)",
2526
"Bash(pnpm i18n:*)",
27+
"Bash(pnpm i18n:compile:*)",
28+
"Bash(pnpm i18n:download:*)",
29+
"Bash(pnpm i18n:extract:*)",
30+
"Bash(pnpm i18n:upload:*)",
2631
"Bash(pnpm info:*)",
2732
"Bash(pnpm list:*)",
2833
"Bash(pnpm remove:*)",
2934
"Bash(pnpm run:*)",
3035
"Bash(pnpm ts-build:*)",
3136
"Bash(pnpm tsc:*)",
32-
"Bash(pnpm view:*)",
3337
"Bash(pnpm update:*)",
38+
"Bash(pnpm view:*)",
3439
"Bash(pnpm why:*)",
3540
"Bash(prettier -w:*)",
3641
"Bash(psql:*)",
3742
"Bash(python3:*)",
43+
"Bash(uv:*)",
3844
"WebFetch",
3945
"WebSearch",
4046
"mcp__cclsp__find_definition",
@@ -43,7 +49,6 @@
4349
"mcp__github__get_issue_comments",
4450
"mcp__github__get_pull_request",
4551
"mcp__github__get_pull_request_comments",
46-
"mcp__github__get_pull_request_comments",
4752
"mcp__github__get_pull_request_status",
4853
"mcp__github__list_workflow_runs",
4954
"mcp__github__list_workflows"

src/CLAUDE.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,93 @@ Same flow as above, but **before 3. i18n:upload**, delete the key. Only new keys
222222
- Ignore everything in `node_modules` or `dist` directories
223223
- Ignore all files not tracked by Git, unless they are newly created files
224224

225+
# CoCalc Python API Client
226+
227+
## Overview
228+
229+
The `python/cocalc-api/` directory contains a Python client library for the CoCalc API, published as the `cocalc-api` package on PyPI.
230+
231+
## Architecture
232+
233+
### Package Structure
234+
235+
- **`src/cocalc_api/`** - Main Python package source code
236+
- `__init__.py` - Package exports (Hub, Project classes)
237+
- `hub.py` - Hub client for account-level API operations
238+
- `project.py` - Project client for project-specific operations
239+
- `api_types.py` - TypedDict definitions for API responses
240+
- `util.py` - Utility functions and decorators
241+
242+
### Key Classes
243+
244+
#### Hub Client (`hub.py`)
245+
246+
Account-level API client that provides access to:
247+
248+
- **System** - Server ping, user search, account name resolution
249+
- **Projects** - Project management (create, start, stop, collaborators)
250+
- **Jupyter** - Global Jupyter kernel execution
251+
- **Database** - Direct PostgreSQL database queries
252+
- **Messages** - Send/receive messages between users
253+
- **Organizations** - Organization management (admin functions)
254+
- **Sync** - File history and synchronization
255+
256+
#### Project Client (`project.py`)
257+
258+
Project-specific API client for:
259+
260+
- **System** - Project ping, shell command execution, Jupyter execution
261+
262+
### Development Tools
263+
264+
- **Package Manager**: `uv` (modern Python package manager)
265+
- **Code Formatter**: `yapf` (Python code formatter following Google style)
266+
- **Code Quality**: `ruff` (linting), `mypy` (type checking), `pyright` (additional type checking)
267+
- **Documentation**: `mkdocs` with material theme
268+
- **Testing**: `pytest`
269+
270+
### Development Commands
271+
272+
```bash
273+
# Setup and install dependencies
274+
make install # or: uv sync --dev && uv pip install -e .
275+
276+
# Format Python code
277+
make format # or: uv run yapf --in-place --recursive src/
278+
279+
# Code quality checks
280+
make check # or: uv run ruff check src/ && uv run mypy src/ && uv run pyright src/
281+
282+
# Documentation
283+
make serve-docs # or: uv run mkdocs serve
284+
make build-docs # or: uv run mkdocs build
285+
286+
# Publishing
287+
make publish # or: uv build && uv publish
288+
289+
# Cleanup
290+
make clean
291+
```
292+
293+
### API Design Patterns
294+
295+
- **Decorator-based Methods**: Uses `@api_method()` decorator to automatically convert method calls to API requests
296+
- **TypedDict Responses**: All API responses use TypedDict for type safety
297+
- **Error Handling**: Centralized error handling via `handle_error()` utility
298+
- **HTTP Client**: Uses `httpx` for HTTP requests with authentication
299+
- **Nested Namespaces**: API organized into logical namespaces (system, projects, jupyter, etc.)
300+
301+
### Authentication
302+
303+
- Supports both account-level and project-specific API keys
304+
- Account API keys provide full access to all hub functionality
305+
- Project API keys are limited to project-specific operations
306+
307+
### Connection Endpoints
308+
309+
- **Hub API**: `POST /api/conat/hub` - Account-level operations
310+
- **Project API**: `POST /api/conat/project` - Project-specific operations
311+
225312
# important-instruction-reminders
226313

227314
Do what has been asked; nothing more, nothing less.

src/python/cocalc-api/Makefile

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,13 @@ install:
55
uv sync --dev
66
uv pip install -e .
77

8+
format:
9+
uv run yapf --in-place --recursive src/
10+
811
check:
912
uv run ruff check src/
1013
uv run mypy src/
14+
uv run pyright src/
1115

1216
serve-docs:
1317
uv run mkdocs serve

src/python/cocalc-api/README.md

Lines changed: 167 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,168 @@
1-
https://pypi.org/project/cocalc-api/
1+
# CoCalc Python API Client
22

3-
This is a Python package that provides an API client for https://cocalc.com
3+
[![PyPI version](https://badge.fury.io/py/cocalc-api.svg)](https://pypi.org/project/cocalc-api/)
4+
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
5+
6+
This is a Python package that provides an API client for [CoCalc](https://cocalc.com), enabling programmatic access to CoCalc's features including project management, Jupyter execution, file operations, messaging, and organization management.
7+
8+
## Installation
9+
10+
```bash
11+
pip install cocalc-api
12+
```
13+
14+
## Quick Start
15+
16+
```python
17+
import cocalc_api
18+
19+
# Initialize hub client with your API key
20+
hub = cocalc_api.Hub(api_key="your-api-key")
21+
22+
# Ping the server
23+
response = hub.system.ping()
24+
print(f"Server time: {response['now']}")
25+
26+
# List your projects
27+
projects = hub.projects.get()
28+
for project in projects:
29+
print(f"Project: {project['title']} ({project['project_id']})")
30+
```
31+
32+
## Features
33+
34+
### Hub Client (Account-Level Operations)
35+
36+
The `Hub` class provides access to account-level operations:
37+
38+
- **System**: Server ping, user search, account name resolution
39+
- **Projects**: Project management (create, start, stop, add/remove collaborators)
40+
- **Jupyter**: Execute code using Jupyter kernels in any project or anonymously
41+
- **Database**: Direct PostgreSQL database queries for advanced operations
42+
- **Messages**: Send and receive messages between users
43+
- **Organizations**: Manage organizations, users, and temporary access tokens
44+
- **Sync**: Access file edit history and synchronization features
45+
46+
### Project Client (Project-Specific Operations)
47+
48+
The `Project` class provides project-specific operations:
49+
50+
- **System**: Execute shell commands and Jupyter code within a specific project
51+
52+
## Authentication
53+
54+
The client supports two types of API keys:
55+
56+
1. **Account API Keys**: Provide full access to all hub functionality
57+
2. **Project API Keys**: Limited to project-specific operations
58+
59+
Get your API key from [CoCalc Account Settings](https://cocalc.com/settings/account) under "API Keys".
60+
61+
## Architecture
62+
63+
### Package Structure
64+
65+
```
66+
src/cocalc_api/
67+
├── __init__.py # Package exports (Hub, Project classes)
68+
├── hub.py # Hub client for account-level operations
69+
├── project.py # Project client for project-specific operations
70+
├── api_types.py # TypedDict definitions for API responses
71+
└── util.py # Utility functions and decorators
72+
```
73+
74+
### Design Patterns
75+
76+
- **Decorator-based Methods**: Uses `@api_method()` decorator to automatically convert method calls to API requests
77+
- **TypedDict Responses**: All API responses use TypedDict for type safety
78+
- **Error Handling**: Centralized error handling via `handle_error()` utility
79+
- **HTTP Client**: Uses `httpx` for HTTP requests with authentication
80+
- **Nested Namespaces**: API organized into logical namespaces (system, projects, jupyter, etc.)
81+
82+
## Development
83+
84+
### Requirements
85+
86+
- Python 3.9+
87+
- [uv](https://github.com/astral-sh/uv) package manager
88+
89+
### Setup
90+
91+
```bash
92+
# Install dependencies
93+
make install
94+
# or: uv sync --dev && uv pip install -e .
95+
96+
# Format Python code
97+
make format
98+
# or: uv run yapf --in-place --recursive src/
99+
100+
# Run code quality checks
101+
make check
102+
# or: uv run ruff check src/ && uv run mypy src/ && uv run pyright src/
103+
104+
# Serve documentation locally
105+
make serve-docs
106+
# or: uv run mkdocs serve
107+
108+
# Build documentation
109+
make build-docs
110+
```
111+
112+
### Code Quality
113+
114+
This project uses multiple tools for code quality:
115+
116+
- **[YAPF](https://github.com/google/yapf)**: Python code formatter
117+
- **[Ruff](https://docs.astral.sh/ruff/)**: Fast Python linter
118+
- **[MyPy](http://mypy-lang.org/)**: Static type checking
119+
- **[Pyright](https://github.com/microsoft/pyright)**: Additional static type checking
120+
- **[MkDocs](https://www.mkdocs.org/)**: Documentation generation
121+
122+
### Documentation Standards
123+
124+
All docstrings follow the [Google Style Guide](https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings) for Python docstrings. This includes:
125+
126+
- Clear one-line summary
127+
- Detailed description when needed
128+
- Properly formatted `Args:`, `Returns:`, `Raises:`, and `Examples:` sections
129+
- Type information consistent with function signatures
130+
- Consistent capitalization and punctuation
131+
132+
Example:
133+
```python
134+
def example_function(param1: str, param2: Optional[int] = None) -> dict[str, Any]:
135+
"""
136+
Brief description of the function.
137+
138+
Longer description if needed, explaining the function's behavior,
139+
side effects, or important usage notes.
140+
141+
Args:
142+
param1 (str): Description of the first parameter.
143+
param2 (Optional[int]): Description of the optional parameter.
144+
145+
Returns:
146+
dict[str, Any]: Description of the return value.
147+
148+
Raises:
149+
ValueError: When this exception might be raised.
150+
151+
Examples:
152+
>>> result = example_function("hello", 42)
153+
>>> print(result)
154+
{'status': 'success', 'data': 'hello'}
155+
"""
156+
```
157+
158+
## License
159+
160+
MIT License. See the [LICENSE](LICENSE) file for details.
161+
162+
## Links
163+
164+
- [PyPI Package](https://pypi.org/project/cocalc-api/)
165+
- [CoCalc Website](https://cocalc.com)
166+
- [Documentation](https://cocalc.com/api/python)
167+
- [Source Code](https://github.com/sagemathinc/cocalc/tree/master/src/python/cocalc-api)
168+
- [Issue Tracker](https://github.com/sagemathinc/cocalc/issues)

src/python/cocalc-api/pyproject.toml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,17 @@ Issues = "https://github.com/sagemathinc/cocalc/issues"
2323
python_version = "3.13"
2424
# strict = true
2525
# disallow_untyped_defs = true
26+
# Ignore empty-body errors for decorator-implemented methods
27+
disable_error_code = ["empty-body"]
28+
29+
[tool.pyright]
30+
# Ignore return type errors for decorator-implemented methods
31+
reportReturnType = false
32+
33+
[tool.yapf]
34+
based_on_style = "pep8"
35+
column_limit = 150
36+
indent_width = 4
2637

2738
[tool.ruff]
2839
line-length = 150
@@ -35,6 +46,8 @@ dev = [
3546
"mkdocs-material",
3647
"mkdocstrings[python]",
3748
"mypy",
49+
"pyright",
3850
"pytest>=8.4.1",
3951
"ruff>=0.12.11",
52+
"yapf",
4053
]

0 commit comments

Comments
 (0)