REST API and Gutenberg, A Marriage Made in Heaven?

REST API and Gutenberg, A Marriage Made in Heaven?

Adam Morgan

Gutenberg is the new WordPress system that is used for the new post editor for WordPress 5.0 is the first time that we have seen REST API used to connect data amongst the server and a JavaScript-driven interface. Here, we are taking a further look at how Gutenberg uses this WordPress REST API.

How Gutenberg Uses WordPress REST API to Save Posts

Gutenberg utilises the REST API to both create and edit posts and when it is updating any posts it uses wp_update_post(). In this process, the same hooks fire amidst rendering the post editor and saving data from it just as it was in previous versions of WordPress.

The Schema of Posts

The most important issue here is that the context conforms to the schema that has been set by the WordPress REST API. With the second version of WordPress API, there are many items represented including the post content, post excerpt and post title with an object that has a minimum if one index rendered. When using Gutenberg, the user has to change posts through the edit_posts function. There will also be a raw index with an unparsed mark up. You’ll only find this information given to those who can see the post editor, however, in case it is sensitive information.

Meta Data In Blocks

There is a number of different ways in which you can store block attribute information and a popular way is to save the information as post meta. When registering a block attribute that utilises meta storage you’ll need to let it know what meta key it should be using. You can then register this key with register_meta. When a block attribute and meta field are registered with the same field then everything else comes automatically.

What’s great about this updated version now is that the annoyance of saving meta box data has bene resolved. While it used to be that developers of custom metaboxes were the ones responsible for the authorisation, sanitisation and validation of the metadata on read and write this is no longer the case. A declarative API now automatically does this in the background, meaning a lot less work for you on the development end.

The Future of Gutenberg and REST API

While this new information may seem overwhelming, it is worth noting that information regarding REST API is still more important that Gutenberg, as Gutenberg instead focuses more on the client-side application. As the REST API is already there, this means that there does not have to be a lot of server-side code to interact with that user. If you need to make any changes to a post by Gutenberg, you can always simply implement what you know about REST API.