I created a custom endpoint for the WordPress API-REST. I can access it normally via browser. But when I try to access it via WP_REST_Request, I get a message of "rest_no_route (404)"
<?php
add_action( 'rest_api_init', 'custom_routes_rifa');
function custom_routes_rifa(){
register_rest_route(
'pluginrifa/v2', '/infos/', array(
'methods' => 'GET',
'callback' => 'api_rifa_infos',
'show_in_index' => false
)
);
}
If I put /wp-json/pluginrifa/v2/infos/?rifa=140 in the browser everything works as it should, but the code below returns 404:
<?php
$request = new WP_REST_Request( 'GET', '/wp-json/pluginrifa/v2/infos' );
$request->set_query_params( [ 'rifa' => 140 ] );
$response = rest_do_request( $request );
$server = rest_get_server();
$data = $server->response_to_data( $response, false );
$json = wp_json_encode( $data );
$obj = json_decode($json);
I found this discussion Custom route endpoint for WP-REST API gives "code": "rest_no_route", error but none of the proposed solutions resolved, apart from apparently be something different, as it works via HTTP, but via WP_REST_Request it doesn't.
I found the problem, I had to replace:
<?php $request = new WP_REST_Request( 'GET', '/wp-json/pluginrifa/v2/infos' );
to
<?php $request = new WP_REST_Request( 'GET','/pluginrifa/v2/infos' );
/wp-json/ needs to be omitted from the request. I don't know why, but in several places on the internet, the examples for new WP_REST_Request are using wp-json in the URL. Perhaps, this has fallen on some WordPress update