How to pass outside function to WP_REST_Request

My approach would be, to declare the function in functions.php and then call it whenever you need.

Since you are trying to use superglobals, you can access them anywhere. Move the code from your page-foobar.php to your theme’s functions.php, and use this whenever you need to access it:

ipAddress();

So, in your REST function you can have:

function foobar(\WP_REST_Request $request) {
    $ip_address = ipAddress();
    if ($ip_address == "undefined") :
        return new WP_Error( 'bad_ip', 'No IP found', array( 'status' => 404 ) );
    endif;
}