Dynamic Redirect in WordPress

Code

add_action( 'rest_api_init', function () {

    register_rest_route( 'CUSTOM_RESTAPI/v1', '/ENDPOINT', array(
        'methods' => 'GET',
        'callback' => 'callback_function',
    ) );

} );

function callback_function( $request ) {

    $query_params = $request->get_query_params();

    $redirect_url = '';
    // process accordingly

    if ( ! empty( $redirect_url ) ) {
        wp_redirect( $redirect_url );
        exit;
    } else {
        return new WP_Error( 'invalid_parameters', 'Invalid query parameters.', array( 'status' => 400 ) );
    }

}

dynamic URL:
/wp-json/CUSTOM_RESTAPI/v1/ENDPOINT/?anyquery=data