How do I create menu programmatically? I read through the Drupal 8 menu_api documentation in drupal.org. The example guide lists an option to create menu links and insert them into an existing menu. How does one create menu itself first and insert the menu links afterwords? 

I used the entitytype manager based on the other answer in stackexchange, but going yml way is recommended. Any pointers? 

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;

\Drupal::entityTypeManager()
-&gt;getStorage('menu')
-&gt;create([
 'id' =&gt; 'test',
 'label' =&gt; 'test menu',
'description' =&gt; 'test test',
 ])
 -&gt;save();


Using routes below to create the links:

 test.home:
 title: 'Home'
 url: 'test.url'
 menu_name: test
 weight: 1
If you have a feature where you need to create a menu whenever something happens, using the code should be just fine.

I prefer using the static create method on the entity object \Drupal\menu\Entity\Menu::create, but the manager is fine as well.

If you are creating menu's on your development environment as part of setting up your drupal site, I would advice using config export/import. If you use drush, you can make it part of the deployment to import configuration so production always reflect the configuration you have saved. I prefer to do things like this, but for small sites it might be a bit overkill.