Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog

## [1.12.0] - 2026-SEP-01

### Added

- Generated API error bodies now live in `prime_sdk/generated/errors.py`, including a shared `ErrorResponse` base class. Domain models remain in `prime_sdk/generated/models.py`.
- `Client.request` parses JSON error bodies (`code`, `message`, `subcode`, `trace_id`) and raises HTTP-status subclasses of `PrimeApiError`: `PrimeBadRequestError`, `PrimeUnauthorizedError`, `PrimeForbiddenError`, `PrimeNotFoundError`, `PrimeTooManyRequestsError`, `PrimeInternalServerError`, `PrimeNotImplementedError`, and `PrimeServiceUnavailableError`.
- `PrimeApiError` exposes `code`, `subcode`, `trace_id`, and a generated `body` dataclass when the API returns JSON.
- Advanced example `prime_sdk/examples/advanced/handle_api_errors.py` shows catching HTTP-status subclasses and printing structured error fields.

### Changed

- Renamed `PrimeSDKError` to `PrimeSdkError` and `PrimeAPIError` to `PrimeApiError`. The previous names remain as aliases.

## [1.11.0] - 2026-AUG-28

### Added
Expand Down
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ promote-titles:

gen-models: promote-titles
cd apiSpec && python3 generate_models.py
ruff format prime_sdk/generated/models.py
ruff format prime_sdk/generated/models.py prime_sdk/generated/errors.py

update-spec: fetch-spec gen-models

check-models: gen-models
@git diff --exit-code prime_sdk/generated/models.py
@git diff --exit-code prime_sdk/generated/models.py prime_sdk/generated/errors.py

# Format and lint all Python code (matches CI)
format:
Expand Down
29 changes: 26 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ The SDK uses a service-based architecture where each domain (portfolios, orders,
```python
from prime_sdk.credentials import Credentials
from prime_sdk.client import Client
from prime_sdk.exceptions import PrimeApiError
from prime_sdk.services.portfolios import PortfoliosService, ListPortfoliosRequest

# Initialize credentials and client
Expand All @@ -106,8 +107,29 @@ request = ListPortfoliosRequest()
try:
response = portfolios_service.list_portfolios(request)
print(response)
except Exception as e:
except PrimeApiError as e:
print(f"Failed to list portfolios: {e}")
print(f"code={e.code} subcode={e.subcode} trace_id={e.trace_id}")
```

API failures raise `PrimeApiError` (or an HTTP-status subclass such as `PrimeNotFoundError`). The exception includes `status_code`, `message`, and when the API returns a JSON error body, `code`, `subcode`, `trace_id`, and a generated `body` dataclass.

```python
from prime_sdk import PrimeApiError, PrimeNotFoundError

try:
response = portfolios_service.list_portfolios(request)
except PrimeNotFoundError as e:
print(e.trace_id)
except PrimeApiError as e:
print(e.status_code, e.message, e.code)
```

A full walkthrough that looks up a missing order (HTTP 404) and optionally submits an invalid create-order request (HTTP 400) lives in [`prime_sdk/examples/advanced/handle_api_errors.py`](prime_sdk/examples/advanced/handle_api_errors.py):

```bash
python prime_sdk/examples/advanced/handle_api_errors.py
python prime_sdk/examples/advanced/handle_api_errors.py --demo-validation
```

#### Available Services
Expand Down Expand Up @@ -295,7 +317,8 @@ prime_sdk/
├── model.py # Public model re-exports (backward-compatible)
├── model_manual.py # Hand-maintained model extensions
├── generated/
│ └── models.py # Generated dataclasses from OpenAPI (schemas + request bodies; do not edit)
│ ├── models.py # Generated dataclasses from OpenAPI (schemas + request bodies; do not edit)
│ └── errors.py # Generated API error bodies and route lookup (do not edit)
└── services/ # Service modules
├── portfolios/ # Portfolio operations
├── orders/ # Order management
Expand All @@ -306,7 +329,7 @@ prime_sdk/
apiSpec/
├── prime-public-api-spec.yaml
├── promote_titles.py # Promotes spec titles to descriptions
├── generate_models.py # Generates prime_sdk/generated/models.py
├── generate_models.py # Generates prime_sdk/generated/models.py and errors.py
└── model_config.py # Backward-compatibility aliases and field rules
```

Expand Down
217 changes: 208 additions & 9 deletions apiSpec/generate_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,20 @@
ROOT = Path(__file__).resolve().parents[1]
AUGMENTED_SPEC_PATH = Path(__file__).parent / ".prime-public-api-spec.augmented.yaml"
OUTPUT_PATH = ROOT / "prime_sdk" / "generated" / "models.py"
ERRORS_OUTPUT_PATH = ROOT / "prime_sdk" / "generated" / "errors.py"
SURFACE_PATH = ROOT / "tests" / "fixtures" / "model_surface.json"
TYPES_PATH = ROOT / "tests" / "fixtures" / "model_types.json"

ERROR_RESPONSE_BASE_FIELDS = ("code", "message", "subcode", "trace_id")
SHARED_ERROR_STATUS_BY_CLASS = {
"UnauthorizedErrorResponse": 401,
"TooManyRequestsErrorResponse": 429,
"InternalServerErrorResponse": 500,
"NotImplementedErrorResponse": 501,
"ServiceUnavailableErrorResponse": 503,
}
HTTP_METHODS = frozenset({"get", "post", "put", "patch", "delete"})

FILE_HEADER = """\
# Copyright 2026-present Coinbase Global, Inc.
#
Expand Down Expand Up @@ -113,6 +124,10 @@ def class_name_for_schema(schema_key: str) -> str:
return short_name(schema_key)


def is_error_response_name(class_short: str) -> bool:
return class_short.endswith("ErrorResponse")


def load_compat() -> tuple[dict[str, list[str]], dict[str, dict[str, str]]]:
surface = json.loads(SURFACE_PATH.read_text(encoding="utf-8"))
types = json.loads(TYPES_PATH.read_text(encoding="utf-8"))
Expand Down Expand Up @@ -584,6 +599,7 @@ def render_class(
field_order: list[str] | None = None,
field_locations: dict[str, str] | None = None,
schemas: dict[str, Any] | None = None,
base_class: str | None = None,
) -> str:
renames = FIELD_RENAMES.get(class_short, {})
if class_summary is None:
Expand All @@ -605,7 +621,10 @@ def render_class(
)

decorator = "@dataclass(kw_only=True)" if kw_only else "@dataclass"
lines = [decorator, f"class {class_short}:"]
class_decl = (
f"class {class_short}({base_class}):" if base_class else f"class {class_short}:"
)
lines = [decorator, class_decl]
if docstring_lines:
lines.append(' """')
for line in docstring_lines:
Expand All @@ -629,24 +648,182 @@ def render_class(
return "\n".join(lines)


def generate_models() -> str:
def load_spec() -> dict[str, Any]:
with AUGMENTED_SPEC_PATH.open(encoding="utf-8") as handle:
spec = yaml.safe_load(handle)
return yaml.safe_load(handle)


def collect_object_schemas(spec: dict[str, Any]) -> dict[str, dict[str, Any]]:
schemas: dict[str, Any] = spec["components"]["schemas"]
object_schemas = {
return {
key: value
for key, value in schemas.items()
if isinstance(value, dict)
and "enum" not in value
and not key.startswith("google.")
}

compat_surface, compat_types = load_compat()
order = topological_sort(object_schemas, schemas)

def openapi_path_to_pattern(path: str) -> str:
stripped = re.sub(r"^/v\d+", "", path)
pieces: list[str] = []
last = 0
for match in re.finditer(r"\{[^}/]+\}", stripped):
pieces.append(re.escape(stripped[last : match.start()]))
pieces.append(r"[^/]+")
last = match.end()
pieces.append(re.escape(stripped[last:]))
return "^" + "".join(pieces) + "$"


def collect_error_routes(
spec: dict[str, Any], schemas: dict[str, Any]
) -> list[tuple[str, str, dict[int, str]]]:
routes: list[tuple[str, str, dict[int, str]]] = []
for path, methods in (spec.get("paths") or {}).items():
if not isinstance(methods, dict):
continue
for method, operation in methods.items():
if method.lower() not in HTTP_METHODS or not isinstance(operation, dict):
continue
status_map: dict[int, str] = {}
for status, response in (operation.get("responses") or {}).items():
if not str(status).isdigit() or not isinstance(response, dict):
continue
status_code = int(status)
if status_code < 400:
continue
schema = (
response.get("content", {})
.get("application/json", {})
.get("schema")
)
if not isinstance(schema, dict):
continue
ref = schema.get("$ref")
if not isinstance(ref, str):
continue
class_name = resolve_ref(ref, schemas)
if class_name and is_error_response_name(class_name):
status_map[status_code] = class_name
if status_map:
routes.append((method.upper(), path, status_map))
return routes


def generate_errors(
spec: dict[str, Any],
schemas: dict[str, Any],
error_schemas: dict[str, dict[str, Any]],
compat_surface: dict[str, list[str]],
compat_types: dict[str, dict[str, str]],
) -> str:
schema_by_short: dict[str, tuple[str, dict[str, Any]]] = {}
for schema_key, schema in object_schemas.items():
for schema_key, schema in error_schemas.items():
schema_by_short[class_name_for_schema(schema_key)] = (schema_key, schema)

body_parts: list[str] = [
"@dataclass",
"class ErrorResponse:",
' """Shared Prime API error body fields."""',
"",
" code: str = None",
" message: str = None",
" subcode: str = None",
" trace_id: str = None",
"",
"",
]

for class_short in sorted(schema_by_short):
schema_key, schema = schema_by_short[class_short]
fields = [
(name, field_type)
for name, field_type in collect_fields(
schema_key, schema, schemas, compat_surface, compat_types
)
if name not in ERROR_RESPONSE_BASE_FIELDS
]
body_parts.append(
render_class(
class_short,
fields,
schema,
schemas=schemas,
base_class="ErrorResponse",
)
)
body_parts.append("")

routes = collect_error_routes(spec, schemas)
body_parts.append(
"ERROR_ROUTE_TABLE: list[tuple[str, re.Pattern[str], dict[int, type[ErrorResponse]]]] = ["
)
for method, path, status_map in routes:
pattern = openapi_path_to_pattern(path)
items = ", ".join(
f"{status}: {cls}" for status, cls in sorted(status_map.items())
)
body_parts.append(f" ({method!r}, re.compile({pattern!r}), {{{items}}}),")
body_parts.append("]")
body_parts.append("")

shared_items = ", ".join(
f"{status}: {cls}"
for cls, status in sorted(
SHARED_ERROR_STATUS_BY_CLASS.items(), key=lambda item: item[1]
)
if cls in schema_by_short
)
body_parts.append(
f"SHARED_ERROR_BY_STATUS: dict[int, type[ErrorResponse]] = {{{shared_items}}}"
)
body_parts.append("")
body_parts.extend(
[
"def resolve_error_class(",
" method: str, path: str, status_code: int",
") -> type[ErrorResponse]:",
' """Return the generated error body class for a request."""',
" method_upper = method.upper()",
" for http_method, pattern, statuses in ERROR_ROUTE_TABLE:",
" if http_method != method_upper:",
" continue",
" if pattern.match(path):",
" matched = statuses.get(status_code)",
" if matched is not None:",
" return matched",
" break",
" return SHARED_ERROR_BY_STATUS.get(status_code, ErrorResponse)",
"",
]
)

exported = sorted(["ErrorResponse", "resolve_error_class", *schema_by_short])
body_parts.append("__all__ = [")
for name in exported:
body_parts.append(f" {name!r},")
body_parts.append("]")
body_parts.append("")

header = FILE_HEADER.replace(
"from dataclasses import dataclass\n",
"import re\nfrom dataclasses import dataclass\n",
)
return header + "\n".join(body_parts) + "\n"


def generate_models(
spec: dict[str, Any],
schemas: dict[str, Any],
model_schemas: dict[str, dict[str, Any]],
compat_surface: dict[str, list[str]],
compat_types: dict[str, dict[str, str]],
) -> str:
order = topological_sort(model_schemas, schemas)

schema_by_short: dict[str, tuple[str, dict[str, Any]]] = {}
for schema_key, schema in model_schemas.items():
schema_by_short[class_name_for_schema(schema_key)] = (schema_key, schema)

enum_imports = {
Expand Down Expand Up @@ -725,6 +902,8 @@ def generate_models() -> str:

alias_lines = ["", "# Backward-compatible public aliases"]
for public_name, generated_name in sorted(CLASS_ALIASES.items()):
if is_error_response_name(generated_name):
continue
alias_lines.append(f"{public_name} = {generated_name}")

body_text = "\n".join(body_parts)
Expand All @@ -747,10 +926,30 @@ def main() -> None:
f"Augmented spec not found at {AUGMENTED_SPEC_PATH}. Run `make promote-titles` first."
)

spec = load_spec()
object_schemas = collect_object_schemas(spec)
schemas: dict[str, Any] = spec["components"]["schemas"]
error_schemas = {
key: value
for key, value in object_schemas.items()
if is_error_response_name(class_name_for_schema(key))
}
model_schemas = {
key: value for key, value in object_schemas.items() if key not in error_schemas
}
compat_surface, compat_types = load_compat()

OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
content = generate_models()
OUTPUT_PATH.write_text(content, encoding="utf-8")
models_content = generate_models(
spec, schemas, model_schemas, compat_surface, compat_types
)
errors_content = generate_errors(
spec, schemas, error_schemas, compat_surface, compat_types
)
OUTPUT_PATH.write_text(models_content, encoding="utf-8")
ERRORS_OUTPUT_PATH.write_text(errors_content, encoding="utf-8")
print(f"Generated {OUTPUT_PATH}")
print(f"Generated {ERRORS_OUTPUT_PATH}")


if __name__ == "__main__":
Expand Down
Loading
Loading