REST : how do you handle the rest_no_route error?


i’m playing with the REST api and when doing some REST requests I got sometimes what I want, and sometimes this response generated by rest_ensure_response() :

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

…But how do you deal with that response, since it is returned as a simple JSON object (or array). It is not a WP_Error object that I could check.

Here’s how I do actually :

function api_request($url){

    $request = wp_remote_get($url);
    if (is_wp_error($request)) return $request;

    $response = wp_remote_retrieve_body( $request );
    if (is_wp_error($response)) return $response;

    $response = json_decode($response, true);

    //handle errors ?
    if ( $code = wpsstm_get_array_value('code',$response) ){
        $message = wpsstm_get_array_value('message',$response);
        $data = wpsstm_get_array_value('data',$response);
        $error = new WP_Error($code,$message,$data );

        $this->debug_log($error,'query API error');

        return $error;

    return $response;


Thanks !

gordie 2 years 2020-12-21T10:10:38-05:00 0 Answers 6 views 0

Leave an answer