0
# High-Level API
1
2
Simple one-function interface for common Markdown conversion tasks. The `commonmark()` function provides the most convenient way to convert Markdown text to various output formats.
3
4
## Capabilities
5
6
### Main Conversion Function
7
8
Converts CommonMark Markdown text to HTML, JSON, AST representation, or reStructuredText in a single function call.
9
10
```python { .api }
11
def commonmark(text, format="html"):
12
"""
13
Render CommonMark into HTML, JSON, AST, or reStructuredText.
14
15
Args:
16
text (str): CommonMark Markdown text to parse
17
format (str): Output format - 'html' (default), 'json', 'ast', or 'rst'
18
19
Returns:
20
str: Rendered output in specified format
21
22
Raises:
23
ValueError: If format is not one of the supported formats
24
"""
25
```
26
27
## Usage Examples
28
29
### HTML Output (Default)
30
31
```python
32
import commonmark
33
34
markdown = """
35
# Hello World
36
37
This is a **bold** text and this is *italic*.
38
39
- Item 1
40
- Item 2
41
"""
42
43
html = commonmark.commonmark(markdown)
44
print(html)
45
# Output: <h1>Hello World</h1>\n<p>This is a <strong>bold</strong> text...</p>\n<ul>\n<li>Item 1</li>\n<li>Item 2</li>\n</ul>\n
46
```
47
48
### JSON AST Output
49
50
```python
51
import commonmark
52
53
markdown = "# Hello\n*World*"
54
json_ast = commonmark.commonmark(markdown, format="json")
55
print(json_ast) # JSON representation of the AST
56
```
57
58
### Pretty-Printed AST
59
60
```python
61
import commonmark
62
63
markdown = "# Hello\n*World*"
64
ast_output = commonmark.commonmark(markdown, format="ast")
65
print(ast_output) # Human-readable AST structure
66
```
67
68
### reStructuredText Output
69
70
```python
71
import commonmark
72
73
markdown = """
74
# Title
75
76
Some **bold** text.
77
"""
78
79
rst = commonmark.commonmark(markdown, format="rst")
80
print(rst)
81
# Output: reStructuredText formatted content
82
```
83
84
## Error Handling
85
86
The function validates the format parameter and raises `ValueError` for unsupported formats:
87
88
```python
89
import commonmark
90
91
try:
92
result = commonmark.commonmark("# Hello", format="invalid")
93
except ValueError as e:
94
print(f"Error: {e}") # Error: format must be 'html', 'json' or 'ast'
95
```