phpwordpressmariadbbuddypress

Simple custom WP BP API Endpoint to return data from a database table


I'm a PHP newbie trying to extend the Wordpress API on our BuddyPress website. I've created a database table which I plan on using to store a user's friends (or in our specific case "favourite members"). I would like to write an API endpoint to return a user's friends using the user's id as an input (i.e. "myapi/v1/favouritemembers/[user id]"). This is what I've done so far;

/*** Grab favourite members for a specified user ***/
function favourite_members( $data ) {
  $favourites = get_favourite_members(array(
    'user_id' => $data['user_id'],
  ) );

  if ( empty( $favourites ) ) {
    return null;
  }

  return $favourites;
}

function get_favourite_members( $data ){
  global $wpdb;
  $sql = $wpdb->prepare( "SELECT member_id FROM wp_my_favourite_members WHERE user_id = %d", $data['user_id'] );
  return $wpdb->get_results( $sql );
}

/*** Register register_rest_route ***/
add_action( 'rest_api_init', function () {
  register_rest_route( 'myapi/v1', '/favouritemembers/(?P<id>\d+)', array(
    'methods' => 'GET',
    'callback' => 'favourite_members',
  ) );
} );

I'm having trouble getting this to work correctly, the endpoint just returns an empty response. If I replace the query "SELECT member_id FROM wp_my_favourite_members WHERE user_id = %d", $data['user_id'] with "SELECT member_id FROM wp_my_favourite_members WHERE user_id = 1" then it works as expected, so I'm suspecting there may be something wrong with the way I am dealing with the input parameters in the get_favourite_members function, but I'm not sure.


Solution

  • I've worked it out, I was almost there, just needed to change

    register_rest_route( 'myapi/v1', '/favouritemembers/(?P<id>\d+)'
    

    to

    register_rest_route( 'myapi/v1', '/favouritemembers/(?P<user_id>\d+)'
    

    so the parameter names match.