BP REST API Handbook
Just like the WordPress REST API does it for content data types the BP REST API provides API endpoints for BuddyPress community actions data types that allow developers to interact with sites remotely by sending and receiving JSON (JavaScript Object Notation) objects. JSON is an open standard data format that is lightweight and human-readable, and looks like Objects do in JavaScript; hence the name.
When you send content to or make a request to the API, the response will be returned in JSON. This enables developers to create, read and update BuddyPress user generated content from client-side JavaScript or from external applications, even those written in languages beyond PHP.
Why use the BP REST API?
The BP REST API makes it easier than ever to use BuddyPress in new and exciting ways, such as creating Single Page Applications on top of BuddyPress. You could create a Template Pack to provide an entirely new front-end experience for BuddyPress, create brand new & interactive community features, or great BuddyPress blocks for the Block Editor.
The BP REST API can also serve as a strong replacement for the WordPress admin-ajax API. By using the BP REST API, you can more easily structure the way you want to get data into and out of BuddyPress. AJAX calls can be greatly simplified by using the BP REST API, enabling you to improve the performance of your custom features.
About authentification
Cookie authentication is the standard authentication method included with WordPress, the BP REST API utilizes it.
The REST API Nonce
The WordPress REST API includes a technique called nonces to avoid CSRF issues. This prevents other sites from forcing you to perform actions without explicitly intending to do so. This requires slightly special handling for the API.
The API uses nonces with the action set to wp_rest
. To generate it and pass it to your script you can use the wp_localize_script()
function.
<?php
// Using wp_localize_script()
function example_enqueue_script() {
wp_enqueue_script( 'my-script-handle', 'url-to/my-script.js', array( 'jquery' ) );
wp_localize_script( 'my-script-handle', 'bpRestApi', array(
'nonce' => wp_create_nonce( 'wp_rest' ),
) );
}
add_action( 'bp_enqueue_scripts', 'example_enqueue_script' );
Sending the nonce
For developers making their own Ajax requests, the nonce will need to be passed with each request. The recommended way to send the nonce value is in the request header. Below is an example using jQuery.
jQuery.ajax( {
url: '/wp-json/buddypress/v1/components',
beforeSend: function( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', bpRestApi.nonce );
},
success: function( data ) {
console.log( data )
}
} );
The WP API Request script as a dependency
We advise you to use the wp-api-request
JavaScript we’ve built to make sure to be compatible with our WordPress minimum required version: 4.7.0
.
That’s why, you’ll find into each endpoint of the Developer Endpoint Reference examples of use relying on this dependency.
To enjoy it, you simply need to include it as a dependency of your JavaScript when registering/enqueueing your script into WordPress. For example, our
example_enqueue_script()
function becomes:
<?php
// Using 'wp-api-request' as a dependency.
function example_enqueue_script() {
wp_enqueue_script( 'my-script-handle', 'url-to/my-script.js', array( 'wp-api-request' ) );
}
add_action( 'bp_enqueue_scripts', 'example_enqueue_script' );
Then into the
my-script.js
file we can directly use thewp.apiRequest()
function:
wp.apiRequest( {
path: 'buddypress/v1/components',
type: 'GET',
} ).done( function( data ) {
console.log( data );
} ).fail( function( error ) {
console.log( error );
} );
Extending the BP REST API
You can extend any of the data endpoint responses by registering custom REST fields using the bp_rest_register_field()
function.
Hooking to bp_rest_api_init
you first need to register your custom REST field.
In the below example code, you’ll notice the
get_callback
parameter, you need to use it to define the function to use to retrieve the value of your custom field and add it to the REST response. Additionally, to update the value of your custom field, you’ll need to code the function you defined as theupdate_callback
parameter you had used.
function example_register_activity_rest_field() {
bp_rest_register_field(
'activity', // Id of the BuddyPress component the REST field is about
'example_field', // Used into the REST response/request
array(
'get_callback' => 'example_get_rest_field_callback', // The function to use to get the value of the REST Field
'update_callback' => 'example_update_rest_field_callback', // The function to use to update the value of the REST Field
'schema' => array( // The example_field REST schema.
'description' => 'Example of Activity Meta Field',
'type' => 'string',
'context' => array( 'view', 'edit' ),
),
)
);
}
add_action( 'bp_rest_api_init', 'example_register_activity_rest_field' );
The function associated with the 'get_callback' parameter.
/**
* The function to use to get the value of the REST Field.
*
* param array $array The list of properties of the BuddyPress component's object.
* param string $attribute The REST Field key used into the REST response.
* return string The value of the REST Field to include into the REST response.
*/
function example_get_rest_field_callback( $array, $attribute ) {
// The key of the metadata can be different from the REST Field key.
$metadata_key = '_example_metadata_key';
return bp_activity_get_meta( $array['id'], $metadata_key );
}
The function associated with the 'update_callback' parameter.
/**
* The function to use to update the value of the REST Field.
*
* param object $object The BuddyPress component's object that was just created/updated during the request.
* (in this case the BP_Activity_Activity object).
* param string $attribute The REST Field key used into the REST response.
* return string $value The value of the REST Field to save.
*/
function example_update_rest_field_callback( $object, $value, $attribute ) {
// The key of the metadata can be different from the REST Field key.
$metadata_key = '_example_metadata_key';
bp_activity_update_meta( $object->id, $metadata_key, $value );
}
Reference
Just like the WordPress REST API, the BP REST API is organized around REST, and is designed to have predictable, resource-oriented URLs and to use HTTP response codes to indicate API errors. The API uses built-in HTTP features, like HTTP authentication and HTTP verbs, which can be understood by off-the-shelf HTTP clients, and supports cross-origin resource sharing to allow you to interact securely with the API from a client-side web application.
The BP REST API uses JSON exclusively as the request and response format, including error responses.
The BP REST API provides public data accessible to any client anonymously, as well as private data only available after authentication. Once authenticated the BP REST API supports most BuddyPress community actions, allowing you to enhance your plugins with more responsive management tools, or build complex single-page applications.
This API reference provides information on the specific endpoints available through the API, their parameters, and their response data format.
Developer Endpoint Reference
Resource | Base Route |
---|---|
Components | /buddypress/v1/components |
Members | /buddypress/v1/members |
Components Endpoint
BuddyPress chose a modular approach using components to organize its features. Two components are loaded by default (eg: BuddyPress Core and Community Members) while the majority are optionals. BuddyPress comes with 8 built-in optional components (Account Settings, Activity Streams, Extended Profiles, Friend connections, Notifications, Private messaging, User groups and Site Tracking).
Components Schema
The schema defines all the fields that exist for BuddyPress components.
Attribute | Type | Description |
---|---|---|
name | string |
Name of the component. Context: view , edit |
status | string |
Whether the component is active or inactive. Context: view , edit . One of: active , inactive |
title | string |
HTML title of the component. Context: view , edit |
description | string |
HTML description of the component. Context: view , edit |
List the BuddyPress components
Arguments - List Components
Attribute | Type | Description |
---|---|---|
context | string |
Scope under which the request is made; determines fields present in response. Default: view One of: view , edit |
page | integer |
Current page of the collection. Default: 1 |
per_page | integer |
Maximum number of components to be returned in result set. Default: 10 |
search | string |
Limit results to those matching a string. |
status | string |
Limit result set to components with a specific status. Default: all One of: all , active , inactive |
type | string |
Limit result set to components with a specific type. Default: all One of: all , optional , retired , required |
Definition - List Components
GET /buddypress/v1/components
Example - List Components
wp.apiRequest( {
path: 'buddypress/v1/components',
type: 'GET',
data: {
context: 'view'
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Activate/Deactivate a BuddyPress Component
Arguments - Activate/Deactivate Component
Name | Type | Description |
---|---|---|
name | string |
Name of the component. Required. |
action | string |
Whether to activate or deactivate the component. Required One of: activate , deactivate |
Definition - Activate/Deactivate Component
PUT /buddypress/v1/components
Example - Activate Component
wp.apiRequest( {
path: 'buddypress/v1/components',
type: 'PUT',
data: {
context: 'edit',
name: 'activity',
action: 'activate'
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Members Endpoint
The BuddyPress Members endpoint extends the WordPress Users one to include specific BuddyPress data such as profile fields data (1) and use the BP_User_Query
instead of the WP_User_Query
to fetch the members.
(1) If the Extend profiles component is active on the website.
Members Schema
The schema defines all the fields that exist for a member object.
Attribute | Type | Description |
---|---|---|
id | integer |
Unique identifier for the member. Read only Context: embed , view , edit |
name | string |
Display name for the member. Context: embed , view , edit |
mention_name | string |
The name used for that user in @-mentions. Context: embed , view , edit |
link | string , uri |
Profile URL of the member. Read only Context: embed , view , edit |
user_login | string |
An alphanumeric identifier for the member. Context: embed , view , edit |
member_types | array |
Member types associated with the member. See this documentation page for more information. Read only Context: embed , view , edit |
registered_date | string or null |
Registration date for the member. Read only Context: edit |
registered_date_gmt | string or null |
The date the member was registered, as GMT. Read only Context: edit |
password | string |
Password for the member (never included). Context: none |
roles | array |
Roles assigned to the member. Context: edit |
capabilities | object |
All capabilities assigned to the member. Read only Context: edit |
extra_capabilities | object |
All capabilities assigned to the member. Read only Context: edit |
xprofile (1) | array |
Member xProfile groups and its fields. Read only Context: view , edit |
friendship_status (2) | boolean |
Whether the logged in user has a friendship relationship with the fetched user. Read only Context: view , edit |
friendship_status_slug (2) | string |
Slug of the friendship relationship status the logged in user has with the fetched user. Read only One of: is_friend , not_friends , pending , awaiting_response Context: view , edit |
last_activity | object |
Last date the member was active on the site (object properties: timediff, date and date_gmt). Read only Context: view , edit |
latest_update (3) | object |
The content of the latest activity posted by the member (object properties: id, raw and rendered). Read only Context: view , edit |
total_friend_count (2) | integer |
Total number of friends for the member.. Read only Context: view , edit |
avatar_urls (4) | object |
Avatar URLs for the member (Full & Thumb sizes). Read only Context: embed , view , edit |
(2) Data is only fetched if the Friends component is active
(3) Data is only fetched if the Activity component is active
(4) Only if the WordPress discussion settings allow avatars.
List Members
Arguments - List Members
Attribute | Type | Description |
---|---|---|
context | string |
Scope under which the request is made; determines fields present in response. Default: view One of: view , embed , edit |
page | integer |
Current page of the collection. Default: 1 |
per_page | integer |
Maximum number of members to be returned in result set. Default: 10 |
search | string |
Limit results to those matching a string. |
exclude | array |
Ensure result set excludes specific IDs. Default: [] |
include | array |
Ensure result set include specific IDs. Default: [] |
type | string |
Shorthand for certain orderby/order combinations. Default: newest One of: active , newest , alphabetical , random , online , popular |
user_id | integer |
Limit results to friends of a user. Default: 0 |
user_ids | array |
Pass IDs of users to limit result set. Default: [] |
populate_extras | boolean |
Whether to fetch extra BP data about the returned members. Default: false |
member_type | array |
Limit results set to certain type(s). See this documentation page for more information. Default: [] |
xprofile | array |
Limit results set to a certain XProfile field. Default: [] |
Definition - List Members
GET /buddypress/v1/members
Example - List Members
wp.apiRequest( {
path: 'buddypress/v1/members',
type: 'GET',
data: {
context: 'view',
'xprofile': {
relation: 'AND',
args: [
{
field: 'Test field',
value: 'Hello world',
compare: '='
}
]
},
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Create a Member
Arguments - Create Member
Attribute | Type | Description |
---|---|---|
user_login | string |
An alphanumeric identifier for the member. Required |
password | string |
Password for the member. Required |
string |
The email address for the member. Required |
|
name | string |
Display name for the member. |
roles | array |
Roles assigned to the member. |
member_type | string |
A comma separated list of Member Types to set for the member. See this documentation page for more information. |
Definition - Create Member
POST /buddypress/v1/members
Example - Create Member
wp.apiRequest( {
path: 'buddypress/v1/members',
type: 'POST',
data: {
context: 'edit',
name: 'Test User',
user_login: 'testuser',
email: 'test@user.mail',
password: 'password' // Always use strong passwords, not like this one!
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Retrieve a Specific Member
Arguments - Retrieve Member
Attribute | Type | Description |
---|---|---|
id | integer |
Unique identifier for the member. |
context | string |
Scope under which the request is made; determines fields present in response. Default: view One of: view , embed ,edit |
populate_extras | boolean |
Whether to fetch extra BP data about the returned member. Default: false |
Definition - Retrieve Member
GET /buddypress/v1/members/<id>
Example - Retrieve Member
wp.apiRequest( {
path: 'buddypress/v1/members/2',
type: 'GET',
data: {
context: 'view'
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Update a Specific Member
Arguments - Update Member
Attribute | Type | Description |
---|---|---|
id | integer |
Unique identifier for the user. |
name | string |
Display name for the member. |
roles | array |
Roles assigned to the member. |
member_type | string |
A comma separated list of Member Types to set for the member. See this documentation page for more information. |
Definition - Update Member
PUT /buddypress/v1/members/<id>
Example - Update Member
wp.apiRequest( {
path: 'buddypress/v1/members/2',
type: 'PUT',
data: {
context: 'edit',
name: 'FirstName LastName',
roles: 'contributor'
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Delete a Specific Member
Arguments - Delete Member
Attribute | Type | Description |
---|---|---|
id | integer |
Unique identifier for the member. Required |
force | boolean |
Required to be true, as members do not support trashing. |
reassign | integer |
Reassign the deleted member’s posts and links to this user ID. Required |
Definition - Delete Member
DELETE /buddypress/v1/members/<id>
Example - Delete Member
wp.apiRequest( {
path: 'buddypress/v1/members/2',
type: 'DELETE',
data: {
context: 'edit',
force: true,
reassign: 1 // The User ID to reassign the deleted user's post to.
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Retrieve the Logged-in Member
Arguments - Retrieve Logged-in Member
Attribute | Type | Description |
---|---|---|
context | string |
Scope under which the request is made; determines fields present in response.>br> Default: view One of: view , embed , edit |
Definition - Retrieve Logged-in Member
GET /buddypress/v1/members/me
Example - Retrieve Logged-in Member
wp.apiRequest( {
path: 'buddypress/v1/members/me',
type: 'GET',
data: {
context: 'view'
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Update the Logged-in Member
Arguments - Update Logged-in Member
Attribute | Type | Description |
---|---|---|
name | string |
Display name for the member. |
roles (1) | array |
Roles assigned to the member. |
member_type | string |
A comma separated list of Member Types to set for the member. See this documentation page for more information. |
(1) To update roles, the logged in member must have the *promote_user*
capability.
Definition - Update Logged-in Member
PUT /buddypress/v1/members/me
Example - Update Logged-in Member
wp.apiRequest( {
path: 'buddypress/v1/members/me',
type: 'PUT',
data: {
context: 'edit',
name: 'FirstName LastName'
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Delete the Logged-in Member
Arguments - Delete Logged-in Member
Attribute | Type | Description |
---|---|---|
force | boolean |
True as users do not support trashing. Required |
reassign | integer |
Reassign the deleted member’s posts and links to this user ID. Required |
Definition - Delete Logged-in Member
DELETE /buddypress/v1/members/me
Example - Delete Logged-in Member
wp.apiRequest( {
path: 'buddypress/v1/members/me',
type: 'DELETE',
data: {
context: 'edit',
force: true,
reassign: 1 // The User ID to reassign the deleted user's post to.
}
} ).done( function( data ) {
return data;
} ).fail( function( error ) {
return error;
} );
Errors
The Kittn API uses the following error codes:
Error Code | Meaning |
---|---|
400 | Bad Request -- Your request is invalid. |
401 | Unauthorized -- Your API key is wrong. |
403 | Forbidden -- The kitten requested is hidden for administrators only. |
404 | Not Found -- The specified kitten could not be found. |
405 | Method Not Allowed -- You tried to access a kitten with an invalid method. |
406 | Not Acceptable -- You requested a format that isn't json. |
410 | Gone -- The kitten requested has been removed from our servers. |
418 | I'm a teapot. |
429 | Too Many Requests -- You're requesting too many kittens! Slow down! |
500 | Internal Server Error -- We had a problem with our server. Try again later. |
503 | Service Unavailable -- We're temporarily offline for maintenance. Please try again later. |