Skip to content

openapi

Class info

Re-exported classes

Class Module Description
OpenAPICallableFactory schemez.openapi.callable_factory Generates typed callables from OpenAPI operations.
OpenAPIResolver schemez.openapi.resolver Resolves $ref references in OpenAPI specs, including external HTTP refs.

🛈 DocStrings

OpenAPI toolset implementation with HTTP-aware reference resolution.

This package provides tools for loading OpenAPI specs and creating callable tools from their operations. It includes a custom resolver that handles external HTTP references in multi-file OpenAPI specifications.

OpenAPICallableFactory

Generates typed callables from OpenAPI operations.

Source code in src/schemez/openapi/callable_factory.py
class OpenAPICallableFactory:
    """Generates typed callables from OpenAPI operations."""

    def __init__(
        self,
        schemas: dict[str, dict[str, Any]],
        request_handler: Callable[..., Awaitable[dict[str, Any]]],
    ) -> None:
        """Initialize the factory.

        Args:
            schemas: Resolved component schemas from spec
            request_handler: Async callable performing HTTP requests.
                             Signature: (method, path, params, body) -> response_json
        """
        self._schemas = schemas
        self._request_handler = request_handler

    def resolve_schema_ref(self, schema: dict[str, Any]) -> dict[str, Any]:
        """Resolve $ref to actual schema."""
        if (
            (ref := schema.get("$ref"))
            and isinstance(ref, str)
            and ref.startswith("#/components/schemas/")
        ):
            name = ref.split("/")[-1]
            return self._schemas.get(name, schema)
        return schema

    def get_type_for_schema(self, schema: dict[str, Any]) -> type | Any:  # noqa: PLR0911
        """Convert OpenAPI schema to Python type."""
        schema = self.resolve_schema_ref(schema)

        if "$ref" in schema:
            logger.debug("Unresolved $ref in schema, using Any: %s", schema.get("$ref"))
            return Any

        match schema.get("type"):
            case "string":
                if enum := schema.get("enum"):
                    return Literal[tuple(enum)]
                if fmt := schema.get("format"):
                    return FORMAT_MAP.get(fmt, str)
                return str

            case "integer":
                return int

            case "number":
                return float

            case "boolean":
                return bool

            case "array":
                if items := schema.get("items"):
                    item_type = self.get_type_for_schema(items)
                    return list[item_type]
                return list[Any]

            case "object":
                # `additionalProperties: true` is a bool, not a schema
                if isinstance(additional_props := schema.get("additionalProperties"), dict):
                    value_type = self.get_type_for_schema(additional_props)
                    type DictType = dict[str, value_type]
                    return DictType
                return dict[str, Any]

            case "null":
                return type(None)

            case None if "oneOf" in schema:
                types = [self.get_type_for_schema(s) for s in schema["oneOf"]]
                return Union[tuple(types)]  # noqa: UP007

            case None if "anyOf" in schema:
                types = [self.get_type_for_schema(s) for s in schema["anyOf"]]
                return Union[tuple(types)]  # noqa: UP007

            case None if "allOf" in schema:
                return dict[str, Any]

            case _:
                return Any

    def get_type_description(self, schema: dict[str, Any]) -> str:  # noqa: PLR0911
        """Get human-readable type description for docstrings."""
        schema = self.resolve_schema_ref(schema)

        if "$ref" in schema:
            return "any"

        match schema.get("type"):
            case "string":
                if enum := schema.get("enum"):
                    return f"one of: {', '.join(repr(e) for e in enum)}"
                if fmt := schema.get("format"):
                    return f"string ({fmt})"
                return "string"

            case "array":
                if items := schema.get("items"):
                    item_type = self.get_type_description(items)
                    return f"array of {item_type}"
                return "array"

            case "object":
                if properties := schema.get("properties"):
                    prop_types = [
                        f"{k}: {self.get_type_description(v)}" for k, v in properties.items()
                    ]
                    return f"object with {', '.join(prop_types)}"
                return "object"

            case t:
                return str(t) if t else "any"

    def create_docstring(self, config: dict[str, Any]) -> str:
        """Generate docstring from operation config."""
        lines: list[str] = []
        if description := config.get("description"):
            lines.append(description)
            lines.append("")

        if parameters := config.get("parameters"):
            lines.append("Args:")
            for param in parameters:
                schema = param.get("schema", {})
                description = schema.get("description", "No description")
                desc = param.get("description", description)
                required = " (required)" if param.get("required") else ""
                type_str = self.get_type_description(schema)
                lines.append(f"    {param['name']}: {desc}{required} ({type_str})")

        if responses := config.get("responses"):
            lines.append("")
            lines.append("Returns:")
            resps = [r for code, r in responses.items() if code.startswith("2")]
            lines.extend(f"    {r.get('description', '')}" for r in resps)

        return "\n".join(lines)

    def create_callable(
        self,
        operation_id: str,
        config: dict[str, Any],
    ) -> Callable[..., Awaitable[dict[str, Any]]]:
        """Create a typed async callable for an operation."""
        annotations: dict[str, Any] = {}
        required_params: set[str] = set()
        param_defaults: dict[str, Any] = {}

        for param in config.get("parameters", []):
            name = param["name"]
            schema = param.get("schema", {})

            param_type = self.get_type_for_schema(schema)
            is_required = param.get("required", False)
            annotations[name] = param_type if is_required else param_type | None

            if is_required:
                required_params.add(name)

            if "default" in schema:
                param_defaults[name] = schema["default"]

        parameters = config.get("parameters", [])
        path_template = config["path"]
        method = config["method"]
        request_handler = self._request_handler

        async def operation_method(**kwargs: Any) -> dict[str, Any]:
            """Dynamic method for API operation."""
            missing = required_params - set(kwargs)
            if missing:
                msg = f"Missing required parameters: {', '.join(sorted(missing))}"
                raise ValueError(msg)

            path = path_template
            request_params: dict[str, Any] = {}
            request_body: dict[str, Any] = {}

            for param in parameters:
                name = param["name"]
                if name not in kwargs and name in param_defaults:
                    kwargs[name] = param_defaults[name]

                if name in kwargs:
                    match param["in"]:
                        case "path":
                            path = path.replace(f"{{{name}}}", str(kwargs[name]))
                        case "query":
                            request_params[name] = kwargs[name]
                        case "body":
                            request_body[name] = kwargs[name]

            return await request_handler(
                method=method,
                path=path,
                params=request_params,
                body=request_body if request_body else None,
            )

        operation_method.__name__ = operation_id
        operation_method.__doc__ = self.create_docstring(config)
        operation_method.__annotations__ = {**annotations, "return": dict[str, Any]}

        return operation_method

__init__

__init__(
    schemas: dict[str, dict[str, Any]], request_handler: Callable[..., Awaitable[dict[str, Any]]]
) -> None

Initialize the factory.

Parameters:

Name Type Description Default
schemas dict[str, dict[str, Any]]

Resolved component schemas from spec

required
request_handler Callable[..., Awaitable[dict[str, Any]]]

Async callable performing HTTP requests. Signature: (method, path, params, body) -> response_json

required
Source code in src/schemez/openapi/callable_factory.py
def __init__(
    self,
    schemas: dict[str, dict[str, Any]],
    request_handler: Callable[..., Awaitable[dict[str, Any]]],
) -> None:
    """Initialize the factory.

    Args:
        schemas: Resolved component schemas from spec
        request_handler: Async callable performing HTTP requests.
                         Signature: (method, path, params, body) -> response_json
    """
    self._schemas = schemas
    self._request_handler = request_handler

create_callable

create_callable(
    operation_id: str, config: dict[str, Any]
) -> Callable[..., Awaitable[dict[str, Any]]]

Create a typed async callable for an operation.

Source code in src/schemez/openapi/callable_factory.py
def create_callable(
    self,
    operation_id: str,
    config: dict[str, Any],
) -> Callable[..., Awaitable[dict[str, Any]]]:
    """Create a typed async callable for an operation."""
    annotations: dict[str, Any] = {}
    required_params: set[str] = set()
    param_defaults: dict[str, Any] = {}

    for param in config.get("parameters", []):
        name = param["name"]
        schema = param.get("schema", {})

        param_type = self.get_type_for_schema(schema)
        is_required = param.get("required", False)
        annotations[name] = param_type if is_required else param_type | None

        if is_required:
            required_params.add(name)

        if "default" in schema:
            param_defaults[name] = schema["default"]

    parameters = config.get("parameters", [])
    path_template = config["path"]
    method = config["method"]
    request_handler = self._request_handler

    async def operation_method(**kwargs: Any) -> dict[str, Any]:
        """Dynamic method for API operation."""
        missing = required_params - set(kwargs)
        if missing:
            msg = f"Missing required parameters: {', '.join(sorted(missing))}"
            raise ValueError(msg)

        path = path_template
        request_params: dict[str, Any] = {}
        request_body: dict[str, Any] = {}

        for param in parameters:
            name = param["name"]
            if name not in kwargs and name in param_defaults:
                kwargs[name] = param_defaults[name]

            if name in kwargs:
                match param["in"]:
                    case "path":
                        path = path.replace(f"{{{name}}}", str(kwargs[name]))
                    case "query":
                        request_params[name] = kwargs[name]
                    case "body":
                        request_body[name] = kwargs[name]

        return await request_handler(
            method=method,
            path=path,
            params=request_params,
            body=request_body if request_body else None,
        )

    operation_method.__name__ = operation_id
    operation_method.__doc__ = self.create_docstring(config)
    operation_method.__annotations__ = {**annotations, "return": dict[str, Any]}

    return operation_method

create_docstring

create_docstring(config: dict[str, Any]) -> str

Generate docstring from operation config.

Source code in src/schemez/openapi/callable_factory.py
def create_docstring(self, config: dict[str, Any]) -> str:
    """Generate docstring from operation config."""
    lines: list[str] = []
    if description := config.get("description"):
        lines.append(description)
        lines.append("")

    if parameters := config.get("parameters"):
        lines.append("Args:")
        for param in parameters:
            schema = param.get("schema", {})
            description = schema.get("description", "No description")
            desc = param.get("description", description)
            required = " (required)" if param.get("required") else ""
            type_str = self.get_type_description(schema)
            lines.append(f"    {param['name']}: {desc}{required} ({type_str})")

    if responses := config.get("responses"):
        lines.append("")
        lines.append("Returns:")
        resps = [r for code, r in responses.items() if code.startswith("2")]
        lines.extend(f"    {r.get('description', '')}" for r in resps)

    return "\n".join(lines)

get_type_description

get_type_description(schema: dict[str, Any]) -> str

Get human-readable type description for docstrings.

Source code in src/schemez/openapi/callable_factory.py
def get_type_description(self, schema: dict[str, Any]) -> str:  # noqa: PLR0911
    """Get human-readable type description for docstrings."""
    schema = self.resolve_schema_ref(schema)

    if "$ref" in schema:
        return "any"

    match schema.get("type"):
        case "string":
            if enum := schema.get("enum"):
                return f"one of: {', '.join(repr(e) for e in enum)}"
            if fmt := schema.get("format"):
                return f"string ({fmt})"
            return "string"

        case "array":
            if items := schema.get("items"):
                item_type = self.get_type_description(items)
                return f"array of {item_type}"
            return "array"

        case "object":
            if properties := schema.get("properties"):
                prop_types = [
                    f"{k}: {self.get_type_description(v)}" for k, v in properties.items()
                ]
                return f"object with {', '.join(prop_types)}"
            return "object"

        case t:
            return str(t) if t else "any"

get_type_for_schema

get_type_for_schema(schema: dict[str, Any]) -> type | Any

Convert OpenAPI schema to Python type.

Source code in src/schemez/openapi/callable_factory.py
def get_type_for_schema(self, schema: dict[str, Any]) -> type | Any:  # noqa: PLR0911
    """Convert OpenAPI schema to Python type."""
    schema = self.resolve_schema_ref(schema)

    if "$ref" in schema:
        logger.debug("Unresolved $ref in schema, using Any: %s", schema.get("$ref"))
        return Any

    match schema.get("type"):
        case "string":
            if enum := schema.get("enum"):
                return Literal[tuple(enum)]
            if fmt := schema.get("format"):
                return FORMAT_MAP.get(fmt, str)
            return str

        case "integer":
            return int

        case "number":
            return float

        case "boolean":
            return bool

        case "array":
            if items := schema.get("items"):
                item_type = self.get_type_for_schema(items)
                return list[item_type]
            return list[Any]

        case "object":
            # `additionalProperties: true` is a bool, not a schema
            if isinstance(additional_props := schema.get("additionalProperties"), dict):
                value_type = self.get_type_for_schema(additional_props)
                type DictType = dict[str, value_type]
                return DictType
            return dict[str, Any]

        case "null":
            return type(None)

        case None if "oneOf" in schema:
            types = [self.get_type_for_schema(s) for s in schema["oneOf"]]
            return Union[tuple(types)]  # noqa: UP007

        case None if "anyOf" in schema:
            types = [self.get_type_for_schema(s) for s in schema["anyOf"]]
            return Union[tuple(types)]  # noqa: UP007

        case None if "allOf" in schema:
            return dict[str, Any]

        case _:
            return Any

resolve_schema_ref

resolve_schema_ref(schema: dict[str, Any]) -> dict[str, Any]

Resolve $ref to actual schema.

Source code in src/schemez/openapi/callable_factory.py
def resolve_schema_ref(self, schema: dict[str, Any]) -> dict[str, Any]:
    """Resolve $ref to actual schema."""
    if (
        (ref := schema.get("$ref"))
        and isinstance(ref, str)
        and ref.startswith("#/components/schemas/")
    ):
        name = ref.split("/")[-1]
        return self._schemas.get(name, schema)
    return schema

OpenAPIResolver

Resolves $ref references in OpenAPI specs, including external HTTP refs.

Source code in src/schemez/openapi/resolver.py
class OpenAPIResolver:
    """Resolves $ref references in OpenAPI specs, including external HTTP refs."""

    def __init__(self, base_url: str, timeout: float = 30.0):
        """Initialize resolver.

        Args:
            base_url: Base URL of the OpenAPI spec (used for relative refs).
            timeout: HTTP request timeout in seconds.
        """
        self.base_url = base_url
        self.timeout = timeout
        self._cache: dict[str, dict[str, Any]] = {}
        self._client: httpx2.Client | None = None
        self._resolving: set[str] = set()  # Track refs being resolved to detect cycles
        # Resolved targets that didn't run into a cycle (shared, not copied)
        self._resolved: dict[str, Any] = {}
        self._cycles = 0

    @property
    def client(self) -> httpx2.Client:
        if self._client is None:
            self._client = httpx2.Client(timeout=self.timeout, follow_redirects=True)
        return self._client

    def close(self) -> None:
        if self._client is not None:
            self._client.close()
            self._client = None

    def __enter__(self) -> Self:
        return self

    def __exit__(self, *args: object) -> None:
        self.close()

    def resolve(self, spec: dict[str, Any]) -> dict[str, Any]:
        """Fully resolve all $ref in the spec.

        Internal refs (`#/...`) resolve against the document they appear in (the spec,
        or an external document), recursively; a cyclic ref, or one whose target can't
        be found or fetched, stays a `$ref`.

        Args:
            spec: The OpenAPI spec dictionary.

        Returns:
            A new dictionary with all refs resolved.
        """
        self._resolving.clear()
        self._resolved.clear()
        self._cache[self.base_url] = spec
        return self._resolve_value(spec, self.base_url)

    def _resolve_value(self, value: Any, current_url: str) -> Any:
        """Recursively resolve refs in a value."""
        match value:
            case dict() if isinstance(value.get("$ref"), str):
                resolved = self._resolve_ref(value["$ref"], current_url)
                siblings = {k: v for k, v in value.items() if k != "$ref"}
                if siblings and isinstance(resolved, dict) and "$ref" not in resolved:
                    resolved = {**resolved, **self._resolve_value(siblings, current_url)}
                return resolved
            case dict():
                return {k: self._resolve_value(v, current_url) for k, v in value.items()}
            case list():
                return [self._resolve_value(item, current_url) for item in value]
            case _:
                return value

    def _resolve_ref(self, ref: str, current_url: str) -> Any:
        """Resolve a single $ref.

        Args:
            ref: The reference string (e.g., '../parameters/foo.yml#/codes').
            current_url: URL of the document containing this ref.

        Returns:
            The resolved schema/object.
        """
        # Split ref into URL part and JSON pointer
        url_part, pointer = ref.split("#", 1) if "#" in ref else (ref, "")
        # Same document for internal refs like #/components/schemas/Foo
        abs_url = urljoin(current_url, url_part) if url_part else current_url
        full_ref = f"{abs_url}#{pointer}"
        if full_ref in self._resolved:
            return self._resolved[full_ref]
        if full_ref in self._resolving:  # Detect circular references
            logger.debug("Circular reference detected: %s", full_ref)
            self._cycles += 1
            return {"$ref": ref}  # Keep original ref to break cycle

        doc = self._fetch_document(abs_url)
        if doc is None:
            return {"$ref": ref}
        result = _navigate_pointer(doc, pointer) if pointer else doc
        if result is _MISSING:
            logger.warning("Unresolvable reference %r in %s", ref, current_url)
            return {"$ref": ref}
        self._resolving.add(full_ref)
        cycles = self._cycles
        try:
            # Recursively resolve any refs in the target, relative to its document
            resolved = self._resolve_value(result, abs_url)
        finally:
            self._resolving.discard(full_ref)
        if self._cycles == cycles:
            self._resolved[full_ref] = resolved
        return resolved

    def _fetch_document(self, url: str) -> dict[str, Any] | None:
        """Fetch and cache an external document (HTTP or any UPath); None on failure."""
        if url in self._cache:
            return self._cache[url]

        logger.debug("Fetching external ref: %s", url)
        try:
            if url.startswith(("http://", "https://")):
                response = self.client.get(url)
                response.raise_for_status()
                content = response.text
            else:
                from upath import UPath

                content = UPath(url).read_text(encoding="utf-8")
            doc = yamling.load_yaml(content, verify_type=dict)
        except Exception as e:  # noqa: BLE001
            logger.warning("Failed to fetch %s: %s", url, e)
            return None
        self._cache[url] = doc
        return doc

__init__

__init__(base_url: str, timeout: float = 30.0)

Initialize resolver.

Parameters:

Name Type Description Default
base_url str

Base URL of the OpenAPI spec (used for relative refs).

required
timeout float

HTTP request timeout in seconds.

30.0
Source code in src/schemez/openapi/resolver.py
def __init__(self, base_url: str, timeout: float = 30.0):
    """Initialize resolver.

    Args:
        base_url: Base URL of the OpenAPI spec (used for relative refs).
        timeout: HTTP request timeout in seconds.
    """
    self.base_url = base_url
    self.timeout = timeout
    self._cache: dict[str, dict[str, Any]] = {}
    self._client: httpx2.Client | None = None
    self._resolving: set[str] = set()  # Track refs being resolved to detect cycles
    # Resolved targets that didn't run into a cycle (shared, not copied)
    self._resolved: dict[str, Any] = {}
    self._cycles = 0

resolve

resolve(spec: dict[str, Any]) -> dict[str, Any]

Fully resolve all $ref in the spec.

Internal refs (#/...) resolve against the document they appear in (the spec, or an external document), recursively; a cyclic ref, or one whose target can't be found or fetched, stays a $ref.

Parameters:

Name Type Description Default
spec dict[str, Any]

The OpenAPI spec dictionary.

required

Returns:

Type Description
dict[str, Any]

A new dictionary with all refs resolved.

Source code in src/schemez/openapi/resolver.py
def resolve(self, spec: dict[str, Any]) -> dict[str, Any]:
    """Fully resolve all $ref in the spec.

    Internal refs (`#/...`) resolve against the document they appear in (the spec,
    or an external document), recursively; a cyclic ref, or one whose target can't
    be found or fetched, stays a `$ref`.

    Args:
        spec: The OpenAPI spec dictionary.

    Returns:
        A new dictionary with all refs resolved.
    """
    self._resolving.clear()
    self._resolved.clear()
    self._cache[self.base_url] = spec
    return self._resolve_value(spec, self.base_url)

load_openapi_spec

load_openapi_spec(url_or_path: JoinablePathLike, timeout: float = 30.0) -> dict[str, Any]

Load and fully dereference an OpenAPI spec.

Parameters:

Name Type Description Default
url_or_path JoinablePathLike

URL or path to the OpenAPI spec.

required
timeout float

HTTP timeout for fetching.

30.0

Returns:

Type Description
dict[str, Any]

Fully dereferenced OpenAPI spec.

Source code in src/schemez/openapi/loader.py
def load_openapi_spec(url_or_path: JoinablePathLike, timeout: float = 30.0) -> dict[str, Any]:
    """Load and fully dereference an OpenAPI spec.

    Args:
        url_or_path: URL or path to the OpenAPI spec.
        timeout: HTTP timeout for fetching.

    Returns:
        Fully dereferenced OpenAPI spec.
    """
    if (path_str := str(url_or_path)).startswith(("http://", "https://")):
        response = httpx2.get(path_str, follow_redirects=True, timeout=timeout)
        response.raise_for_status()
        content = response.text
        base_url = path_str
    else:
        content = UPath(url_or_path).read_text(encoding="utf-8")
        base_url = UPath(url_or_path).resolve().as_uri()

    # Try to detect format and parse accordingly
    try:
        # First try JSON (faster to fail if not JSON)
        spec = anyenv.load_json(content)
    except anyenv.JsonLoadError:
        # Fall back to YAML
        spec = yamling.load_yaml(content, verify_type=dict)

    return resolve_openapi_refs(spec, base_url, timeout)

parse_operations

parse_operations(paths: dict[str, Any]) -> dict[str, dict[str, Any]]

Parse OpenAPI paths into operation configurations.

Source code in src/schemez/openapi/loader.py
def parse_operations(paths: dict[str, Any]) -> dict[str, dict[str, Any]]:
    """Parse OpenAPI paths into operation configurations."""
    operations = {}
    for path, path_item in paths.items():
        if not isinstance(path_item, dict):
            continue

        for method, operation in path_item.items():
            if method not in {"get", "post", "put", "delete", "patch"}:
                continue
            if not isinstance(operation, dict):
                continue

            # Generate operation ID if not provided
            op_id = operation.get("operationId")
            if not op_id:
                op_id = f"{method}_{path.replace('/', '_').strip('_')}"

            # Collect all parameters
            params = operation.get("parameters", [])
            # Filter out any unresolved refs
            params = [p for p in params if isinstance(p, dict) and "$ref" not in p]

            # Handle request body
            if (
                (request_body := operation.get("requestBody"))
                and isinstance(request_body, dict)
                and (content := request_body.get("content", {}))
                and (json_schema := content.get("application/json", {}).get("schema"))
                and isinstance(json_schema, dict)
                and (properties := json_schema.get("properties", {}))
            ):
                for name, schema in properties.items():
                    if isinstance(schema, dict) and "$ref" not in schema:
                        params.append({
                            "name": name,
                            "in": "body",
                            "required": name in json_schema.get("required", []),
                            "schema": schema,
                            "description": schema.get("description", ""),
                        })

            operations[op_id] = {
                "method": method,
                "path": path,
                "description": operation.get("description", ""),
                "parameters": params,
                "responses": operation.get("responses", {}),
            }

    return operations

resolve_openapi_refs

resolve_openapi_refs(spec: dict[str, Any], base_url: str, timeout: float = 30.0) -> dict[str, Any]

Resolve all $ref in an OpenAPI spec.

Parameters:

Name Type Description Default
spec dict[str, Any]

The OpenAPI spec dictionary.

required
base_url str

Base URL for resolving relative references.

required
timeout float

HTTP timeout for fetching external refs.

30.0

Returns:

Type Description
dict[str, Any]

Spec with all resolvable refs inlined (cyclic ones stay $ref).

Source code in src/schemez/openapi/resolver.py
def resolve_openapi_refs(
    spec: dict[str, Any],
    base_url: str,
    timeout: float = 30.0,
) -> dict[str, Any]:
    """Resolve all $ref in an OpenAPI spec.

    Args:
        spec: The OpenAPI spec dictionary.
        base_url: Base URL for resolving relative references.
        timeout: HTTP timeout for fetching external refs.

    Returns:
        Spec with all resolvable refs inlined (cyclic ones stay `$ref`).
    """
    with OpenAPIResolver(base_url, timeout) as resolver:
        return resolver.resolve(spec)