Skip to content

fix: Raise ResponseValidationError when an API response does not match its model - #1243

Open
emreocell wants to merge 2 commits into
apify:masterfrom
emreocell:fix/response-validation-error
Open

emreocell wants to merge 2 commits into
apify:masterfrom
emreocell:fix/response-validation-error

Conversation

@emreocell

Copy link
Copy Markdown

Fixes #1170

Problem

Resource methods turn API responses into models with <Model>.model_validate(...). A response that does not match the model raises a bare pydantic.ValidationError. It does not inherit from ApifyClientError, so except ApifyClientError handlers 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:

client = ApifyClient(token='t', api_url=server_url)  # GET /v2/datasets/ds-1 -> {"data": {"unexpected": "shape"}}

try:
    client.dataset('ds-1').get()
except ApifyClientError:
    ...  # not reached

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 to apify_client.errors. It exposes method and url and keeps the original error as __cause__. url has no query string, in line with how ApifyApiError reports path. Because it subclasses pydantic.ValidationError, existing except pydantic.ValidationError and except ValueError handlers keep working, so this is not a breaking change. errors() returns the same entries as before.
  • validate_response(model, data) in _utils/http.py replaces the direct model_validate() call on response data at every resource client call site (sync and async). It rebuilds the error with from_exception_data(). The method and URL come from the existing log_context variables that HttpClient.call() already sets for every request, so no call site needed new arguments.
  • UserClient.get() still validates the private model directly and catches the raw ValidationError to fall back to the public model. The public-model validation goes through the helper, so a body that fits neither model raises ResponseValidationError.
  • Validation of request input (TaskInput, CreateVersionRequest, RequestWithoutId, and similar) is left as it was, since no response is involved.
  • A short section on the new error is added to docs/02_concepts/04_error_handling.mdx.

Tests

tests/unit/test_response_validation.py (28 test cases across the impit and httpx2 transports, sync and async):

  • a mismatched response raises ResponseValidationError for a single GET, a collection list, a POST (get_or_create), a PUT (update) and wait_for_finish, and the error is an ApifyClientError, a pydantic.ValidationError and a ValueError, with the right method, a url ending in the request path, non-empty errors(), the pydantic error as __cause__, and the request in str(error)
  • the url carries no query string
  • UserClient.get() still falls back to the public model, and raises ResponseValidationError when neither model fits
  • invalid request input still raises a plain pydantic.ValidationError

Verification

Run on Windows with Python 3.12.10:

  • Before the change, a copy of the new tests with ResponseValidationError aliased to ApifyClientError reported 24 failed and 4 passed on a clean checkout of master. 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.tzset is Unix-only).
  • uv run ruff format --check and uv run ruff check: clean.
  • uv run python -m scripts.check_docstrings: passed.
  • uv run ty check: clean with python-platform set to linux for the run. On Windows it reports two time.tzset errors in tests/unit/test_http_clients.py, which this change does not touch.
  • The pre-commit hooks (lint, type check, docstring check) ran on the commit and passed, with the ty platform set as above.

Not run:

  • Integration tests (they need Apify API tokens).
  • The docs build and markdownlint for the new docs section (they need Node.js and pnpm).
  • Python 3.11, 3.13 and Linux.

Notes

  • The generated models (_models.py, _typeddicts.py, _literals.py) are not touched.
  • The method and URL are read from request-scoped context variables, which are per thread and per asyncio task, and the validation always follows the request it belongs to. A custom HTTP client that replaces HttpClient.call() without setting log_context would produce an error without method and url; the error is still raised.

…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
@emreocell
emreocell requested a review from szaganek as a code owner November 18, 2026 17:03
Copilot AI balanced review requested due to automatic review settings November 18, 2026 17:03

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@github-actions github-actions Bot added the t-tooling Issues with this label are in the ownership of the tooling team. label Nov 18, 2026
@vdusek vdusek changed the title fix: raise ResponseValidationError when an API response does not match its model fix: Raise ResponseValidationError when an API response does not match its model Nov 20, 2026
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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/apify_client/_utils/http.py Outdated
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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread docs/02_concepts/04_error_handling.mdx Outdated

## 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 = [

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@vdusek
vdusek requested a review from apify-factory November 20, 2026 08:56

@apify-factory apify-factory left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-engineering
  • same-repo: head repo is emreocell/apify-client-python
  • max-files: 31 changed files: over the limit 10
  • max-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

Comment thread src/apify_client/errors.py Outdated
url: The URL of that request, without query parameters (if available).
"""

method: str | None = None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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).
@emreocell
emreocell requested a review from vdusek November 20, 2026 11:16

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

t-tooling Issues with this label are in the ownership of the tooling team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Response validation raises a raw pydantic ValidationError that is not an ApifyClientError

4 participants