wp_get_object_terms() returns invalid taxonomy inside rest_api_init hook

I tried to reproduce the issue with the following post type and taxonomy registration code (which I put in the functions.php file of a child theme):

add_action( 'init', function () {
    register_post_type( 'venue', [
        'public'       => true,
        'label'        => 'Venues',
        'show_in_rest' => true,
    ] );

    register_taxonomy( 'country', 'venue', [
        'public'            => true,
        'label'             => 'Countries',
        'show_admin_column' => true,
        'show_in_rest'      => true,
    ] );
} );

Then I used your code to register the custom REST API endpoint (note though, you should always set the permission callback just as I did below):

register_rest_route( 'myevents/v2', '/venue', array(
    'methods'             => 'GET',
    'callback'            => 'myevents_get_post_items',
    // always set this, but the value doesn't need to be __return_true
    'permission_callback' => '__return_true',
) );

And then when I visited https://example.com/wp-json/myevents/v2/venue, I did not get the “invalid taxonomy” error.

But I did notice an issue in your myevents_get_post_items() function — the $post variable is undefined.

Hence I used $post_id = get_the_ID(); instead of $post_id = $post->ID;. (But you could instead add global $post; or $post = get_post(); somewhere in your function, before you access the $post.)

So please fix that issue and ensure that your custom taxonomy is registered in the init hook. And note that the wp_get_object_terms() call worked for me, with or without setting the show_in_rest to a true.

Also, I guessed those echo and print_r() calls were just for testing, but still, keep in mind that your callback should not echo anything.

error code: 523