WordPress Disable WP JSON REST API Complete Guide

Since WordPress version 4.4 release of December 2015 and onwards, REST API infrastructure has been included in the core.

REST is short for Representational State Transfer. It is a standard client-server protocol that makes your website available as a web service. This means, that other applications or websites can retrieve information available on your website without a browser to access the website.

To retrieve information from a target website you just need to send a specific HTTP GET request. This request is understood by REST and executed.

The REST architecture uses multiple formats such as plain text, HTML, JSON, XML, YAML, etc to deliver requested data.

WordPress REST API endpoints are open and unsecured by default .

On just viewing or sending an HTTP GET request yourdomain.com/wp-json/wp/v2/users, we get the list of all the users on the website. Notice that the REST renders the ID number, name, URL, description, link, slug, avatar_urls, meta, and more. This exposes all your uses and it is a serious security concern issue.

To Prevent WP-JSON from Exposing Users

Add these code to functions.php by using Code Snippets

add_filter('rest_endpoints', function( $endpoints ) {
    if ( isset( $endpoints['/wp/v2/users'] ) ) {
        unset( $endpoints['/wp/v2/users'] );
    }
    if ( isset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] ) ) {
        unset( $endpoints['/wp/v2/users/(?P<id>[\d]+)'] );
    }
    return $endpoints;
});

After adding the code, yourdomain.com/wp-json/wp/v2/users should throw an error.


Not only that, but REST API can get you a list of all the posts saved on a website. You just have to pass a calculated request. From posts, pages, categories, tags, comments to taxonomies, media, users, settings, and more; REST could make everything available to anyone. These information retrieved is already publicly available by anyone viewing your site but the REST API parses it in such a way that it is easy for other automated forms to read it. This make your web content easily to be subjected to scraping/plagiarism.

yourdomain.com/wp-json

You may think to want to completely disable REST API.

However, bad news, a complete REST API deactivation will block the Block Editor (Gutenberg) and maybe some third party plugins along the way. 

To Disable REST API for Non-Logged in Users and Users of Administrator role only, use this code:

add_filter( 'rest_authentication_errors', 'wp_snippet_disable_rest_api' );

function wp_snippet_disable_rest_api( $access ) {
      //if( ! is_user_logged_in() ) {
      if( ! current_user_can( 'administrator' ) ) {
         return new WP_Error( 'rest_disabled', __('The WordPress REST API has been disabled.'), array( 'status' => rest_authorization_required_code()));
         }
}

After adding this, when any random visitors visit yourdomain.com/wp-json , it will throw an error.

There you have it, it is done and now can you have your rest of mind.