WordPress REST API What It Is And How To Use It

 

WordPress REST API What It Is And How To Use It

 

There is lot of excitement around the forthcoming REST API for WordPress, back in pre version , WordPress initiated custom post types after that this can be the biggest turning point in the journey of creating WordPress a right application framework.

In short, the REST API provides a chance for developers to completely separate the front-end and the core WordPress package. This will lead to provide an ability to develop a decent mobile apps, It offers highly customized themes and expectantly best implementations we haven’t even got an idea of yet.

In this article, we will see how to get started with the REST API and few companies already using it successfully so lets see.

A rapid note: This article is for developers with a solid knowledge of PHP and WordPress we expect you are the one.

Let’s Begin With the WP REST API

At first, you’ll require the REST API Plugin to begin with as well as you require the latest version of WordPress. You’ll also need to have some knowledge of the WordPress HTTP API to make calls.

As our first project, let’s make a local WordPress installation, which will be able to pull posts from our live site using the REST API. First of all, Make sure you have the REST API plugin installed on the live site then build an empty widget plugin on your local website. Below you will discover the amazing code I used, to begin with:

/**

* Plugin Name: REST API Test Widget

* Plugin URI: http://outsource2global.com

* Description: This plugin joins a widget that pulls posts through the REST API

* Version: 1.0.0

* Author: outsource2global

* Author URI: http://outsource2global.com

* License: GPL2

*/

class My_Author_List_Widget extends WP_Widget {

public function __construct() {

$widget_details = array(

‘classname’ => ‘rest-api-test-widget’,

‘description’ => ‘A REST API test widget which pulls posts from a different website’

);

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’ );

});

This code is held within a rest-API-test-widget folder in the plugins directory, in a file named rest-API-test-widget.php. This holds the plugin header, that is used when listing the plugin in the admin and a tiny bit more than the bare minimum for building a decent widget.

If you aren’t familiar with building widgets don’t worry, we have an article on building WordPress widgets like a pro. In this article, we’ll mainly concentrate on the widget() function, which rules the output of the widget.

We are going to use the WordPress HTTP API to make requests and read responses from the WordPress API. If you’re just a beginner to HTTP just take a look at our guide on using the HTTP API.

Gripping Some Posts

Just as with any REST API, we will require a couple of stuffs to make each request. We all require to know the following:

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

/wp-json/wp/v2/ is the base path of the API. All routes we will explain will be relatable to this path. So our full base URL would be mywebsite.com -&nbspmywebsite Resources and Information.. The route for getting posts will be /posts so the full route URL will be mywebsite.com -&nbspmywebsite Resources and Information..

Each route can also have a number of endpoints which makes them different from the HTTP method. The route to a single article might be something like this /posts/325. This route has three endpoints:

  • GET will retrieve the post
  • PUT will update the post
  • DELETE will delete the post

For instance, we will be using the mywebsite.com -&nbspThis website is for sale! -&nbspmywebsite Resources and Information. route with the GET endpoint to retrieve posts. This is a simple code, implementing HTTP API

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

get-posts.php hosted with ❤ by GitHub

view raw

In this scenario, the response is approvable if it’s not a WP_Error object & if it returns a few posts. The complete data is returned in the body of the response which you can seize using the wp_remote_retrieve_body() function. The body will contain a JSON encoded string with the post data. Following is the complete code for showing them in our widget.

Code:

public function widget( $args, $instance ) {

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

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’];

}

This looks like the most simple example and yes it is, but the potential it holds is fantastic. If we restore the HTTP API functions with cURL or something else, our example is particularly WordPress-agnostic. We could be laboring with Laravel, Joomla or a mobile application. The fact that we are displaying posts from WordPress in other one WordPress system is entire coincidence.

This implies that we could build a mobile app for your WooCommerce store that is entirely iPhone/Android native. And also engages with your WordPress site accurately, including functions like taking orders, getting payments, and managing shipments. It will transform WordPress into an app platform that will be creating all our websites that much better.

 

 

Bringing off More with the REST API

This simple example displays us that 90% of how you execute with the WP API. Following are 3 more things that it is really important looking into a nutshell:

  1. Caching responses
  2. Authentication
  3. Discovering more to do

Caching Responses

It doesn’t work to continuously trouble servers with calls when they aren’t required. In the instance above we have shown a list of posts which perhaps won’t vary within seconds so caching this response for an hour, perhaps even a day, would be a great notion.

There are many ways to solve this, including JP REST API CACHE that is a composer library, caching plugins as well as utilizing native transients. We will look at a quick transient’s instance here.

The notion of a transient is like it keeps data with an expiration date. By default, data will move into the database but some setups let storage in memory which builds it more quickly. When you retrieve the posts you need to put those posts in a transient and then fix the expiration to an hour. Until the expiration time comes those posts are restored from our own database. After the expiration of time, they are restored or retrieved from the external website once again and then put into the transient.

Here is how we would revise the widget function (building an additional function in the whole process).

Code:

public function get_remote_posts() {

$posts = get_transient( ‘remote_posts’ );

if( empty( $posts ) ) {

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

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’];

}

cached-posts.php hosted with ❤ by GitHub

Expand Codeview raw

Authentication

The procedure shown above should work even if there is no authentication but authenticate yourself always. Please check the Authentication section in the documentation for more information regarding it. You will have two alternatives which are basic authentication and OAuth when you work with external requests.

Basic authentication is the easiest one but should never be utilized in production as it is not safe; basic authentication needs you to convey your real username and password with each request. It is a great procedure for testing purpose though so we will show you how to actually get it up and running.

Basic Authentication

To allow the basic authentication, you require to install a plugin on the aimed website. Once this plugin has been activated you will be able to do authenticated calls.

To begin with you require to set an authorization header with this value Basic <Base64 encoded username:password>. Let’s suppose your username is mrcool and your password is coolpass you could make this header & authenticate a call like so:

Code.

$headers = array (

‘Authorization’ => ‘Basic ‘ . base64_encode( ‘mrcool:coolpass’ ),

);

$response = wp_remote_request( ‘http://mysite.com/wp-json/wp/v2/…‘, array(

‘method’ => ‘DELETE’,

‘headers’ => $headers

));

view raw

Be attentive, if you utilize your own website URL and are appropriately authenticated this will remove the post with the ID of 1183! As we can look, manipulating data is super easy with the API, this is really a fun to work with.

OAuth Authentication

This process of authentication also needs us to install a plugin. When this API will get combined into core this plugin will be involved. So you won’t require to bother about many separate plugins. Unluckily at this minute, the documentation for OAuth is a trouble so we won’t be able to display you how to get this done.

It includes installing using WP-CLI (a command line interface for WordPress), installing a community extension for it and the WP Client CLI as well as utilizing those two together. This should not really create a difficulty, but a command listed isn’t available & it is creating our lives tougher than it should be.

Once easy-to-use guidelines are available we will announce back on how to work on this. For this moment, we can use the basic authentication.

Discovering More To Do

We highly put up reading the Discovery page of the documentation. You will discover all the procedures that authorize you to intercommunicate with users, media, post types, as well as metadata and everything else you require.

A module of learning any API is making you well known with all attributes and alternatives and the WordPress API is no anomaly. You’ will discover some peculiarities like not being able to remove users as well as other minor difficulties, but keep in mind that this is still work in betterment & this is forming a shape up gracefully.

Companies Using The REST API Right Now

Even as the REST API is emerging from its infancy there are many companies who already using it.

Here is a list of just some of them testing the waters:

  • Event Espresso is a famous event management plugin is utilizing it to gain access to its data
  • Human Made is successfully using it to develop client websites when the client needs something more adaptable in the front-end.
  • Editus is a premium plugin using it to give potential to their front-end editing abilities.
  • WP Search Live It is a free plugin – utilizes it to give potential to their search functionality
  • JoinIn is utilizing it for powering up an embeddable JS widget
  • Modern Tribe is also utilizing this to give more potential to both Handlebars and full-page React templates in their themes.
  • Simmer – This tool is utilizing this to make their own developer APIs and to support others create cookbooks into their mobile apps that they can effortlessly sell.
  • According to Who’s using this thing? post on Make WordPress a lot of people are using the API to make mobile apps for their websites.

Where Do You Find Yourself?

Are you currently utilizing the WP REST API? We gonna appreciate to hear how you are utilizing it or strategy to utilize it.

What do you think about the amazing chances it offers? Do you actually look it as the future for the WordPress community or is it just a passing fad as per your perspective?

 

Leave a Reply

Your email address will not be published. Required fields are marked *