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
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import asyncio
from dataclasses import dataclass
import logging
import re
import ssl
from typing import Any
from typing import Callable
Expand Down Expand Up @@ -174,6 +175,31 @@ def _encode_path_param(*, name: str, value: str) -> str:
return quote(value, safe="")


_PATH_TEMPLATE_FIELD_RE = re.compile(r"\{([^{}]+)\}")


def _fill_path_template(path: str, path_params: dict[str, str]) -> str:
"""Substitutes each ``{name}`` in an OpenAPI path template.

``str.format`` reads ``.`` and ``[`` in a field name as attribute and index
access, so a template such as ``/files/{file.name}`` would look up
``file`` instead of ``file.name``. Each name is looked up whole here.

Args:
path: The OpenAPI path template.
path_params: Encoded parameter values keyed by their original names.

Returns:
The path with every placeholder replaced.

Raises:
KeyError: If a placeholder has no value in ``path_params``.
"""
return _PATH_TEMPLATE_FIELD_RE.sub(
lambda match: path_params[match.group(1)], path
)


class RestApiTool(BaseTool):
"""A generic tool that interacts with a REST API.

Expand Down Expand Up @@ -535,7 +561,7 @@ def _prepare_request_params(
base_url = self.endpoint.base_url or ""
base_url = base_url[:-1] if base_url.endswith("/") else base_url
try:
formatted_path = self.endpoint.path.format(**path_params)
formatted_path = _fill_path_template(self.endpoint.path, path_params)
except KeyError as e:
missing_param = e.args[0] if e.args else str(e)
for param in parameters:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2285,6 +2285,41 @@ def test_prepare_request_params_path_param(
request_params["url"] == "https://example.com/test/123"
) # Path param replaced

@pytest.mark.parametrize("name", ["file.name", "items[0]"])
def test_prepare_request_params_path_param_name_with_dot_or_bracket(
self, sample_endpoint, sample_auth_credential, sample_auth_scheme, name
):
"""A path parameter name is substituted whole, not as attribute access."""
tool = RestApiTool(
name="test_tool",
description="Test Tool",
endpoint=sample_endpoint,
operation=Operation(operationId="test_op"),
auth_credential=sample_auth_credential,
auth_scheme=sample_auth_scheme,
)
params = [
ApiParameter(
original_name=name,
py_name="file_name",
param_location="path",
param_schema=OpenAPISchema(type="string"),
)
]
tool.endpoint = OperationEndpoint(
base_url="https://example.com",
path=f"/files/{{{name}}}/content",
method="get",
)

request_params = tool._prepare_request_params(
params, {"file_name": "report.txt"}
)

assert request_params["url"] == (
"https://example.com/files/report.txt/content"
)

def test_prepare_request_params_path_param_is_percent_encoded(
self, sample_endpoint, sample_auth_credential, sample_auth_scheme
):
Expand Down
Loading