Skip to content

Commit d9eeaeb

Browse files
Update api spec (#791)
* YOYO NEW API SPEC! * Fix generation for project uploads and archive downloads --------- Co-authored-by: zoo-github-actions-auth[bot] <zoo-github-actions-auth[bot]@users.noreply.github.com> Co-authored-by: Adam Sunderland <iterion@gmail.com>
1 parent e789475 commit d9eeaeb

49 files changed

Lines changed: 7372 additions & 4371 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,56 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
## Unreleased
99

10+
### Changed
11+
12+
- Regenerate from API `main` at `b8a9549c95e9e59d914a783484b67cbef798b353`.
13+
- Generate typed metadata and file attachment arguments for project creation,
14+
replacement, and version saves. Attachment keys become relative project
15+
filenames, including when uploading bytes or streams. Project replacement uses
16+
PUT, and version saves accept an optional `idempotency_key`.
17+
- Project downloads now stream TAR or ZIP archives through context managers.
18+
File ID lists use the API's comma-separated query encoding.
19+
- Factory quote retrieval and acceptance now require a payment attempt ID.
20+
KCL migrations use the ordinary Copilot connection; the dedicated migration
21+
WebSocket and application acknowledgement models are no longer in the spec.
22+
23+
### Migration
24+
25+
- Pass a `CreateProjectRequest`, `UpdateProjectRequest`, or
26+
`CreateProjectVersionRequest` as `body`, plus a nonempty `file_attachments`
27+
mapping. Keys are relative project paths; `body` and `event` are reserved.
28+
Upload a complete project snapshot, including unchanged files:
29+
30+
```python
31+
from pathlib import Path
32+
from kittycad.models import CreateProjectRequest
33+
34+
project = client.projects.create_project(
35+
body=CreateProjectRequest(title="Bracket"),
36+
file_attachments={"main.kcl": Path("main.kcl")},
37+
)
38+
```
39+
40+
- Read downloads inside `with client.projects.download_project(id) as response`
41+
and consume `response.iter_bytes()`. For the async client, use
42+
`async with client.projects.download_project(id) as response` and
43+
`response.aiter_bytes()`. The same pattern applies to project versions, public
44+
projects, and `client.hidden.download_shared_project(key)`. The methods return
45+
an HTTP response containing archive bytes instead of parsing JSON.
46+
- Replace `client.factory.preview_user_factory_quote` and
47+
`preview_org_factory_quote` with `get_user_factory_quote` and
48+
`get_org_factory_quote`. Generate a `payment_attempt_id` UUID once for an
49+
explicit acceptance, pass it to quote retrieval and `accept_*_factory_quote`,
50+
and retain it across transport retries. A new attempt after a confirmed decline
51+
needs a new UUID.
52+
- Replace `client.ml.kcl_migration_ws` with `client.ml.ml_copilot_ws` and send
53+
the `migrate_kcl` variant of `MlCopilotClientMessage`, constructed with
54+
`OptionMigrateKcl(request=...)` from `kittycad.models.ml_copilot_client_message`.
55+
Handle ordinary Copilot progress and final messages. Remove imports of the
56+
dedicated `KclMigrationClientMessage`, `KclMigrationServerMessage`, history,
57+
and application acknowledgement models, along with Apply/Undo/Redo
58+
acknowledgement messages.
59+
1060
## v1.12.0
1161

1262
### Added

‎generate/file_operation_detection.py‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from typing import Any, Dict, List, Optional
88

9+
from .schema_utils import get_request_body_type_schema
910
from .utils import (
1011
FILE_DOWNLOAD_CONTENT_TYPES,
1112
FILE_UPLOAD_CONTENT_TYPES,
@@ -284,6 +285,12 @@ def extract_file_parameter_info(endpoint: dict, data: dict) -> Dict[str, Any]:
284285
.get("schema", {})
285286
)
286287
part_schema = multipart_schema.get("additionalProperties")
288+
info["filenames_from_keys"] = (
289+
isinstance(part_schema, dict) and part_schema.get("format") == "binary"
290+
)
291+
info["requires_file_attachments"] = multipart_schema.get("minProperties", 0) > len(
292+
multipart_schema.get("properties", {})
293+
)
287294
info["binary_or_files"] = (
288295
"application/octet-stream" in info["upload_content_types"]
289296
and isinstance(part_schema, dict)
@@ -296,8 +303,12 @@ def extract_file_parameter_info(endpoint: dict, data: dict) -> Dict[str, Any]:
296303
info["download_strategy"] = determine_download_strategy(endpoint)
297304
info["download_content_types"] = get_download_content_types(endpoint)
298305

299-
info["binary_response"] = (
300-
"application/octet-stream" in info["download_content_types"]
306+
info["binary_response"] = any(
307+
content_type == "application/octet-stream"
308+
or media.get("schema", {}).get("format") == "binary"
309+
for status, response in endpoint.get("responses", {}).items()
310+
if str(status).startswith("2")
311+
for content_type, media in response.get("content", {}).items()
301312
)
302313

303314
# Check for JSON body + multipart pattern
@@ -343,14 +354,8 @@ def _extract_json_body_schema(endpoint: dict, data: dict) -> Optional[str]:
343354
if "schema" not in multipart_content:
344355
return None
345356

346-
schema = multipart_content["schema"]
347-
348-
# Handle $ref schemas
349-
if "$ref" in schema:
350-
ref_name = resolve_schema_ref(schema["$ref"])
351-
return ref_name
352-
353-
return None
357+
name, _ = get_request_body_type_schema(endpoint, data)
358+
return name
354359

355360

356361
def _extract_multipart_file_params(endpoint: dict, data: dict) -> List[Dict[str, Any]]:

‎generate/function_generators.py‎

Lines changed: 9 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -10,64 +10,14 @@
1010
)
1111

1212

13-
def _generate_docstring_with_examples(
14-
endpoint: dict, file_info: dict, request_body_type: str | None
15-
) -> str:
16-
"""Generate docstring with usage examples for endpoints."""
17-
base_docs = endpoint.get("description", endpoint.get("summary", ""))
13+
def _generate_docstring_with_examples(endpoint: dict, file_info: dict) -> str:
14+
"""Reuse the generated endpoint example for multipart method documentation."""
15+
docs = endpoint.get("description", endpoint.get("summary", ""))
16+
example = endpoint.get("x-python", {}).get("example")
17+
if file_info.get("has_json_body_multipart") and example:
18+
docs += f"\n\nExamples:\n```python\n{example}\n```"
1819
# Preserve literal backslashes when the docs are embedded in Python source.
19-
base_docs = base_docs.replace("\\", "\\\\")
20-
21-
# Add examples for JSON + multipart endpoints
22-
if file_info.get("has_json_body_multipart", False):
23-
examples = f"""
24-
25-
Examples:
26-
Basic usage with file attachments:
27-
28-
```python
29-
from pathlib import Path
30-
from kittycad.models.{camel_to_snake(request_body_type) if request_body_type else "text_to_cad_multi_file_iteration_body"} import {request_body_type or "TextToCadMultiFileIterationBody"}
31-
32-
# Create the request body
33-
body = {request_body_type or "TextToCadMultiFileIterationBody"}(
34-
# Add your parameters here
35-
)
36-
37-
# Prepare file attachments
38-
file_attachments = {{
39-
"main.kcl": Path("path/to/main.kcl"),
40-
"helper.kcl": Path("path/to/helper.kcl"),
41-
}}
42-
43-
# Make the request
44-
result = client.{camel_to_snake(endpoint.get("operationId", ""))}(
45-
body=body,
46-
file_attachments=file_attachments,
47-
)
48-
```
49-
50-
Using different file types:
51-
52-
```python
53-
from io import BytesIO
54-
55-
# Mix of file paths and file-like objects
56-
file_attachments = {{
57-
"main.kcl": Path("main.kcl"),
58-
"config.kcl": BytesIO(b"// KCL configuration"),
59-
"data.json": "path/to/data.json",
60-
}}
61-
62-
result = client.{camel_to_snake(endpoint.get("operationId", ""))}(
63-
body=body,
64-
file_attachments=file_attachments,
65-
)
66-
```
67-
"""
68-
return base_docs + examples
69-
70-
return base_docs
20+
return docs.replace("\\", "\\\\")
7121

7222

7323
def generate_sync_function(path: str, method: str, endpoint: dict, data: dict) -> str:
@@ -158,9 +108,7 @@ def generate_sync_function(path: str, method: str, endpoint: dict, data: dict) -
158108
"has_request_body": has_body_param,
159109
"request_body_type": request_body_type,
160110
"args": args,
161-
"docs": _generate_docstring_with_examples(
162-
endpoint, file_info, request_body_type
163-
),
111+
"docs": _generate_docstring_with_examples(endpoint, file_info),
164112
"file_info": file_info, # Add file operation info to context
165113
}
166114

@@ -262,9 +210,7 @@ def generate_async_function(path: str, method: str, endpoint: dict, data: dict)
262210
"has_request_body": has_body_param,
263211
"request_body_type": request_body_type,
264212
"args": args,
265-
"docs": _generate_docstring_with_examples(
266-
endpoint, file_info, request_body_type
267-
),
213+
"docs": _generate_docstring_with_examples(endpoint, file_info),
268214
"file_info": file_info, # Add file operation info to context
269215
}
270216

‎generate/generate.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
deduplicate_imports,
2727
enum_member_name,
2828
parameter_name,
29+
render_template_to_file,
2930
to_pascal_case,
3031
)
3132

@@ -42,6 +43,10 @@ def main():
4243
logging.info("opening spec file: %s", spec_path)
4344
parser = BaseParser(spec_path)
4445

46+
render_template_to_file(
47+
"multipart.py.jinja2", {}, os.path.join(cwd, "kittycad", "_multipart.py")
48+
)
49+
4550
# Generate the types.
4651
generate_types(cwd, parser.specification)
4752

@@ -399,8 +404,12 @@ def generate_type_and_example_python(
399404
return generate_type_and_example_python(
400405
parameter_type, ref_schema, data, None, None
401406
)
402-
elif "description" in schema and not any(
403-
key in schema for key in ["type", "$ref", "oneOf", "anyOf", "allOf"]
407+
elif (
408+
schema == {}
409+
or "description" in schema
410+
and not any(
411+
key in schema for key in ["type", "$ref", "oneOf", "anyOf", "allOf"]
412+
)
404413
):
405414
# Match the model generator's unconstrained JSON type.
406415
parameter_type = "Any"

‎generate/run.sh‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,14 @@
22
set -e
33
set -o pipefail
44

5-
git add kittycad/models/base64data.py || true
6-
git add kittycad/models/empty.py || true
7-
8-
9-
# Cleanup old stuff.
10-
rm -rf kittycad/models
5+
# Remove generated models while preserving the shared model helpers.
6+
for model in kittycad/models/*.py; do
7+
case "$model" in
8+
*/base.py|*/base64data.py|*/empty.py) ;;
9+
*) rm "$model" ;;
10+
esac
11+
done
1112
rm -rf kittycad/api
12-
git checkout kittycad/models/base64data.py || true
13-
git checkout kittycad/models/empty.py || true
14-
git checkout kittycad/models/base.py || true
1513

1614
# Generate new.
1715
uv run python -m generate.generate

‎generate/schema_utils.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,10 @@ def get_endpoint_refs(endpoint: dict, data: dict) -> List[str]:
110110
raise Exception("Unknown type ", json["type"])
111111
else:
112112
refs.append("dict")
113-
elif content_type == "application/octet-stream":
113+
elif (
114+
content_type == "application/octet-stream"
115+
or content[content_type].get("schema", {}).get("format") == "binary"
116+
):
114117
continue # Streamed responses have no JSON model.
115118
elif content_type == "*/*":
116119
s = content[content_type]["schema"]
@@ -178,6 +181,8 @@ def get_request_body_refs(endpoint: dict) -> List[str]:
178181
refs.append(ref)
179182
elif content_type == "multipart/form-data":
180183
form = content[content_type]["schema"]
184+
# A multipart envelope can contain a named JSON metadata part.
185+
form = form.get("properties", {}).get("body", form)
181186
if "$ref" in form:
182187
ref = resolve_schema_ref(form["$ref"])
183188
refs.append(ref)
@@ -232,6 +237,7 @@ def get_request_body_type_schema(
232237
raise Exception("not a ref")
233238
elif content_type == "multipart/form-data":
234239
form = content[content_type]["schema"]
240+
form = form.get("properties", {}).get("body", form)
235241
if "$ref" in form:
236242
ref = resolve_schema_ref(form["$ref"])
237243
type_schema = data["components"]["schemas"][ref]
@@ -348,6 +354,8 @@ def get_function_result_type(
348354

349355

350356
def get_type_name(schema: dict) -> str:
357+
if schema == {}:
358+
return "Any"
351359
if "type" in schema:
352360
if schema["type"] == "string":
353361
if "format" in schema:

‎generate/templates/README.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -184,4 +184,9 @@ To migrate from legacy templates to the universal template:
184184
1. **Use template comments**: Add `{# DEBUG: variable_name = {{ variable_name }} #}`
185185
2. **Check context**: Print context dictionary before rendering
186186
3. **Validate macros**: Test macros independently with minimal context
187-
4. **Compare outputs**: Diff generated code with expected results
187+
4. **Compare outputs**: Diff generated code with expected results
188+
189+
## Multipart runtime helper
190+
191+
`multipart.py.jinja2` is the source for `kittycad/_multipart.py`. Change the
192+
template and run `just generate` when updating multipart upload behavior.

‎generate/templates/async_function.py.jinja2‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@
2121
{% for arg in args %}
2222
{% if arg.in_query %}
2323
if {{ arg.name }} is not None:
24-
url = str(httpx.URL(url).copy_add_param("{{ arg.name }}", {% if "datetime" in arg.type %}{{ arg.name }}.isoformat(){% elif "bool" in arg.type %}str({{ arg.name }}).lower(){% else %}str({{ arg.name }}){% endif %}))
24+
url = str(httpx.URL(url).copy_add_param("{{ arg.name }}", {% if arg.is_csv %}",".join(str(value) for value in {{ arg.name }}){% elif "datetime" in arg.type %}{{ arg.name }}.isoformat(){% elif "bool" in arg.type %}str({{ arg.name }}).lower(){% else %}str({{ arg.name }}){% endif %}))
2525
{% endif %}
2626
{% endfor %}
2727

2828
_client = self.client.get_http_client()
2929
{% set header_args = args|selectattr("header_name")|list %}
30-
{% if header_args or file_info.binary_or_files %}
30+
{% if header_args or file_info.binary_or_files or file_info.has_json_body_multipart %}
3131
headers = httpx.Headers(self.client.get_headers())
3232
{% if header_args and has_request_body and request_body_type != "bytes" and not file_info.has_json_body_multipart %}
3333
headers.setdefault("Content-Type", "application/json")
@@ -54,13 +54,19 @@
5454
headers["Content-Type"] = "application/octet-stream"
5555
response = await _client.{{ method }}(url, content=body, headers=headers, timeout=request_timeout)
5656
{% elif file_info.has_json_body_multipart %}
57-
# JSON + multipart endpoint
57+
{% if file_info.requires_file_attachments %}
58+
if not file_attachments:
59+
raise ValueError("At least one file attachment is required")
60+
{% endif %}
61+
headers.pop("Content-Type", None)
5862
response = await upload_json_multipart_async(
5963
client=_client,
6064
url=url,
65+
method="{{ method|upper }}",
6166
json_body=body,
67+
filenames_from_keys={{ file_info.filenames_from_keys }},
6268
file_attachments=file_attachments,
63-
headers={% if header_args %}headers{% else %}self.client.get_headers(){% endif %},
69+
headers=headers,
6470
)
6571
{% else %}
6672
response = await _client.{{ method }}(

‎generate/templates/async_paginated_function.py.jinja2‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@
6565
{% for arg in args %}
6666
{% if arg.in_query %}
6767
if "{{ arg.name }}" in kwargs and kwargs["{{ arg.name }}"] is not None:
68-
url = str(httpx.URL(url).copy_add_param("{{ arg.name }}", {% if "datetime" in arg.type %}kwargs["{{ arg.name }}"].isoformat(){% elif "bool" in arg.type %}str(kwargs["{{ arg.name }}"]).lower(){% else %}str(kwargs["{{ arg.name }}"]){% endif %}))
68+
url = str(httpx.URL(url).copy_add_param("{{ arg.name }}", {% if arg.is_csv %}",".join(str(value) for value in kwargs["{{ arg.name }}"]){% elif "datetime" in arg.type %}kwargs["{{ arg.name }}"].isoformat(){% elif "bool" in arg.type %}str(kwargs["{{ arg.name }}"]).lower(){% else %}str(kwargs["{{ arg.name }}"]){% endif %}))
6969
{% endif %}
7070
{% endfor %}
7171

0 commit comments

Comments
 (0)