REST API with wordpress

The REST API is included in WordPress 4.7! Plugins are no longer required and you can create a rest API only with wordpress framework.

I ‘ve create a REST API that make specific search on the database base on email(second block of code).

Also I ‘ve added a filter(first block of code) to prevent unauthenticated users for making this call.

//filter for wordpress Rest Api

   function mytheme_only_allow_logged_in_rest_access( $access ) {
   if( ! is_user_logged_in() ) {
  return new WP_Error( 'rest_cannot_access', __( 'Only authenticated users can access the REST API.', 'disable-json-api' ), array( 'status' => rest_authorization_required_code() ) );
   }
   return $access;
      }
     add_filter( 'rest_authentication_errors', 'mytheme_only_allow_logged_in_rest_access' );
    }
  }

//Rest SERVICE

function prefix_register_rest_route() {
    register_rest_route( 'routeName1/routeName2', '/rest/(?P<email>\S+)', array(
        // Supported methods for this endpoint. WP_REST_Server::READABLE translates to GET.
        'methods' => WP_REST_Server::READABLE,
        // Register the callback for the endpoint.
        'callback' => 'prefix_get_rest'
    ) );
}

add_action( 'rest_api_init', 'prefix_register_rest_route' ); 


function prefix_get_rest( $request ) {
    // Here we are accessing the path variable 'email' from the $request.    
    $rest = prefix_get_the_rest( $request['email']);
    return rest_ensure_response( $rest );
}

function prefix_get_the_rest( $email ) {
 global $wpdb;
    //$email ="blabla@gmail.com";
    $query = 'SELECT id, surname, firstname, etc, etc2, etc3, etc4 FROM accounts where email="'.$email.'"';
    $list = $wpdb->get_results($query);   
    //return rest_ensure_response( $list );
    $rests =$list ;
    $rest = '';

return $rests;

}

Σχόλια