Add custom post_meta to the WordPress rest API

So I needed some metadata to be in the rest API of a custom post_type.
The following adds the subtitle to the book post_type

add_action('rest_api_init', function () {
    register_rest_field('book', 'subtitle', [
        'get_callback'    => 'get_meta_data_for_rest',
        'update_callback' => null,
        'schema'          => null,
    ]);

});

function get_meta_data_for_rest($post, $field_name, $request)
{
    // it's not always an object
    if (isset($post->id) && ! empty($post->id)) {
        $post_id = $post->id;
    } elseif (isset($post['id']) && ! empty($post['id'])) {
        $post_id = $post['id'];
    } else {
        return null;
    }

    return get_post_meta($post_id, $field_name, true);
}