How to create gutenberg block using REST API independently or as headless way?

Block editor blocks are dynamically constructed by parsing the HTML of post_content. Blocks are delimited by HTML comments that looks like these:

<!-- wp:image -->
<figure class="wp-block-image"><img src="https://wordpress.stackexchange.com/questions/359758/source.jpg" alt="" /></figure>
<!-- /wp:image -->

The way the actual data of blocks is stored depends entirely on the block. Blocks can either store their attributes inside the HTML comment as JSON (the editor takes care of this), like this example from here:

<!-- wp:latest-posts {"postsToShow":4,"displayPostDate":true} /-->

Or they can reconstruct the attributes by parsing the saved HTML. It could even be a mix. For example, the Button block stores the className attribute as in the comment as JSON, but recovers the link and label by parsing the HTML:

<!-- wp:button {"className":"is-style-outline"} -->
<div class="wp-block-button is-style-outline"><a class="wp-block-button__link" href="https://wpthemetestdata.wordpress.com/2018/11/03/block-button/">another button</a></div>
<!-- /wp:button -->

The possible ways of storing block data are documented here, and every block will work differently.

The problem here is that Blocks are not designed to be hand-written. They’re supposed to be created with the Block Editor. The logic used to convert the HTML in post_content back into a block in the Block Editor only exists in the code for that block. So to write HTML that can be converted into a block, you need to study the code used to register that block, to see what format it expects.

If you have a non-WordPress application that needs to create block content, the only reliable approach would be to adapt the block editor to that application.

Leave a Comment