Complete Guide to Rest API for WordPress

The REST API is playing a vital role in making the WordPress more powerful and compelling web development framework. It has already created a lot of buzz around the web world and is slowly and steadily becoming a robust tool to develop fully-fledged websites, mobile applications, and highly-customized themes.

In a simple term, the REST API enables developers to decouple the front-end of a WordPress site. This helps them add more advanced functionalities to the core of WordPress package for the better implementation of the framework.

In fact, most of the reputed business owners are using REST API for their WordPress sites to make the most of this CMS platform and its rich features. It helps developers to build user-friendly sites, which in turn,  encourages companies to generate quality traffic and higher sales for their web business.  However, most of the people don’t have complete information about the REST API.

If you are one of those, then this blog post will help you. We bring you the complete guide to rest API for your WordPress site.  But before diving into the main concept, it is important to tell you that this blog post is for those developers who have comprehensive knowledge of WordPress and PHP.

Let’s get started!

How to Get Started with WordPress REST API?

To make the most of REST API make sure you meet the following two requirements:

Besides this, you must have basic knowledge of the WP HTTP API. This will help you make calls easily.

So, if you want to use the Rest API, you will need to install the plugin on the live site and also create an empty widget plugin on your local site. Using the following lines of code, you can get started with it:

/**

 * Plugin Name: REST API Test Widget

 * Plugin URI: http://forexample.com

 * Description: Adding a widget to fetch pulls posts using the REST API

 * Version: 1.0.0

 * Author: XYZ

 * Author URI: http://forexample.com

 * License: GPL2

 */

class My_Author_List_Widget extends WP_Widget {
 
    	public function __construct() {
            	$widget_details = array(
                    	'classname' => 'rest-api-test-widget',
                    	'description' => 'Adding a widget to fetch pulls posts using the REST API'
            	);
 
            	parent::__construct( 'rest-api-test-widget', 'REST API Test Widget', $widget_details );
 
    	}
 
    	public function form( $instance ) {
    	$title = ( !empty( $instance['title'] ) ) ? $instance['title'] : '';
    	?>
 
    	<p>
        	<label for="<?php echo $this->get_field_name( 'title' ); ?>">Title: </label>
        	<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
    	</p>
 
    	<?php
    	}
 
 
    	public function widget( $args, $instance ) {
    	echo $args['before_widget'];
 
    	if( !empty( $instance['title'] ) ) {
            	echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) . $args['after_title'];
    	}
 
    	// Main Widget Code Here
 
    	echo $args['after_widget'];
 
    	}
 
}
 
add_action( 'widgets_init', function(){
 	register_widget( 'My_Author_List_Widget' );
});

Note: You can find this code in a rest-api-test-widget folder, available in the plugins directory. It is saved in a file known as rest-api-test-widget.php. It includes the plugin header that is used to list the plugin in the admin to create a widget.

If you are a novice WordPress developer, you may find difficulties in creating widgets for your site. But you don’t need to worry because we will explore more about the widget() function to let you create WordPress widgets with ease.

Apart from this, we will also use the WordPress HTTP API to make calls and read responses from the WP API. So, tighten your seat belts and start the journey of using REST API for your WordPress site.

How to make Requests with the Rest API?

If you want to make requests and receive the responses using Rest API, you need to consider the following things:

  • The endpoint used
  • The route used
  • Parameters
  • The base path of the API
  • Headers required

The API’s base path remains the ‘/wp-json/wp/v2/”, and all the routes mentioned above will be relevant to this path. It means the full base URL would be something like this:

http://forexample.cpm/wp-json/wp/v2/

And the route for generating posts is /posts/. The full route URL would be something like this:

http://forexample.com/wp-json/wp.v2/posts/

Since each route has multiple endpoints, classified by the HTTP method. The route to the single post would look like /posts/224. And, this route has four endpoints:

  • POST – to create the post
  • PUT – to update the post
  • GET – to retrieve the post
  • DELETE – to delete the post

You can access the data object (resource) of your WordPress site through the HTTP request. With the help of WP REST API, you can do this in a quick and easy way. And if you are using the latest version of WordPress APO (version 2), then you should be aware of 9 different WordPress objects, including:

  • Pages
  • Posts
  • Post meta
  • Comments
  • Media
  • Post revisions
  • Users
  • Taxonomies and
  • Terms

These elements help you create a fully-fledged WordPress site and you can access it via HTTP REST API. You can even CREATE, PUT, UPDATE, RETRIEVE, or DELETE  any of the WordPress site’s resources mentioned above using WP API.

For an example, If you are using the http://forexample.com/wp-json/wp/v2/posts/ route with the GET endpoint, then you will need to add the following piece of a line using HTTP API to retrieve your posts:

$response = wp_remote_get( ‘http://mysite.com/wp-json/wp/v2/posts/’ );

Now, the data will be returned in the body of the response and you can collect it using the wp_remote_retrieve_body() function. Below is the full code that will help you showcase post data in your widget:

public function widget( $args, $instance ) {
    	$response = wp_remote_get( 'http://forexample.com/wp-json/wp/v2/posts/' );
 
    	if( is_wp_error( $response ) ) {
            	return;
    	}
 
    	$posts = json_decode( wp_remote_retrieve_body( $response ) );
 
    	if( empty( $posts ) ) {
            	return;
    	}
    	 
	echo $args['before_widget'];
 
    	if( !empty( $instance['title'] ) ) {
            	echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) . $args['after_title'];
    	}
 
 
    	if( !empty( $posts ) ) {
            	echo '<ul>';
            	foreach( $posts as $post ) {
                    	echo '<li><a href="' . $post->link. '">' . $post->title->rendered . '</a></li>';
            	}
            	echo '</ul>';
    	}
 
    	echo $args['after_widget'];
 
}

How to make the most of the REST API?

The above example and coding clearly show that how you can perform the CREATE, GET, UPDATE, RETRIEVE, and DELETE actions with any of your WordPress objects using WP API. In this particular section, we will explore more about the use of REST API depending on the three important aspects:

1. Caching Responses

However, the example mentioned above in the previous section is amazing, but it won’t change in seconds. For that, you will need to cache the response for an hour using REST API.

Fortunately, there are multiple ways to cache your resources, including, using a composer library (JP REST API CACHE), WordPress caching plugins and of course, using native transients, which is one of the best ways. We will show you how transients work using an example.

Transient is used to store WordPress data, along with an expiration date. It will, by default, move to the database but making some setup modifications can store it in the memory to make it work faster.

While retrieving the posts, you can add them in a transient and don’t forget to set the expiration to an hour. Before meeting the expiration time, the posts are retrieved from the WordPress database. But once after the expiration, they are retrieved from the external site and added into the transient.

With the help of following code base, we will explain you this in a better way:

public function get_remote_posts() {
    	$posts = get_transient( 'remote_posts' );
    	if( empty( $posts ) ) {
            	$response = wp_remote_get( 'http://forexample.com/wp-json/wp/v2/posts/' );
            	if( is_wp_error( $response ) ) {
                    	return array();
            	}
 
            	$posts = json_decode( wp_remote_retrieve_body( $response ) );
 
            	if( empty( $posts ) ) {
                    	return array();
            	}
 
            	set_transient( 'remote_posts', $posts, HOUR_IN_SECONDS );
    	}
 
    	return $posts;
}
 
 
public function widget( $args, $instance ) {
    	$posts = $this->get_remote_posts();
 
    	if( empty( $posts ) ) {
            	return;
    	}
    	 
	echo $args['before_widget'];
 
    	if( !empty( $instance['title'] ) ) {
            	echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'], $instance, $this->id_base ) . $args['after_title'];
    	}
 
    	echo '<ul>';
    	foreach( $posts as $post ) {
            	echo '<li><a href="' . $post->link. '">' . $post->title->rendered . '</a></li>';
    	}
    	echo '</ul>';
 
    	echo $args['after_widget'];
 
}

2. The Concept of Authentication

When it comes to the WordPress REST API, then you must know that some HTTP requests don’t need authentication. For example, GET requests like getting posts don’t require authentication. But other GET requests do need authentication, such as getting users, getting revisions, and getting post meta data. Plus, all POST, PUT and DELETE actions need authentication. They won’t perform without the authentication process.

To an addition, when you perform on site actions such as installing themes and plugins to the site, these are managed by cookies. But, if you are doing it off site, authentication is handled by OAuth.

For that, you will need to download the OAuth plugin to your site to lead the external site through the basic OAuth flow process to get access. You can also use the Basic Authentication plugin for the same task.

3. Explore more about WordPress REST API

If you are looking for the resources to discover more about the usage of WordPress REST API, then you should read the Developer Resource page of the documentation. There, you will find all the relevant methods that help you know how to interact with WordPress data objects such as users, media, meta data, post types and a lot more.

Being a WordPress developer, you should always be aware of the fact that learning or discovering more about APIs means you are enhancing your skills and boosting the capabilities of developing more powerful sites, mobile apps and themes for WordPress.

Conclusion

In this blog post, we tried to elaborate the entire usage, capabilities, and benefits of WordPress REST API. If you have some great tips related to this topic, feel free to share them below in the comment box.

Author Bio

Lucy Barret is currently working for a Website to WordPress Migration Company and handling all major projects. She is a talented blogger and loves to write technical content on numerous topics. Feel free to follow her on Twitter

1 Response

  1. important information thanks for sharing