Skip to content

OpenAPI Integration

This section documents the OpenAPI/Swagger integration capabilities of the ToolRegistry library.

Architecture Overview

The OpenAPI integration is designed to automatically discover and register REST API endpoints as tools based on OpenAPI specifications. The architecture follows a three-layer design:

Core Components

  1. OpenAPIToolWrapper: A wrapper class that provides both synchronous and asynchronous HTTP client methods for API calls

  2. Handles GET, POST, PUT, DELETE requests

  3. Supports parameter processing and validation
  4. Integrates with a built-in HTTP client for HTTP communication

  5. OpenAPITool: A tool class that preserves function metadata extracted from OpenAPI specifications

  6. Automatically generates parameter schemas from OpenAPI specs

  7. Normalizes tool names and descriptions
  8. Maintains namespace support

  9. OpenAPIIntegration: The main integration class that orchestrates the registration process

  10. Parses OpenAPI specifications
  11. Creates tool instances for each endpoint
  12. Supports both synchronous and asynchronous registration

Design Patterns

  • Factory Pattern: OpenAPITool.from_openapi_spec() creates tool instances from specifications
  • Wrapper Pattern: OpenAPIToolWrapper provides a unified interface for HTTP operations
  • Template Method: Both sync and async versions follow similar patterns with async/await support

Key Features

  • Automatic parameter extraction from OpenAPI schemas
  • Support for query parameters, path parameters, and request bodies
  • Namespace support for organizing tools
  • Full async/await compatibility
  • Automatic HTTP status error handling

API Reference

OpenAPIToolWrapper

Wrapper class that provides both synchronous and asynchronous methods for OpenAPI tool calls.

toolregistry.integrations.openapi.integration.OpenAPIToolWrapper

OpenAPIToolWrapper(client_config: HttpClientConfig, name: str, method: str, path: str, params: list[str] | None, persistent: bool = True)

Bases: BaseToolWrapper

Wrapper class that provides both synchronous and asynchronous methods for OpenAPI tool calls.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for the HTTP client.

required
name str

The name of the tool.

required
method str

The HTTP method (e.g., "get", "post").

required
path str

The API endpoint path.

required
params Optional[List[str]]

List of parameter names for the API call.

required
persistent bool

If True, reuse a persistent HTTP client.

True

call_async async

call_async(*args: Any, **kwargs: Any) -> Any

Asynchronously call the API using the client configuration.

Parameters:

Name Type Description Default
*args Any

Positional arguments for the API call.

()
**kwargs Any

Keyword arguments for the API call.

{}

Returns:

Name Type Description
Any Any

The JSON response from the API.

Raises:

Type Description
ValueError

If the tool name is not set.

HTTPStatusError

If an HTTP error occurs.

call_sync

call_sync(*args: Any, **kwargs: Any) -> Any

Synchronously call the API using the client configuration.

Parameters:

Name Type Description Default
*args Any

Positional arguments for the API call.

()
**kwargs Any

Keyword arguments for the API call.

{}

Returns:

Name Type Description
Any Any

The JSON response from the API.

Raises:

Type Description
ValueError

If the tool name is not set.

HTTPStatusError

If an HTTP error occurs.

OpenAPITool

Wrapper class for OpenAPI tools preserving function metadata.

toolregistry.integrations.openapi.integration.OpenAPITool

Bases: Tool

Wrapper class for OpenAPI tools preserving function metadata.

from_openapi_spec classmethod

from_openapi_spec(client_config: HttpClientConfig, path: str, method: str, spec: dict[str, Any], namespace: str | None = None, persistent: bool = True) -> OpenAPITool

Create an OpenAPITool instance from an OpenAPI specification.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for HTTP client.

required
path str

API endpoint path.

required
method str

HTTP method.

required
spec Dict[str, Any]

The OpenAPI operation specification.

required
namespace Optional[str]

Optional namespace to prefix tool names with.

None

Returns:

Name Type Description
OpenAPITool OpenAPITool

An instance of OpenAPITool configured for the specified operation.

OpenAPIIntegration

Handles integration with OpenAPI services for tool registration.

toolregistry.integrations.openapi.integration.OpenAPIIntegration

OpenAPIIntegration(registry: ToolRegistry)

Handles integration with OpenAPI services for tool registration.

Attributes:

Name Type Description
registry ToolRegistry

The tool registry where tools are registered.

close

close() -> None

Close all persistent HTTP clients (sync).

close_async async

close_async() -> None

Close all persistent HTTP clients (async).

register_openapi_tools

register_openapi_tools(client_config: HttpClientConfig, openapi_spec: dict[str, Any], namespace: bool | str = False, persistent: bool = True) -> None

Synchronously register all tools defined in an OpenAPI specification.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for the HTTP client.

required
openapi_spec Dict[str, Any]

The OpenAPI specification dictionary.

required
namespace Union[bool, str]

Whether to prefix tool names with a namespace. - If False, no namespace is used. - If True, the namespace is derived from the OpenAPI info.title. - If a string is provided, it is used as the namespace. Defaults to False.

False
persistent bool

If True (default), reuse a persistent HTTP client for connection pooling.

True

Returns:

Type Description
None

None

register_openapi_tools_async async

register_openapi_tools_async(client_config: HttpClientConfig, openapi_spec: dict[str, Any], namespace: bool | str = False, persistent: bool = True) -> None

Asynchronously register all tools defined in an OpenAPI specification.

Parameters:

Name Type Description Default
client_config HttpClientConfig

Configuration for the HTTP client.

required
openapi_spec Dict[str, Any]

The OpenAPI specification dictionary.

required
namespace Union[bool, str]

Whether to prefix tool names with a namespace. - If False, no namespace is used. - If True, the namespace is derived from the OpenAPI info.title. - If a string is provided, it is used as the namespace. Defaults to False.

False
persistent bool

If True (default), reuse a persistent HTTP client for connection pooling.

True

Returns:

Type Description
None

None

Module Utilities

OpenAPI Utils

Utility functions for OpenAPI processing.

toolregistry.integrations.openapi.utils

determine_urls

determine_urls(url: str) -> dict[str, Any]

Determine whether the given URL or its common endpoints contain an OpenAPI schema.

Parameters:

Name Type Description Default
url str

Base URL or schema URL.

required

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: Contains "found" (bool), "schema_url" (str) if valid or None, and "base_api_url" (str).

extract_base_url_from_specs

extract_base_url_from_specs(openapi_spec: dict[str, Any]) -> str | None

Extract and validate the base URL from the 'servers' field of the OpenAPI specification.

Parameters:

Name Type Description Default
openapi_spec Dict[str, Any]

The parsed OpenAPI specification.

required

Returns:

Type Description
str | None

Optional[str]: The validated base API URL extracted from the 'servers' field, or None if not valid.

load_openapi_spec

load_openapi_spec(uri: str) -> dict[str, Any]

Sync version that calls the async implementation.

Parameters:

Name Type Description Default
uri str

URL or file path pointing to an OpenAPI specification.

required

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: A dictionary containing the parsed OpenAPI specification.

Raises:

Type Description
ValueError

If URI retrieval, parsing, or decoding fails.

load_openapi_spec_async async

load_openapi_spec_async(uri: str) -> dict[str, Any]

Async version of load_openapi_spec using AsyncClient.

Parameters:

Name Type Description Default
uri str

URL or file path pointing to an OpenAPI specification.

required

Returns:

Type Description
dict[str, Any]

Dict[str, Any]: A dictionary containing the parsed OpenAPI specification.

Raises:

Type Description
ValueError

If URI retrieval, parsing, or decoding fails.