How to Create Custom Get Rest Api In WordPress

The WordPress Has In build Rest Api and Also Provides End Points
To Create A Rest Api in word press are
1 :Get Methods
//End point is   : http://wpdadd.com/wp-json/api/v1/getwpdaddstaff
 
add_action( 'rest_api_init', function () {
 
 
    register_rest_route( 'api', '/v1/getwpdaddstaff', array(
 
 
        'methods' => 'GET',
 
 
        'callback' => 'wpdaddStuff',
 
 
    ));
 
 
});
 
 
function wpdaddStuff( $request ) {
 
 
 return   'Welcome to Wpdadd'  ;
 
 
 
 }
//ouput be
Welcome to Wpdadd
2 – Passing one of number parameter to Get Method
 
//Endpoint  http://wpdadd.com/wp-json/api/v1/get/wpdadd/{number}
 
 
 
add_action( 'rest_api_init', function () {
 
 
    register_rest_route( 'api', '/v1/get/wpdadd/(?P<id>\d+)', array(
 
 
        'methods' => 'GET',
 
 
        'callback' => 'wpdaddStuff',
 
 
    ));
 
 
});
 
 
 
 
 
function wpdaddStuff( $request ) {
 
 
 return   $request['id']  ;
 
 
 }
4 – Passing multiple parameters of combination of number and alphabet using get method
 
//Endpoint : http://wpdadd.com/wp-json/api/v1/getwp/{parameter 1}/{parameter2}
 
 
 
 
 
add_action( 'rest_api_init', function () {
 
 
    register_rest_route( 'api', '/v1/getwp/(?P<param1>[a-z0-9\-]+)/(?P<param2>[a-z0-9\-]+)', array(
 
 
        'methods' => 'GET',
 
 
        'callback' => 'wpdaddStuff',
 
 
    ));
 
 
});
 
 
 
 
 
function wpdaddStuff( $request ) {
 
 
 
 
 
 return $request['param1']." ".$request['param2'];
 
 
}

0 comments:

Post a Comment

Don't Forget to comment