Skip to content

Add support to use serialisation as mode for response models#41

Merged
LanderMoerkerke merged 1 commit into
masterfrom
feature/support-computed-fields
May 12, 2026
Merged

Add support to use serialisation as mode for response models#41
LanderMoerkerke merged 1 commit into
masterfrom
feature/support-computed-fields

Conversation

@LanderMoerkerke
Copy link
Copy Markdown
Member

@LanderMoerkerke LanderMoerkerke commented May 11, 2026

Specify mode when generating ModelField. This adds support for calculated / read-only properties defined in Pydantic (see: Fields | Pydantic Docs).

Summary by Sourcery

Support generation of response schemas using Pydantic serialization mode so computed/read-only fields are included correctly.

New Features:

  • Expose a mode parameter on create_field to select between validation and serialization schema views for Pydantic models.

Enhancements:

  • Use serialization mode when building response and publish model fields so computed fields appear with proper read-only metadata in AsyncAPI schemas.

Tests:

  • Add coverage ensuring computed fields on response models appear as read-only and required in generated AsyncAPI schemas while remaining absent from request models.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented May 11, 2026

Reviewer's Guide

Add support for generating response schemas in serialization mode so Pydantic v2 computed/read-only fields appear correctly, and ensure request/params schemas still reflect only input fields.

Flow diagram for using serialization mode in response ModelField generation

flowchart LR
    EndpointHandler --> RouterOperation
    RouterOperation -->|create_field mode=validation| RequestModelField
    RouterOperation -->|create_field mode=serialization| ReplyModelField
    RouterOperation -->|create_field mode=serialization| PublishParamsField

    subgraph Utils
        create_field
    end

    RouterOperation --> create_field
    create_field -->|PYDANTIC_V2 and mode set| ModelField
    create_field -->|Pydantic v1 no mode| ModelField

    ModelField --> AsyncapiSchemaGeneration
Loading

File-Level Changes

Change Details Files
Allow create_field to generate ModelField objects in either validation or serialization mode, and use serialization mode for response/output models so computed fields are included in AsyncAPI schemas.
  • Extended create_field signature to accept a mode parameter with Literal['validation', 'serialization'] defaulting to 'validation'.
  • When running under Pydantic v2, passed the mode keyword to ModelField creation; preserved existing behavior for Pydantic v1 by keeping the previous kwargs path.
  • Updated routing.Request and routing.Publish route initialization to create reply/params/request fields using serialization mode for result/output and publish payload models, while keeping validation mode for incoming params where appropriate.
natsapi/utils.py
natsapi/routing.py
Add regression test to verify computed fields appear in response schemas but not in request schemas when using Pydantic v2 serialization mode.
  • Defined User and CreateUserParams models with @computed_field full_name to exercise computed/read-only properties.
  • Registered request and publish handlers using these models, generated the AsyncAPI schema, and asserted that the User schema includes full_name as a readOnly and required property.
  • Asserted that the CreateUserParams request schema does not include the computed full_name property, only the actual input fields.
tests/asyncapi/test_generation.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="tests/asyncapi/test_generation.py" line_range="416" />
<code_context>
     assert schema["channels"]["natsapi.development.pub"]["publish"]["summary"] == "Pub"
+
+
+def test_computed_field_in_result_should_appear_in_response_schema():
+
+    class User(BaseModel):
</code_context>
<issue_to_address>
**issue (testing):** Guard this test so it only runs under Pydantic v2 where `@computed_field` is available and the `mode` parameter is supported.

Because this test relies on v2-only features, it will fail or be meaningless under Pydantic v1. Please either skip it when running with v1 (e.g., via a version check and `pytest.mark.skipif`) or move it into a v2-only test module so the test suite remains valid across both supported versions.
</issue_to_address>

### Comment 2
<location path="tests/asyncapi/test_generation.py" line_range="443" />
<code_context>
+    def get_user(app, params: CreateUserParams):
+        return {}
+
+    @router.publish("users.CREATED")
+    def user_created(app, user: User):
+        return {}
</code_context>
<issue_to_address>
**suggestion (testing):** Add an assertion that the `users.CREATED` publish payload schema also exposes `full_name` as readOnly.

This test only verifies the shared `User` schema and request model. It doesn’t confirm that the `users.CREATED` channel’s publish message actually uses that schema (and therefore exposes `full_name` as readOnly). Please add an assertion on `schema["channels"]["natsapi.development.v1.users.CREATED"]["publish"]["message"]["payload"]` (or the correct path) to ensure the publish payload uses the serialization view including `full_name`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread tests/asyncapi/test_generation.py
Comment thread tests/asyncapi/test_generation.py
@LanderMoerkerke LanderMoerkerke force-pushed the feature/support-computed-fields branch from b4aeff7 to a2ca3bb Compare May 11, 2026 16:05
@LanderMoerkerke LanderMoerkerke force-pushed the feature/support-computed-fields branch from a2ca3bb to da041b2 Compare May 11, 2026 16:07
@LanderMoerkerke LanderMoerkerke merged commit 4264c85 into master May 12, 2026
11 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