Build Your Own REST API on WordPress in 3 Minutes

In this article, we will learn how to build a REST API on WordPress.

Registration

In order to build our API, we first need to register it with WordPress by using  rest_api_init hook which fires when the API request is coming.

add_action( 'rest_api_init', 'regsiter_api', 10 );

Inside the register_api function, we will register the routes and implement the logic for each of them.

Implementation

Our API’s design includes one resource that is “options” and it has two methods GET and POST. We need to use a register_rest_route function to register a new REST API route.

First, we register the GET method to return the plugin options.

register_rest_route( 'plugin-slug/v1', '/options', array(
'methods' => 'POST',
'callback' => 'get_options',
) );

Inside the get_aws_options function, we use the get_options method to fetch our saved options in the WordPress database.

function get_options() {
return get_option( PLUGIN_CONSTANTS::PLUGIN_OPTION_NAME );
}

Great! Let’s make some test by using curl to make a GET request to our API.

Please note, the WordPress REST API must begin with “wp-json” prefix.

curl http://localhost:8888/wp-json/plugin-slug/v1/options
false

As you can see the response returns false because we haven’t saved any options to the WordPress database.

Next, we will add a POST method to create our plugin’s options.

register_rest_route( 'plugin-slug/v1', '/options', array(
'methods' => 'POST',
'callback' => array( $this, 'add_option' ),
) );

add_option function will receive the HTTP Post data from the request including a JSON object with two keys key1 and key2.

function add_option( $data ) {
$option      = array(
'key1' => $data['key1'],
'key2' => $data['key2'],
);
$option_json = wp_json_encode( $option );
$result      = update_option( PLUGIN_CONSTANTS::PLUGIN_OPTION_NAME, $option_json );
return $result;
}

In the above snippet, we create a $option array variable that contains the data from the request. We then encode it in JSON format, which helps store the values into the database easier.

It’s a piece of cake, isn’t?

Let’s do some test.

curl -H "Content-Type: application/json" \
-d '{"key1":"value1", "key2": "value2"}' \
-X POST http://localhost:8888/wp-json/plugin-slug/v1/options
true

We need to make sure that our options are already created by making a GET request to our API. Before that, we need to improve our get_options function by decoding the data received from the database.

function get_options() {
$options = get_option( SSU_CONSTANTS::AWS_OPTION_NAME );
return json_decode( $options );
}

Perfect! Now again we make a GET request by curl to our API.

curl http://localhost:8888/wp-json/plugin-slug/v1/aws-options
{"key1":"value1", "key2": "value2"}

Hope you can learn something from this tutorial and use it to build your own REST API for your next WordPress projects and plugins. Happy coding!