How to create a rest api in wordpress?

Please share an example how to create a rest api in wordpress?

Wordpress allow us to create a rest api that can be used in application like mobile android, iOS apps or any other javascript frameworks. There is action hook "rest_api_init" which is used to create such an API in wordpress. You can understand it more exactly by below example:

// Get user details by id

function get_user_details(WP_REST_Request $request ) {    

    $id = $_REQUEST['uid'];    

    if( $id < 1)        

        return;

    $userd = get_userdata($id);    

    return new WP_REST_Response($userd, 200);

}

function pluginname_register_api_endpoints() {    

    register_rest_route( 'api', '/userDetails', array(      

            'methods' => 'GET',      

            'callback' => 'get_user_details',    

        ) 

    );

}   

add_action( 'rest_api_init', 'pluginname_register_api_endpoints' );

 

You can paste the above code in functions.php or in any plugin which will work perfectly. You can change the http request methods as per your choice like POST or GET. Hope you would have a basic idea of creating a rest api in wordpress but if you want to know in more details go to the documentation of above action hook.