Skip to content

Converters API Reference

Complete API reference for all BlockNote-py converters.

HTML Converters

Converts a list of Block objects to an HTML string.

Parameters:

Name Type Description Default
blocks List[Block]

List of validated Block objects to convert

required

Returns:

Type Description
str

An HTML string representation of the blocks

Raises:

Type Description
TypeError

If input is not a list or contains non-Block objects

Example

blocks = [ ... Block( ... id="1", ... type="heading", ... props={"level": 1}, ... content=[InlineContent(type="text", text="Title")], ... ) ... ] blocks_to_html(blocks) '

Title

'

Source code in .venv/lib/python3.11/site-packages/blocknote/converter/blocknote_to_html.py
def blocks_to_html(blocks: List[Block]) -> str:
    """
    Converts a list of Block objects to an HTML string.

    Args:
        blocks: List of validated Block objects to convert

    Returns:
        An HTML string representation of the blocks

    Raises:
        TypeError: If input is not a list or contains non-Block objects

    Example:
        >>> blocks = [
        ...     Block(
        ...         id="1",
        ...         type="heading",
        ...         props={"level": 1},
        ...         content=[InlineContent(type="text", text="Title")],
        ...     )
        ... ]
        >>> blocks_to_html(blocks)
        '<h1>Title</h1>'
    """
    if not isinstance(blocks, list):
        raise TypeError("Input must be a list of Block objects")

    if not blocks:
        return ""

    html_elements = []

    for i, block in enumerate(blocks):
        try:
            if not isinstance(block, Block):
                raise TypeError(
                    f"Item at index {i} must be a Block object, "
                    f"got {type(block)}"
                )

            html_element = _convert_block_to_html(block)
            if html_element:
                html_elements.append(html_element)
        except Exception as e:
            raise ValueError(
                f"Failed to convert block at index {i} to HTML: {e}"
            )

    return "\n".join(html_elements)

Converts an HTML string to a list of Block objects.

Parameters:

Name Type Description Default
html str

The HTML string to convert

required

Returns:

Type Description
List[Block]

List of validated Block objects

Raises:

Type Description
ValueError

If HTML parsing fails or produces invalid blocks

TypeError

If input is not a string

Source code in .venv/lib/python3.11/site-packages/blocknote/converter/html_to_blocknote.py
def html_to_blocks(html: str) -> List[Block]:
    """
    Converts an HTML string to a list of Block objects.

    Args:
        html: The HTML string to convert

    Returns:
        List of validated Block objects

    Raises:
        ValueError: If HTML parsing fails or produces invalid blocks
        TypeError: If input is not a string
    """
    if not isinstance(html, str):
        raise TypeError("Input must be a string")

    if not html.strip():
        return []

    try:
        parser = BlockNoteHTMLParser()
        parser.feed(html)
        return parser.get_blocks()
    except Exception as e:
        raise ValueError(f"Failed to parse HTML: {e}")

Markdown Converters

Converts a list of Block objects to a Markdown string.

Parameters:

Name Type Description Default
blocks List[Block]

List of validated Block objects to convert

required

Returns:

Type Description
str

A markdown string representation of the blocks

Raises:

Type Description
TypeError

If input is not a list or contains non-Block objects

Source code in .venv/lib/python3.11/site-packages/blocknote/converter/blocknote_to_md.py
def blocks_to_markdown(blocks: List[Block]) -> str:
    """
    Converts a list of Block objects to a Markdown string.

    Args:
        blocks: List of validated Block objects to convert

    Returns:
        A markdown string representation of the blocks

    Raises:
        TypeError: If input is not a list or contains non-Block objects

    """
    if not isinstance(blocks, list):
        raise TypeError("Input must be a list of Block objects")

    if not blocks:
        return ""

    markdown_lines = []

    for i, block in enumerate(blocks):
        try:
            if not isinstance(block, Block):
                raise TypeError(
                    f"Item at index {i} must be a Block object, "
                    f"got {type(block)}"
                )

            markdown_line = _convert_block_to_markdown(block)
            if markdown_line:  # Only add non-empty lines
                markdown_lines.append(markdown_line)
        except Exception as e:
            raise ValueError(
                f"Failed to convert block at index {i} to markdown: {e}"
            )

    return "\n\n".join(markdown_lines)

Converts a Markdown string to a list of Block objects.

Parameters:

Name Type Description Default
markdown str

The markdown string to convert

required

Returns:

Type Description
List[Block]

List of validated Block objects

Raises:

Type Description
ValueError

If markdown parsing fails or produces invalid blocks

TypeError

If input is not a string

Source code in .venv/lib/python3.11/site-packages/blocknote/converter/md_to_blocknote.py
def markdown_to_blocks(markdown: str) -> List[Block]:
    """
    Converts a Markdown string to a list of Block objects.

    Args:
        markdown: The markdown string to convert

    Returns:
        List of validated Block objects

    Raises:
        ValueError: If markdown parsing fails or produces invalid blocks
        TypeError: If input is not a string
    """
    if not isinstance(markdown, str):
        raise TypeError("Input must be a string")

    if not markdown.strip():
        return []

    try:
        md = MarkdownIt()
        tokens = md.parse(markdown)
        blocks = []

        i = 0
        while i < len(tokens):
            token = tokens[i]
            try:
                if token.type == "heading_open":
                    block = _parse_heading(tokens, i)
                    blocks.append(block)
                    i += 3
                elif token.type == "paragraph_open":
                    block = _parse_paragraph(tokens, i)
                    blocks.append(block)
                    i += 3
                elif (
                    token.type == "bullet_list_open"
                    or token.type == "ordered_list_open"
                ):
                    block, skip_count = _parse_list(tokens, i)
                    blocks.append(block)
                    i += skip_count
                elif token.type == "blockquote_open":
                    block = _parse_quote(tokens, i)
                    blocks.append(block)
                    i += 3
                else:
                    i += 1
            except Exception as e:
                raise ValueError(
                    f"Failed to parse markdown token at position {i}: {e}"
                )

        return blocks

    except Exception as e:
        raise ValueError(f"Failed to parse markdown: {e}")

Dictionary Converters

Converts a list of Block objects to a list of dictionaries.

Parameters:

Name Type Description Default
blocks List[Block]

List of Block objects to convert

required

Returns:

Type Description
List[Dict[str, Any]]

List of dictionaries representing the blocks

Raises:

Type Description
TypeError

If input is not a list or contains non-Block objects

Source code in .venv/lib/python3.11/site-packages/blocknote/converter/blocknote_to_dict.py
def blocks_to_dict(blocks: List[Block]) -> List[Dict[str, Any]]:
    """
    Converts a list of Block objects to a list of dictionaries.

    Args:
        blocks: List of Block objects to convert

    Returns:
        List of dictionaries representing the blocks

    Raises:
        TypeError: If input is not a list or contains non-Block objects
    """
    if not isinstance(blocks, list):
        raise TypeError("Input must be a list of Block objects")

    result = []
    for i, block in enumerate(blocks):
        if not isinstance(block, Block):
            raise TypeError(
                f"Item at index {i} must be a Block object, got {type(block)}"
            )

        result.append(_block_to_dict(block))

    return result

Converts a list of dictionaries to a list of Block objects.

Parameters:

Name Type Description Default
data List[Dict[str, Any]]

List of dictionaries representing Blocknote blocks

required

Returns:

Type Description
List[Block]

List of validated Block objects

Raises:

Type Description
TypeError

If input is not a list

ValueError

If any dictionary cannot be converted to a valid Block

Source code in .venv/lib/python3.11/site-packages/blocknote/converter/dict_to_blocknote.py
def dict_to_blocks(data: List[Dict[str, Any]]) -> List[Block]:
    """
    Converts a list of dictionaries to a list of Block objects.

    Args:
        data: List of dictionaries representing Blocknote blocks

    Returns:
        List of validated Block objects

    Raises:
        TypeError: If input is not a list
        ValueError: If any dictionary cannot be converted to a valid Block
    """
    if not isinstance(data, list):
        raise TypeError("Input must be a list of dictionaries")

    blocks = []
    for i, item in enumerate(data):
        try:
            if not isinstance(item, dict):
                raise TypeError(
                    f"Item at index {i} must be a dictionary, got {type(item)}"
                )

            block_dict = _normalize_block_dict(item)
            block = Block(**block_dict)
            blocks.append(block)
        except Exception as e:
            raise ValueError(
                f"Failed to convert dict at index {i} to Block: {e}. "
                f"Dict: {item}"
            )
    return blocks

Usage Examples

HTML Conversion

from blocknote.converter import blocks_to_html, html_to_blocks
from blocknote.schema import Block, InlineContent

# Create a block
block = Block(
    id="example",
    type="paragraph",
    content=[
        InlineContent(
            type="text",
            text="Hello, World!",
            styles={"bold": True}
        )
    ]
)

# Convert to HTML
html = blocks_to_html([block])
print(html)  # <p><strong>Hello, World!</strong></p>

# Convert back to blocks
blocks = html_to_blocks(html)
print(blocks[0].content[0].text)  # Hello, World!

Markdown Conversion

from blocknote.converter import blocks_to_markdown, markdown_to_blocks

# Convert blocks to Markdown
markdown = blocks_to_markdown([block])
print(markdown)  # **Hello, World!**

# Convert Markdown to blocks
md_text = "# Heading\n\nThis is **bold** text."
blocks = markdown_to_blocks(md_text)

Dictionary Conversion

from blocknote.converter import blocks_to_dict, dict_to_blocks

# Convert to dictionary
block_dict = blocks_to_dict([block])
print(block_dict)

# Convert back to blocks
blocks = dict_to_blocks(block_dict)

Error Handling

All converters raise appropriate exceptions for invalid input:

from blocknote.converter import blocks_to_html
from pydantic import ValidationError

try:
    html = blocks_to_html("invalid input")
except TypeError as e:
    print(f"Type error: {e}")

try:
    html = blocks_to_html([{"invalid": "block"}])
except TypeError as e:
    print(f"Invalid block: {e}")

Type Definitions

Function Signatures

def blocks_to_html(blocks: List[Block]) -> str: ...
def html_to_blocks(html: str) -> List[Block]: ...
def blocks_to_markdown(blocks: List[Block]) -> str: ...
def markdown_to_blocks(markdown: str) -> List[Block]: ...
def blocks_to_dict(blocks: List[Block]) -> List[Dict[str, Any]]: ...
def dict_to_blocks(data: List[Dict[str, Any]]) -> List[Block]: ...

Common Exceptions

  • TypeError: Invalid input type
  • ValueError: Invalid data structure or content
  • ValidationError: Pydantic validation failure

Performance Considerations

Memory Usage

  • Large documents may consume significant memory
  • Consider processing in batches for very large datasets

Processing Time

  • Complex nested structures take longer to process
  • HTML parsing is generally slower than dictionary conversion
  • Markdown parsing requires additional dependencies

Optimization Tips

  1. Batch Processing: Process multiple blocks at once
  2. Caching: Cache converted results when possible
  3. Validation: Pre-validate input data to avoid processing errors
  4. Memory Management: Use generators for large datasets

Best Practices

Input Validation

def safe_convert(blocks):
    if not isinstance(blocks, list):
        raise TypeError("Input must be a list")

    if not all(isinstance(b, Block) for b in blocks):
        raise TypeError("All items must be Block objects")

    return blocks_to_html(blocks)

Error Recovery

def robust_html_conversion(blocks):
    try:
        return blocks_to_html(blocks)
    except Exception as e:
        logger.error(f"Conversion failed: {e}")
        return "<p>Content unavailable</p>"

Performance Monitoring

import time
from functools import wraps

def time_conversion(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.2f}s")
        return result
    return wrapper

@time_conversion
def convert_large_document(blocks):
    return blocks_to_html(blocks)