How to add CMS Static Block Programmatically using Setup Patchdata in Magento 2?

From Magento 2.3, Core modules use the declarative schema approach rather than setup upgrade scripts. This is the new recommended approach for Magento versions 2.3 and upper version.

All the InstallData and UpgrageData will be replaced by Data Patch Versioning.

Now you have to create Setup/Patch/Data folder and create the class file for create/update attribute or add sample data in Magento.

The new module is simply residing in the app/code folder of Magento instance.

Just Create Folder under the app/code,
For example, We kept Packagename as Rbj and Modulename as CmsBlock.

You can keep any name for Packagename/Modulename. In our demo, we have kept Packagename_Modulename as Rbj_CmsBlock.

Now start with basic module creation, Registration.php file is to register our module.

Create a registration.php file,
Full Path,  app/code/Rbj/CmsBlock/registration.php,

Create a module.xml file,
app/code/Rbj/CmsBlock/etc/module.xml,

You don’t need to specify the setup_version and schema_version in a module.xml file.

Create a Patch file, Our module that contains the name is AddNewCmsStaticBlock.php
Path: app/code/Rbj/CmsBlock/Setup/Patch/Data/AddNewCmsStaticBlock.php

The DataPatchInterface expects the implementation of three functions: apply(), getDependencies() and getAliases().

The PatchVersionInterface expects the implementation of one functions: getVersion().

apply() function is used to define your core logic for install/upgrade data to the database.
getAliases()  which defines aliases for this patch class.
getDependencies() function expects an array of strings containing class names of dependencies.
getVersion() function, we can return a string with a version number of Patch.

The apply function is where we will create our CMS Page programmatically. You can check the function in code and all the fields are self-explanatory.

For installing our module in Magento 2,  We need to run the command using SSH,  Login with SSH and go to your project root path where Magento is installed,
Run below command,

For all patches which are successfully executed,

Magento inserts a record into the patch_list database table with the value of the patch_name field being the value of our Data patch full class.

You can check your CMS Static Block from Admin panel by, Content -> Elements ->Block.
Search your block name and you can see the new Block added using PatchData.

Check New Blogs, Get CMS Block usin Graphql Magento 2.