Skip to content

Python: 11769 - Enabling support for additional extended headers support with application/json #12555

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
@@ -1,6 +1,7 @@
# Copyright (c) Microsoft. All rights reserved.

import logging
import re
from collections import OrderedDict
from collections.abc import Generator
from typing import TYPE_CHECKING, Any, Final
Expand Down Expand Up @@ -48,7 +49,23 @@ class OpenApiParser:
"""

PAYLOAD_PROPERTIES_HIERARCHY_MAX_DEPTH: int = 10
SUPPORTED_MEDIA_TYPES: Final[list[str]] = ["application/json", "text/plain"]

# Regex patterns for supported media types
SUPPORTED_MEDIA_TYPE_PATTERNS: Final[list[re.Pattern]] = [
re.compile(r"^application/json$"),
re.compile(r"^text/plain$"),
re.compile(r"^application/[\w\.\-]+?\+json$"),
]

@classmethod
def is_supported_media_type(cls, media_type: str) -> bool:
"""Check if the media type is supported by matching against known patterns and log the matching pattern."""
for pattern in cls.SUPPORTED_MEDIA_TYPE_PATTERNS:
if pattern.match(media_type):
logger.debug(f"Media type '{media_type}' matched pattern '{pattern.pattern}'")
return True
logger.debug(f"Media type '{media_type}' did not match any supported pattern.")
return False

def parse(self, openapi_document: str) -> Any | dict[str, Any] | None:
"""Parse the OpenAPI document."""
Expand Down Expand Up @@ -123,9 +140,10 @@ def _create_rest_api_operation_payload(
if content is None:
return None

media_type = next((mt for mt in OpenApiParser.SUPPORTED_MEDIA_TYPES if mt in content), None)
# Find the first supported media type using the new matcher
media_type = next((mt for mt in content if self.is_supported_media_type(mt)), None)
if media_type is None:
raise Exception(f"Neither of the media types of {operation_id} is supported.")
raise Exception(f"None of the media types of {operation_id} is supported.")

media_type_metadata = content[media_type]
payload_properties = self._get_payload_properties(
Expand All @@ -141,7 +159,7 @@ def _create_rest_api_operation_payload(
def _create_response(self, responses: dict[str, Any]) -> Generator[tuple[str, RestApiExpectedResponse], None, None]:
for response_key, response_value in responses.items():
media_type = next(
(mt for mt in OpenApiParser.SUPPORTED_MEDIA_TYPES if mt in response_value.get("content", {})), None
(mt for mt in response_value.get("content", {}) if self.is_supported_media_type(mt)), None
)
if media_type is not None:
matching_schema = response_value["content"][media_type].get("schema", {})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,13 +151,27 @@ async def run_operation(
headers.update(APP_INFO)
headers = prepend_semantic_kernel_to_user_agent(headers)

if "Content-Type" not in headers:
# giving precedence to what request body defines & if it's not present, using the first response media type
# as a fallback
if operation.request_body is not None:
logger.debug(
"Using request body media type '%s' for operation '%s'.",
operation.request_body.media_type,
operation.id,
)
headers["Content-Type"] = operation.request_body.media_type
elif "Content-Type" not in headers:
responses = (
operation.responses
if isinstance(operation.responses, OrderedDict)
else OrderedDict(operation.responses or {})
)
headers["Content-Type"] = self._get_first_response_media_type(responses)
logger.debug(
"Using default response media type '%s' for operation '%s'.",
headers["Content-Type"],
operation.id,
)

timeout = options.timeout if options and hasattr(options, "timeout") and options.timeout is not None else None

Expand Down
Loading