Skip to content

perf(dispatch): call model_validate_json directly and stream JSON into Python objects (#255) - #262

Merged
ZhuchkaTriplesix merged 1 commit into
devfrom
issue-255-pydantic-model-validate-json
Oct 18, 2026
Merged

ZhuchkaTriplesix merged 1 commit into
devfrom
issue-255-pydantic-model-validate-json

Conversation

@ZhuchkaTriplesix

Copy link
Copy Markdown
Member

Closes #255

Summary of Changes

  • Pydantic Model Direct Validation (src/dispatch.rs):

    • Eliminated intermediate serde_json::from_slice::<JsonValue> AST parsing and intermediate Python dictionary allocation when body_model is configured.
    • Passes raw request body_bytes (reusing the borrowed PyBytes buffer zero-copy when available) directly to Pydantic's model_validate_json. This delegates JSON parsing to Pydantic v2's native Rust/C core (pydantic-core), avoiding double allocation and multiple AST traversals.
    • Retained graceful fallback to model_validate(pyv) for models or validators that do not implement model_validate_json.
  • Direct Streaming JSON Deserializer (src/schema.rs):

    • Implemented json_bytes_to_py(py, bytes) using serde::de::Visitor and serde::de::DeserializeSeed.
    • Deserializes raw JSON bytes directly into native Python objects (dict, list, str, int, float, bool, None) in a single pass without ever allocating an intermediate serde_json::Value, serde_json::Map, or Rust String AST.
    • Unescaped strings in JSON are borrowed directly from the input buffer (visit_borrowed_str) into PyString.
  • Error Handling & Parity:

    • Maintained HTTP 400 with {"error": "json: ..."} when non-Pydantic JSON parsing fails.
    • Maintained HTTP 422 with {"detail": [...]} when Pydantic model validation fails.
  • Tests (tests/test_validation.py):

    • Added test_model_validate_json_called_directly to verify that model_validate_json is invoked directly with raw bytes.
    • Added test_body_model_fallback_without_model_validate_json to verify fallback for classes without model_validate_json.
    • Added test_body_model_malformed_json_returns_422 to verify 422 with json_invalid error on malformed JSON bodies.

@ZhuchkaTriplesix
ZhuchkaTriplesix merged commit 855dc58 into dev Oct 18, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant