Skip to main content

Jentic OpenAPI Parser

Project description

jentic-openapi-parser

A Python library for parsing OpenAPI documents using pluggable parser backends. This package is part of the Jentic OpenAPI Tools ecosystem and provides a flexible, extensible architecture for OpenAPI document parsing with support for multiple YAML/JSON parsing libraries.

Features

  • Pluggable Backend Architecture: Support for multiple parsing strategies via entry points
  • Multiple Input Formats: Parse OpenAPI documents from file URIs or text strings (JSON/YAML)
  • Multiple Parser Backends: Choose from PyYAML, ruamel.yaml, or ruamel.yaml roundtrip modes
  • Enhanced JSON Serialization: Built-in support for datetime, UUID, Path, Decimal, Enum, and attrs classes
  • Type Safety: Full type hints with overloaded methods for precise return types
  • Extensible Design: Easy integration of third-party parser backends

Installation

pip install jentic-openapi-parser

Prerequisites:

  • Python 3.11+

Quick Start

Basic Parsing

from jentic.apitools.openapi.parser.core import OpenAPIParser

# Create parser with default backend (pyyaml)
parser = OpenAPIParser()

# Parse from file URI
doc = parser.parse("file:///path/to/openapi.yaml")
print(doc["info"]["title"])

# Parse from JSON string
json_doc = '{"openapi":"3.1.0","info":{"title":"My API","version":"1.0.0"}}'
doc = parser.parse(json_doc)

# Parse from YAML string
yaml_doc = """
openapi: 3.1.0
info:
  title: My API
  version: 1.0.0
"""
doc = parser.parse(yaml_doc)

Parse with Type Conversion

from ruamel.yaml import CommentedMap

# Parse with specific return type
parser = OpenAPIParser("ruamel-roundtrip")
doc = parser.parse(yaml_doc, return_type=CommentedMap)

# Parse with strict type checking
doc = parser.parse(yaml_doc, return_type=CommentedMap, strict=True)

Using Different Backends

# Use PyYAML backend (default)
parser = OpenAPIParser("pyyaml")
doc = parser.parse("file:///path/to/openapi.yaml")

# Use ruamel.yaml backend (safe mode)
parser = OpenAPIParser("ruamel-safe")
doc = parser.parse("file:///path/to/openapi.yaml")

# Use ruamel.yaml roundtrip mode (preserves comments and formatting info)
parser = OpenAPIParser("ruamel-roundtrip")
doc = parser.parse("file:///path/to/openapi.yaml", return_type=CommentedMap)
# Access line/column information
print(doc.lc.line, doc.lc.col)

Configuration Options

Backend Selection

# Use backend by name
parser = OpenAPIParser("pyyaml")

# Pass backend instance directly
from jentic.apitools.openapi.parser.backends.pyyaml import PyYAMLParserBackend
backend = PyYAMLParserBackend()
parser = OpenAPIParser(backend=backend)

# Pass backend class
parser = OpenAPIParser(backend=PyYAMLParserBackend)

Custom Configuration

import logging

# Configure with custom logger and timeouts
logger = logging.getLogger(__name__)
parser = OpenAPIParser(
    backend="pyyaml",
    logger=logger,
    conn_timeout=10,  # Connection timeout in seconds
    read_timeout=30   # Read timeout in seconds
)

Working with Return Types

The parser supports flexible return type handling:

from ruamel.yaml import CommentedMap

parser = OpenAPIParser("ruamel-roundtrip")

# Without return_type: Returns plain dict
doc = parser.parse(yaml_doc)
assert isinstance(doc, dict)

# With return_type: Returns specified type
doc = parser.parse(yaml_doc, return_type=CommentedMap)
assert isinstance(doc, CommentedMap)

# With strict=True: Raises error if type doesn't match
try:
    doc = parser.parse(yaml_doc, return_type=list, strict=True)
except TypeConversionError:
    print("Type mismatch!")

API Reference

OpenAPIParser

class OpenAPIParser:
    def __init__(
        self,
        backend: str | BaseParserBackend | Type[BaseParserBackend] | None = None,
        *,
        logger: logging.Logger | None = None,
        conn_timeout: int = 5,
        read_timeout: int = 10,
    ) -> None

Parameters:

  • backend: Parser backend to use. Can be:
    • str: Name of a backend registered via entry points (e.g., "pyyaml", "ruamel-safe", "ruamel-roundtrip")
    • BaseParserBackend: Instance of a parser backend
    • Type[BaseParserBackend]: Class of a parser backend (will be instantiated)
    • Defaults to "pyyaml" if None
  • logger: Custom logger instance (optional)
  • conn_timeout: Connection timeout in seconds for URI loading
  • read_timeout: Read timeout in seconds for URI loading

Methods:

  • parse(document: str) -> dict[str, Any]

    • Parse without type conversion, returns plain dict
  • parse(document: str, *, return_type: type[T], strict: bool = False) -> T

    • Parse with optional type conversion
    • document: File URI or text string (JSON/YAML)
    • return_type: Expected return type (e.g., dict, CommentedMap)
    • strict: If True, raises TypeConversionError if result doesn't match return_type
    • Returns: Parsed document
  • load_uri(uri: str) -> str

    • Load content from a URI (HTTP(S), file://, or local file path)
  • list_backends() -> list[str]

    • Static method to list all available parser backends

JSON Serialization

The parser includes enhanced JSON serialization utilities for working with OpenAPI documents:

from jentic.apitools.openapi.parser.core import json_dumps

# Serialize with special type support
from datetime import datetime
from pathlib import Path
from uuid import UUID

data = {
    "timestamp": datetime(2025, 10, 1, 12, 0, 0),
    "id": UUID("550e8400-e29b-41d4-a716-446655440000"),
    "path": Path("/var/log/app.log")
}

json_str = json_dumps(data, indent=2)
# Output:
# {
#   "id": "550e8400-e29b-41d4-a716-446655440000",
#   "path": "/var/log/app.log",
#   "timestamp": "2025-10-01T12:00:00"
# }

Supported Types:

  • datetime / date - Serialized to ISO 8601 format
  • UUID - Converted to string
  • Path - Converted to string
  • Decimal - Converted to float
  • Enum - Serialized using enum value
  • attrs classes - Converted to dictionaries

Exceptions

from jentic.apitools.openapi.parser.core.exceptions import (
    OpenAPIParserError,        # Base exception
    DocumentParseError,        # Parsing failed
    DocumentLoadError,         # URI loading failed
    InvalidBackendError,       # Backend initialization failed
    BackendNotFoundError,      # Backend not found
    TypeConversionError,       # Type conversion failed
)

Available Backends

pyyaml (Default)

Standard PyYAML-based parser. Fast and reliable for basic parsing needs.

Accepts: text (JSON/YAML strings)

parser = OpenAPIParser("pyyaml")
doc = parser.parse(content)

ruamel-safe

ruamel.yaml-based parser with safe loading. Provides better YAML 1.2 support than PyYAML.

Accepts: text (JSON/YAML strings), uri (file paths/URLs)

parser = OpenAPIParser("ruamel-safe")
doc = parser.parse(content)

ruamel-roundtrip

ruamel.yaml roundtrip mode that preserves comments, formatting, and provides line/column information.

Accepts: text (JSON/YAML strings), uri (file paths/URLs)

from ruamel.yaml import CommentedMap

parser = OpenAPIParser("ruamel-roundtrip")
doc = parser.parse(content, return_type=CommentedMap)

# Access line/column information
print(f"Line: {doc.lc.line}, Column: {doc.lc.col}")

Testing

Run the test suite:

uv run --package jentic-openapi-parser pytest packages/jentic-openapi-parser -v

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jentic_openapi_parser-1.0.0a11.tar.gz (11.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jentic_openapi_parser-1.0.0a11-py3-none-any.whl (18.4 kB view details)

Uploaded Python 3

File details

Details for the file jentic_openapi_parser-1.0.0a11.tar.gz.

File metadata

  • Download URL: jentic_openapi_parser-1.0.0a11.tar.gz
  • Upload date:
  • Size: 11.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for jentic_openapi_parser-1.0.0a11.tar.gz
Algorithm Hash digest
SHA256 8ed547dd2786e8c90881ca25c3b9cf2f6b309ed29521df1e2a57f876ad501b84
MD5 1a845cbc8bf23ffb88bb7fca799f5cb1
BLAKE2b-256 f938dfbeb6eb9b5d7ec7e1d89e87ce95a5d86f54d96050511b78e8368e4ad94b

See more details on using hashes here.

Provenance

The following attestation bundles were made for jentic_openapi_parser-1.0.0a11.tar.gz:

Publisher: release.yml on jentic/jentic-openapi-tools

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file jentic_openapi_parser-1.0.0a11-py3-none-any.whl.

File metadata

File hashes

Hashes for jentic_openapi_parser-1.0.0a11-py3-none-any.whl
Algorithm Hash digest
SHA256 1bc306fabc57fe594f73cc2a363683b3e751ad89751b6623a5ef1cfcb898da30
MD5 a46968e19e79eddd9d04e0f9c9a7814b
BLAKE2b-256 dd602812dc3665b8803e62c442c4fe232588674ab10c9b5c3c0ffdbce376bacb

See more details on using hashes here.

Provenance

The following attestation bundles were made for jentic_openapi_parser-1.0.0a11-py3-none-any.whl:

Publisher: release.yml on jentic/jentic-openapi-tools

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page