Repository navigation
Conversation
…tch its model Resource methods validated responses with `Model.model_validate()`, so a response that did not match raised a bare `pydantic.ValidationError`. It does not inherit from `ApifyClientError`, so `except ApifyClientError` handlers missed it, and the message did not say which request failed. Responses are now validated through `validate_response()`, which raises `ResponseValidationError`. It subclasses both `ApifyClientError` and `pydantic.ValidationError`, so existing handlers for the pydantic error or `ValueError` keep working. It carries the HTTP method and the URL of the request without its query string, and the original error as `__cause__`. `UserClient.get()` still catches the raw error from the private model to fall back to the public one. Fixes apify#1170
ResponseValidationError when an API response does not match its modelResponseValidationError when an API response does not match its model
| return model.model_validate(data) | ||
| except ValidationError as exc: | ||
| # The details `errors()` returns are accepted as input details, only their declared types differ. | ||
| line_errors = cast('list[InitErrorDetails]', exc.errors(include_url=False)) |
There was a problem hiding this comment.
Important: from_exception_data() rejects some entries that errors() returns. An EmailStr failure raises TypeError: ValueError: 'error' required in context, and a PydanticCustomError raises KeyError: Invalid error type. The caller then gets an exception that none of ValidationError, ValueError or ApifyClientError catches. No response model hits this today, but a regenerated model with an email field would. Could you fall back to PydanticCustomError(e['type'], e['msg']) entries when the rebuild fails, fix the comment above, and add a test with an EmailStr model?
✍️ Drafted by Claude Code
| line_errors = cast('list[InitErrorDetails]', exc.errors(include_url=False)) | ||
| error = ResponseValidationError.from_exception_data(exc.title, line_errors) | ||
|
|
||
| error.method = log_context.method.get() |
There was a problem hiding this comment.
Nit: log_context.method and log_context.url are never reset. With a custom client that replaces call(), the error names the previous request from the same thread or task, not None. Resetting both in the _injects_client_details_to_log_context wrappers (_logging.py) would fix it.
✍️ Drafted by Claude Code
|
|
||
| ## Response validation errors | ||
|
|
||
| The client validates every API response against its model. When a response does not match, for example because the API changed ahead of the client, it raises a <ApiLink to="class/ResponseValidationError">`ResponseValidationError`</ApiLink> instead of a bare `pydantic.ValidationError`. It inherits from <ApiLink to="class/ApifyClientError">`ApifyClientError`</ApiLink>, so a handler for client errors catches it. It also inherits from `pydantic.ValidationError`, so `errors()` lists the individual mismatches and an existing `except pydantic.ValidationError` or `except ValueError` handler keeps working. The `method` and `url` attributes name the request whose response failed, and `__cause__` holds the original validation error. |
There was a problem hiding this comment.
Nit: Dataset items, KVS records and logs are not validated, so "every API response" is too broad. Maybe "Most API responses". Also, the existing last line ("For a complete list of error classes, see the ApifyApiError reference") now ends up under this section. Could you move the section below it?
✍️ Drafted by Claude Code
| pytest.param('/v2/actor-runs/run-1', 'GET', lambda c: c.run('run-1').wait_for_finish(), id='wait_for_finish'), | ||
| ] | ||
|
|
||
| _ASYNC_CASES = [ |
There was a problem hiding this comment.
Nit: _ASYNC_CASES is a copy of _SYNC_CASES, so one list can serve both tests. An async UserClient.get() fallback test is also missing.
✍️ Drafted by Claude Code
apify-factory
left a comment
There was a problem hiding this comment.
Looks good, nothing blocking.
🏭 Factory review — ℹ️ not auto-approved
This change was reviewed but cannot be auto-approved: a gate failed, so the review cannot end in an approval.
| check | result |
|---|---|
| Static gates | ❌ 11/16 — author-allowed, same-repo, max-files, max-lines, file-extensions |
| Review findings | ✅ none |
| Reviewer escalation | ❌ Changes the exception type raised by every resource method and adds a new exported error class, which is a public contract change. |
Juror 1 — claude-sonnet-5-5, adversarial |
⏭️ skipped — a gate failed |
Why it was not auto-approved
Failed gates:
author-allowed: emreocell: not a member of apify/product-engineeringsame-repo: head repo is emreocell/apify-client-pythonmax-files: 31 changed files: over the limit 10max-lines: 533 changed lines: over the limit 200 (+376/-157)file-extensions: disallowed extension: docs/02_concepts/04_error_handling.mdx
The comments above are the review itself; this section only explains the approval decision. Push a change and request @apify-factory again to re-run it, or ask a human to review.
Reviewed 08f8c7910 · Review details on the dashboard · workflow run
| url: The URL of that request, without query parameters (if available). | ||
| """ | ||
|
|
||
| method: str | None = None |
There was a problem hiding this comment.
[apify/apify-client-python:client-parity] Nit: ApifyApiError in this module exposes the request method as http_method, so naming this attribute method gives the two client errors different names for the same field; call it http_method here too.
Matches ApifyApiError, which exposes the same field as http_method (review nit).
Fixes #1170
Problem
Resource methods turn API responses into models with
<Model>.model_validate(...). A response that does not match the model raises a barepydantic.ValidationError. It does not inherit fromApifyClientError, soexcept ApifyClientErrorhandlers miss it, and its message does not say which request failed.Minimal reproduction against a local server that returns a body of the wrong shape:
Before the change, the call raises
pydantic_core.ValidationError("8 validation errors for DatasetResponse"), which the handler above does not catch.Fix
ResponseValidationError(ApifyClientError, pydantic.ValidationError)is added toapify_client.errors. It exposesmethodandurland keeps the original error as__cause__.urlhas no query string, in line with howApifyApiErrorreportspath. Because it subclassespydantic.ValidationError, existingexcept pydantic.ValidationErrorandexcept ValueErrorhandlers keep working, so this is not a breaking change.errors()returns the same entries as before.validate_response(model, data)in_utils/http.pyreplaces the directmodel_validate()call on response data at every resource client call site (sync and async). It rebuilds the error withfrom_exception_data(). The method and URL come from the existinglog_contextvariables thatHttpClient.call()already sets for every request, so no call site needed new arguments.UserClient.get()still validates the private model directly and catches the rawValidationErrorto fall back to the public model. The public-model validation goes through the helper, so a body that fits neither model raisesResponseValidationError.TaskInput,CreateVersionRequest,RequestWithoutId, and similar) is left as it was, since no response is involved.docs/02_concepts/04_error_handling.mdx.Tests
tests/unit/test_response_validation.py(28 test cases across theimpitandhttpx2transports, sync and async):ResponseValidationErrorfor a single GET, a collection list, a POST (get_or_create), a PUT (update) andwait_for_finish, and the error is anApifyClientError, apydantic.ValidationErrorand aValueError, with the rightmethod, aurlending in the request path, non-emptyerrors(), the pydantic error as__cause__, and the request instr(error)urlcarries no query stringUserClient.get()still falls back to the public model, and raisesResponseValidationErrorwhen neither model fitspydantic.ValidationErrorVerification
Run on Windows with Python 3.12.10:
ResponseValidationErroraliased toApifyClientErrorreported 24 failed and 4 passed on a clean checkout ofmaster. The 4 that passed are the user fallback and request-input tests, which guard existing behavior.uv run pytest tests/unit/test_response_validation.py tests/unit/test_client_errors.py: 126 passed.uv run pytest --numprocesses=4 tests/unit: 2965 passed, 7 skipped (zstd needs Python 3.14,time.tzsetis Unix-only).uv run ruff format --checkanduv run ruff check: clean.uv run python -m scripts.check_docstrings: passed.uv run ty check: clean withpython-platformset tolinuxfor the run. On Windows it reports twotime.tzseterrors intests/unit/test_http_clients.py, which this change does not touch.typlatform set as above.Not run:
markdownlintfor the new docs section (they need Node.js and pnpm).Notes
_models.py,_typeddicts.py,_literals.py) are not touched.HttpClient.call()without settinglog_contextwould produce an error withoutmethodandurl; the error is still raised.