how-to-post-gutenberg-blocks-python-wordpress-rest-api

How to Post Gutenberg Blocks with Python and WP REST API

Learn how to authenticate with WordPress Application Passwords and post clean Gutenberg blocks from Python without triggering block recovery errors.

Have you ever pushed an article to WordPress with Python, only to see everything trapped inside a single Classic block?

Even worse, maybe you tried adding block markup and got hit with the dreaded “Attempt Block Recovery” warning in the editor.

The good news is that posting native Gutenberg blocks from Python is simple once you follow WordPress’s exact comment syntax. In this step-by-step guide, we will show you how to authenticate with Application Passwords and build clean Gutenberg blocks in Python.

Executive Summary

  • Native Block Support: WordPress stores Gutenberg blocks as HTML wrapped in <!-- wp:... --> comment delimiters inside the content field.
  • Secure Auth Setup: Use HTTP Basic Auth with a WordPress Application Password over HTTPS so your main login stays safe.
  • Two Practical Methods: Send raw block templates for quick scripts, or use Python helper functions to generate valid blocks dynamically.
  • Zero Recovery Warnings: Matching inner HTML classes and closing comment tags prevents editor validation errors.

Table of Contents

How WordPress Stores Gutenberg Blocks

Many developers assume the WordPress REST API expects a JSON tree for Gutenberg blocks. In reality, WordPress stores block content as plain HTML surrounded by special HTML comments.

When you send a POST request to /wp-json/wp/v2/posts, WordPress saves your content string directly into post_content. When someone opens the post in the Block Editor, WordPress parses those comment tags to render individual blocks.

If those comment tags are missing, WordPress wraps your entire article in a legacy Classic block. If the HTML inside the comments does not match what the block expects, the editor flags a validation error.

Common Gutenberg Block Markup Reference

Before writing Python code, keep this quick reference handy. Each core block needs an opening comment, matching HTML tags, and an exact closing comment.

Block TypeOpening CommentRequired Inner HTMLClosing Comment
Paragraph<!-- wp:paragraph --><p>Text here.</p><!-- /wp:paragraph -->
Heading (H2)<!-- wp:heading --><h2 class="wp-block-heading">Title</h2><!-- /wp:heading -->
Heading (H3)<!-- wp:heading {"level":3} --><h3 class="wp-block-heading">Subtitle</h3><!-- /wp:heading -->
Bullet List<!-- wp:list --><ul class="wp-block-list"><li>Item</li></ul><!-- /wp:list -->
Table<!-- wp:table --><figure class="wp-block-table"><table>...</table></figure><!-- /wp:table -->
Code Block<!-- wp:code --><pre class="wp-block-code"><code>...</code></pre><!-- /wp:code -->
How to Post Gutenberg Blocks with Python and WP REST API Data Chart

Method 1: Post Raw Gutenberg Markup with Python (Quick Start)

If you want to test block publishing right away, start with a short script that sends hardcoded Gutenberg markup. This confirms your authentication and block formatting work together.

Step 1: Install Requests and Load Your Credentials

First, make sure the requests library is installed in your Python environment (pip install requests). Then store your WordPress URL, username, and Application Password in environment variables.

import base64
import os
import requests

SITE_URL = os.environ["WP_SITE_URL"].rstrip("/")
USERNAME = os.environ["WP_USERNAME"]
APP_PASSWORD = os.environ["WP_APP_PASSWORD"].replace(" ", "")

token = base64.b64encode(f"{USERNAME}:{APP_PASSWORD}".encode("utf-8")).decode("utf-8")
HEADERS = {
    "Authorization": f"Basic {token}",
    "Content-Type": "application/json",
    "User-Agent": "TeckScaler-Block-Publisher/1.0",
}

Step 2: Compose Valid Gutenberg Block HTML

Next, write a multi-line string containing valid block delimiters. Notice how the <h2> tag includes class="wp-block-heading", which modern WordPress versions require for clean validation.

gutenberg_content = """<!-- wp:heading -->
<h2 class="wp-block-heading">Automated Section Title</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>This paragraph was published as a native Gutenberg block from Python.</p>
<!-- /wp:paragraph -->"""

Step 3: Send the POST Request as a Draft

Finally, send the payload to /wp-json/wp/v2/posts with "status": "draft". Opening the draft in the WordPress editor lets you verify that every block loads cleanly without warnings.

payload = {
    "title": "Python Gutenberg Block Test",
    "slug": "python-gutenberg-block-test",
    "content": gutenberg_content,
    "status": "draft",
}

response = requests.post(
    f"{SITE_URL}/wp-json/wp/v2/posts",
    headers=HEADERS,
    json=payload,
    timeout=30,
)
response.raise_for_status()
print("Created draft ID:", response.json()["id"])

Pro Tip: Always test new block templates with "status": "draft" first. You can inspect the post inside the WordPress Block Editor before switching it to "publish".

Method 2: Build a Reusable Python Block Helper (Developer Workflow)

Writing comment tags by hand gets messy when you generate long guides or data tables. A small set of Python helper functions keeps your code readable and escapes HTML characters safely.

Step 1: Create Core Block Helper Functions

Create a dedicated module with functions for paragraphs, headings, lists, and code blocks. Using Python’s built-in html.escape() on code snippets stops angle brackets from breaking your page layout.

import html
import json


def wp_paragraph(text: str) -> str:
    return f"<!-- wp:paragraph -->\n<p>{text}</p>\n<!-- /wp:paragraph -->"


def wp_heading(text: str, level: int = 2) -> str:
    attrs = "" if level == 2 else f" {json.dumps({'level': level})}"
    return (
        f"<!-- wp:heading{attrs} -->\n"
        f'<h{level} class="wp-block-heading">{text}</h{level}>\n'
        f"<!-- /wp:heading -->"
    )


def wp_code(code: str) -> str:
    escaped = html.escape(code)
    return (
        "<!-- wp:code -->\n"
        f'<pre class="wp-block-code"><code>{escaped}</code></pre>\n'
        "<!-- /wp:code -->"
    )

Step 2: Assemble Blocks into a Clean Document

Next, join your block outputs with double newlines (\n\n). WordPress uses whitespace between block comments to separate each element cleanly in the database.

blocks = [
    wp_heading("Why Use Python Block Helpers?"),
    wp_paragraph("Helper functions keep your HTML valid and prevent typos."),
    wp_heading("Sample Python Snippet", level=3),
    wp_code('print("Hello, Gutenberg!")'),
]

full_content = "\n\n".join(blocks)

Step 3: Publish and Verify in the Block Editor

Send full_content in your POST request payload just like in Method 1. When you open the post in WordPress, click each block to confirm it shows the proper Paragraph, Heading, and Code block toolbars.

Note: In WordPress 6.6 and newer, list items inside wp:list use nested <!-- wp:list-item --> comments. Wrapping each <li> with <!-- wp:list-item --> keeps list blocks 100% compliant.

Troubleshooting Block Recovery Warnings

If you open a published post and see “This block contains unexpected or invalid content,” one of three small mismatches is usually to blame:

  • **Missing wp-block-* CSS Classes:** Modern WordPress expects class="wp-block-heading" on headings and class="wp-block-list" on lists. Leaving those classes off triggers a block recovery prompt.
  • Attribute JSON Mismatch: If you pass {"level":3} in the opening <!-- wp:heading --> comment, the inner HTML tag must be <h3>, not <h2>.
  • Unescaped Characters in Code Blocks: Raw < or > characters inside <pre><code> tags break HTML parsing. Always pass code strings through html.escape() first.

Frequently Asked Questions

Can I post Gutenberg blocks without using HTML comments?

No. Without <!-- wp:... --> comment delimiters, WordPress treats the entire content payload as a single Classic block instead of native Gutenberg blocks.

How do I find the exact markup for a custom or third-party block?

Create a sample post in the WordPress Block Editor, add the block you want, and switch to the Code editor view (via the three-dot menu in the top right). Copy the exact comment attributes and inner HTML directly into your Python helper.

Do I need to escape JSON inside Gutenberg block comments?

Yes, any attributes inside <!-- wp:block {...} --> must be valid JSON with double quotes. Using json.dumps() in Python guarantees valid formatting every time.

Can I update only the content of an existing Gutenberg post?

Yes. Send a POST request to /wp-json/wp/v2/posts/{post_id} with only the "content" key in your JSON body, and WordPress will leave the title, slug, and featured image untouched.

You May Also Like

We hope this guide helped you learn how to authenticate and post Gutenberg blocks using Python. Written by the TeckScaler Editorial Engineering Team. Explore more resources to level up your publishing pipeline:

Primary Sources and References