WordPress Rest API with rest_do_request, possible race condition?

The fundamental problem is that the code tries to use the REST API endpoint before the endpoints have been registered.

Specifically it needs to do this after the rest_api_init hook has fired. Try to do it on a hook that runs after plugins and theme are loaded such as wp_loaded.

In general avoid doing work in the root scope of a plugins file or functions.php. WordPress is architected around hooks and filters and a particular load process, so it’s more accurate to think of hooks as events on a timeline. By just putting stuff in the plugin file without using a hook, it’s essentially running in prehistoric times. You can’t ask it to drive from A to B because cars haven’t been invented yet.

So this isn’t a problem of what, it’s a problem of when