Python API Package

Purpose

This subtopic defines the Python-facing package interface that exposes the Rust-accelerated JSON serialization and deserialization functionality. It addresses the need for a clean, stable, and idiomatic Python API that serves as the entry point for all orjson users. By consolidating exports, type declarations, and error classes, it provides a consistent environment that abstracts the underlying Rust FFI complexity and enables seamless usage in Python applications.

Functionality

The Python API package primarily:

These elements collectively allow Python developers to interact with orjson as a natural extension of the Python standard library's `json` module but with significant performance and feature enhancements.

Key Methods and Constants

Error Classes

Fragment Class

A lightweight wrapper representing a JSON fragment, typically used internally or for advanced use cases where partial serialization output is needed.

Integration

This package acts as the bridge between Python code and the Rust FFI layer described in the parent topic. It imports the Rust-backed `orjson` module and exposes its functionality in a Python-native manner.

Diagram

classDiagram
    class PythonAPIPackage {
        +bytes dumps(obj: Any, default: Callable | None, option: int | None)
        +Any loads(obj: bytes | str)
        +int OPT_INDENT_2
        +int OPT_SORT_KEYS
        +int OPT_SERIALIZE_NUMPY
        +...
    }

    class JSONDecodeError {
        <<exception>>
    }
    class JSONEncodeError {
        <<exception>>
    }
    class Fragment {
        +bytes|str contents
    }

    PythonAPIPackage "1" o-- "1" JSONDecodeError : raises
    PythonAPIPackage "1" o-- "1" JSONEncodeError : raises
    PythonAPIPackage "1" o-- "1" Fragment : defines

    note for PythonAPIPackage "Imports Rust-backed orjson module\nRe-exports core functions and constants"

Code Snippet Illustrating Key Export

# pysrc/orjson/__init__.py (excerpt)
from .orjson import *
from .orjson import __version__

__all__ = (
    "__version__",
    "dumps",
    "loads",
    "JSONDecodeError",
    "JSONEncodeError",
    "Fragment",
    "OPT_INDENT_2",
    "OPT_SORT_KEYS",
    "OPT_SERIALIZE_NUMPY",
    # ... additional options
)

This snippet shows how the package re-exports Rust module symbols and explicitly specifies the public API surface, enabling clean imports and consistent usage patterns.


By serving as the Python interface layer, the Python API package ensures that orjson’s powerful Rust-based JSON processing capabilities are accessible, intuitive, and maintainable for Python developers.