From 5d101c5a961f6c76f8f0ed432a3cf4c902b45b0d Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Mon, 16 Nov 2026 15:24:36 +0300 Subject: [PATCH 1/2] Use validation_alias for embedded bodies --- src/msgspec_fastapi/router.py | 7 ++++- tests/test_router.py | 57 ++++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 2 deletions(-) diff --git a/src/msgspec_fastapi/router.py b/src/msgspec_fastapi/router.py index 07312c6..255f50d 100644 --- a/src/msgspec_fastapi/router.py +++ b/src/msgspec_fastapi/router.py @@ -777,7 +777,12 @@ def add_api_route(self, path: str, endpoint: Callable[..., Any], **kwargs: Any) decode_type = body_type if embedded: assert body_meta is not None - body_alias = body_meta.alias or body.name + # As in FastAPI, the key read from the request is a string validation_alias, + # falling back to alias; AliasChoices and AliasPath do not change it. + validation_alias = body_meta.validation_alias + if not isinstance(validation_alias, str): + validation_alias = None + body_alias = validation_alias or body_meta.alias or body.name # One explicit JSON envelope, preserving a possible Body alias. field = ( ('value', body_type) diff --git a/tests/test_router.py b/tests/test_router.py index 1d745d3..7738cb8 100644 --- a/tests/test_router.py +++ b/tests/test_router.py @@ -22,7 +22,7 @@ from fastapi.exceptions import ResponseValidationError from fastapi.responses import HTMLResponse, PlainTextResponse from fastapi.testclient import TestClient -from pydantic import BaseModel, Field +from pydantic import AliasChoices, BaseModel, Field from msgspec_fastapi import MsgspecRouter, install_openapi @@ -426,6 +426,61 @@ def test_request_shapes_match_fastapi(method: str, path: str, options: dict[str, assert actual.json() == expected.json() +def embedded_alias_app( + router_class: type[APIRouter], model: Any, validation_alias: Any, optional: bool +) -> FastAPI: + router = router_class() + body = Body(embed=True, alias='other', validation_alias=validation_alias) + + async def optional_body(city: Annotated[model | None, body] = None) -> int | None: + return None if city is None else city.population + + async def required_body(city: Annotated[model, body]) -> int: + return city.population + + router.add_api_route('/value', optional_body if optional else required_body, methods=['POST']) + app = FastAPI() + app.include_router(router) + install_openapi(app) + return app + + +@pytest.mark.parametrize( + 'validation_alias,optional,payload', + [ + ('key', False, {'key': {'population': 1}}), + ('key', False, {'key': {'population': -1}}), + ('key', False, {'other': {'population': 1}}), + ('key', True, {'key': {'population': 1}}), + (AliasChoices('key', 'city'), False, {'other': {'population': 1}}), + (AliasChoices('key', 'city'), False, {'key': {'population': 1}}), + ], +) +def test_embedded_body_validation_alias_matches_fastapi( + validation_alias: Any, optional: bool, payload: dict[str, Any] +) -> None: + def post(router_class: type[APIRouter], model: Any) -> httpx.Response | httpx2.Response: + app = embedded_alias_app(router_class, model, validation_alias, optional) + return TestClient(app, raise_server_exceptions=False).post('/value', json=payload) + + expected, actual = post(APIRouter, PydCity), post(MsgspecRouter, City) + assert actual.status_code == expected.status_code + if expected.status_code == 200: + assert actual.json() == expected.json() + else: + assert [e['loc'] for e in actual.json()['detail']] == [ + e['loc'] for e in expected.json()['detail'] + ] + + +def test_embedded_body_schema_uses_validation_alias() -> None: + app = embedded_alias_app(MsgspecRouter, City, 'key', optional=False) + schema = app.openapi()['paths']['/value']['post']['requestBody']['content']['application/json'][ + 'schema' + ] + assert list(schema['properties']) == schema['required'] == ['key'] + + def test_install_openapi_accepts_no_router_arguments() -> None: app = FastAPI() install_openapi(app) From 4c9f49ef633d65bc57b2c54a937481b6124ff12b Mon Sep 17 00:00:00 2001 From: Tseluiko Aleksandr Date: Mon, 16 Nov 2026 19:32:16 +0300 Subject: [PATCH 2/2] Test the request schema of streaming routes with validation_alias --- tests/test_router.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/tests/test_router.py b/tests/test_router.py index 7738cb8..785b480 100644 --- a/tests/test_router.py +++ b/tests/test_router.py @@ -1,6 +1,7 @@ """Tests for MsgspecRouter request decoding, parameter validation and response encoding.""" import asyncio +from collections.abc import AsyncIterator from typing import Annotated, Any, Generic, TypeVar import httpx @@ -427,7 +428,11 @@ def test_request_shapes_match_fastapi(method: str, path: str, options: dict[str, def embedded_alias_app( - router_class: type[APIRouter], model: Any, validation_alias: Any, optional: bool + router_class: type[APIRouter], + model: Any, + validation_alias: Any, + optional: bool, + streaming: bool = False, ) -> FastAPI: router = router_class() body = Body(embed=True, alias='other', validation_alias=validation_alias) @@ -438,7 +443,11 @@ async def optional_body(city: Annotated[model | None, body] = None) -> int | Non async def required_body(city: Annotated[model, body]) -> int: return city.population - router.add_api_route('/value', optional_body if optional else required_body, methods=['POST']) + async def streaming_body(city: Annotated[model, body]) -> AsyncIterator[int]: + yield city.population + + endpoint = streaming_body if streaming else optional_body if optional else required_body + router.add_api_route('/value', endpoint, methods=['POST']) app = FastAPI() app.include_router(router) install_openapi(app) @@ -473,8 +482,9 @@ def post(router_class: type[APIRouter], model: Any) -> httpx.Response | httpx2.R ] -def test_embedded_body_schema_uses_validation_alias() -> None: - app = embedded_alias_app(MsgspecRouter, City, 'key', optional=False) +@pytest.mark.parametrize('streaming', [False, True]) +def test_embedded_body_schema_uses_validation_alias(streaming: bool) -> None: + app = embedded_alias_app(MsgspecRouter, City, 'key', optional=False, streaming=streaming) schema = app.openapi()['paths']['/value']['post']['requestBody']['content']['application/json'][ 'schema' ]