Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .chronus/changes/http-client-python-model-query-expansion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http-client-python"
---

Serialize named model query parameters using form-style expansion, including exploded properties and query continuation routes.
3 changes: 3 additions & 0 deletions packages/http-client-python/emitter/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ export function isAbstract<TServiceOperation extends SdkServiceOperation>(
export function getDelimiterAndExplode(
parameter: SdkQueryParameter | SdkHeaderParameter,
): [string | undefined, boolean] {
if (parameter.kind === "query" && parameter.type.kind === "model") {
return [undefined, parameter.explode];
}
if (parameter.type.kind !== "array") return [undefined, false];
let delimiter: string | undefined = undefined;
let explode = parameter.kind === "query" && parameter.explode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
ClientParameter,
ConfigParameter,
ParameterType,
ModelType,
)
from ..models.parameter import _ParameterBase
from ..models.parameter_list import BodyParameterType
Expand Down Expand Up @@ -164,11 +165,24 @@ def serialize_query_header(
f""" _headers[{python_string_literal(header_name)}] = _SERIALIZER.header("if_none_match", if_none_match, "str")""",
]

set_parameter = "_{}[{}] = {}".format(
kwarg_name,
python_string_literal(param.wire_name, quote="'"),
self.serialize_parameter(param, serializer_name),
)
if not is_legacy and param.location == ParameterLocation.QUERY and isinstance(param.type, ModelType):
serialized_model = (
f"{serializer_name}.query_model({python_string_literal(param.full_client_name)}, "
f"{param.full_client_name}, skip_quote={param.skip_url_encoding})"
)
if param.explode:
set_parameter = f"_{kwarg_name}.update({serialized_model})"
else:
set_parameter = (
f"_{kwarg_name}[{python_string_literal(param.wire_name)}] = "
f"','.join(component for pair in {serialized_model}.items() for component in pair)"

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.

[P2] Omit standard expansion when the model has no defined properties

This branch assigns _params["param"] = "" when query_model() returns {}, producing ?param= (or &param= for continuation) instead of omitting the parameter. This is reachable with a named model containing only optional properties, e.g. model Filters { field?: string; }, when the caller passes Filters(); an all-None mapping has the same result. I reproduced both cases using the serializer methods from this revision.

RFC 6570 section 2.3 treats an associative value with zero members, or only undefined members, as undefined: https://www.rfc-editor.org/rfc/rfc6570.html#section-2.3. Servers can distinguish an absent parameter from an explicitly empty value. Exploded expansion already omits it correctly via .update({}).

Could we serialize the pairs once and only assign the standard query parameter when that dictionary is nonempty? Please add regressions for empty/all-None properties in standard expansion and continuation, while preserving a defined empty-string property such as {"field": ""}.

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.

I think up comment belongs to corner case to feel free to accept or not.

)
else:
set_parameter = "_{}[{}] = {}".format(
kwarg_name,
python_string_literal(param.wire_name, quote="'"),
self.serialize_parameter(param, serializer_name),
)
# When the body is optional, the content-type may legitimately be ``None`` (no body
# was sent). In that case the header must be omitted instead of serialized, otherwise
# ``_SERIALIZER.header`` raises ``ValueError: No value for given attribute``.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,28 @@ class Serializer: # pylint: disable=too-many-public-methods
raise TypeError("{} must be type {}.".format(name, data_type)) from exc
return str(output)

def query_model(
self, name: str, data: Optional[Mapping[str, Any]], *, skip_quote: bool = False
) -> dict[str, str]:
"""Serialize a model's wire-name/value pairs for form-style query expansion.

:param str name: The name of the query parameter.
:param Mapping data: The model or mapping to serialize.
:keyword bool skip_quote: Whether to skip URL encoding.
:return: Individually encoded property names and values.
:rtype: dict[str, str]
:raises ValueError: if data is None.
"""
if data is None:
raise ValueError("No value for given attribute: {}".format(name))
Comment on lines +752 to +764
return {
cast(str, self.query(name, key, "str", skip_quote=skip_quote)): cast(
str, self.query(name, value, "bool" if isinstance(value, bool) else "str", skip_quote=skip_quote)
)
for key, value in data.items()
if value is not None
}

def header(self, name, data, data_type, **kwargs):
"""Serialize data intended for a request header.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest
import pytest_asyncio
from routes.aio import RoutesClient
from routes.models import ExpandParameters


@pytest_asyncio.fixture
Expand All @@ -19,6 +20,14 @@ async def test_fixed(client: RoutesClient):
await client.fixed()


@pytest.mark.asyncio
@pytest.mark.parametrize("expansion", ["query_expansion", "query_continuation"])
@pytest.mark.parametrize("style", ["standard", "explode"])
async def test_query_parameters_model(client: RoutesClient, expansion: str, style: str):
operation = getattr(getattr(client.query_parameters, expansion), style)
await operation.model(param=ExpandParameters(field="status", value="active"))


@pytest.mark.asyncio
async def test_in_interface_fixed(client: RoutesClient):
await client.in_interface.fixed()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# --------------------------------------------------------------------------
import pytest
from routes import RoutesClient
from routes.models import ExpandParameters


@pytest.fixture
Expand Down Expand Up @@ -213,6 +214,13 @@ def test_query_parameters_annotation_only(client: RoutesClient):
)


@pytest.mark.parametrize("expansion", ["query_expansion", "query_continuation"])
@pytest.mark.parametrize("style", ["standard", "explode"])
def test_query_parameters_model(client: RoutesClient, expansion: str, style: str):
operation = getattr(getattr(client.query_parameters, expansion), style)
operation.model(param=ExpandParameters(field="status", value="active"))


def test_query_parameters_query_expansion_standard_primitive(client: RoutesClient):
client.query_parameters.query_expansion.standard.primitive(
param="a",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from types import SimpleNamespace

import pytest
from jinja2 import Environment, PackageLoader


@pytest.fixture(scope="session", autouse=True)
def testserver():
yield


@pytest.fixture
def serializer():
env = Environment(loader=PackageLoader("pygen.codegen", "templates"))
source = env.get_template("serialization.py.jinja2").render(
code_model=SimpleNamespace(license_header="", core_library="corehttp")
)
namespace = {}
exec(compile(source, "<serialization>", "exec"), namespace)
return namespace["Serializer"]()


def test_query_model_quotes_components_and_preserves_falsy_values(serializer):
result = serializer.query_model(
"filter",
{"wire,name": "a,b & c", "enabled": False, "count": 0, "empty": "", "omitted": None},
)
assert result == {"wire%2Cname": "a%2Cb%20%26%20c", "enabled": "false", "count": "0", "empty": ""}


def test_query_model_skip_url_encoding(serializer):
assert serializer.query_model("filter", {"wire,name": "a,b"}, skip_quote=True) == {"wire,name": "a,b"}


def test_query_model_rejects_missing_required_model(serializer):
with pytest.raises(ValueError, match="filter"):
serializer.query_model("filter", None)
Loading