1

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.

2 Answers2

2

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

  • Just find out that `/wp-json/` has to be included in the URL for async **js** requests on a site page, but it has to be dropped for internal **php** requests. – Cheslab Nov 13 '21 at 21:52
0

Tyler Collier has the correct answer here. Based on his advice that:

Ensure your callback to add_action( 'rest_api_init', 'dt_register_api_hooks' ); is being run.

We used PHP code that follows, in our WordPress, to resolve the BUG appearing in our Android Studio's Logcat:

I Webhook response: {"code":"rest_no_route","message":"No route was found matching the URL and request method.","data":{"status":404}}

// Register the custom webhook route
function register_custom_webhook_route() {
    register_rest_route('my-webhooks/v1', '/webhook/text', array(
        'methods' => 'POST',
        'callback' => 'handle_webhook_request',
    ));
}

// Ensure the callback to register_custom_webhook_route is being run
add_action('rest_api_init', 'register_custom_webhook_route');

Our error was putting an if !function_exists check on the 'register_custom_webhook_route' function.

The code relies on WP Rest API plugin and can be viewed in full at this GitHub link. The repo, cellnet, pulls text messages from your mobilephone and posts to your WordPress website based on authorization keywords.