How To Use The WordPress REST API Plugin
December 5, 2022 2 Comments Development Solutions, HOME Rameshwar Lokhande

How To Use The WordPress REST API Plugin An Application Programming Interface (API) (sometimes called the WP JSON REST API)  is a type of software that enables two applications to work with each other by exchanging information. There are several types of APIs you can use, including Representational State Transfer (REST) options. A REST API is basically software that enables two applications to exchange data using a specific set of constraints.

How To Use The WordPress REST API Plugin

In particular, the WordPress REST API enables you to connect your WordPress website with external applications. This means you can develop a mobile app using practically any programming language, and use the WP REST API to fetch data from WordPress. How To Use The WordPress REST API Plugin In a way, the REST API offers a way to free yourself from WordPress’ inherent structure, while harnessing it to help you create an application.

How the WordPress REST API Works

In the past, you needed a WordPress plugin in order to access the WordPress JSON REST API. However, since Version 4.4, this WordPress API became a part of the core software. As such, to use the REST API, you simply need to know how to interact with it, which boils down to using four different types of HTTP methods as part of your requests:

  • GETWith this method, you can fetch information from the server.
  • POSTThis enables you to send information to the server in question.
  • PUTWith the put method, you can edit and update existing data.
  • DELETEThis enables you to delete information.

How To Set up and Use WordPress REST API: Basic Authentication

However, I will start this tutorial with some theoretical discussion on the definition of authentication.

What Is Authentication?

In the context of Information and Communications Technology (ICT), authentication is the idea and process of verifying the credentials of the person or entity that asks for access to a particular system.

It is essential to understand that authentication is different from authorization. When a person is authenticated on a particular WordPress web Hosting server, they are granted general level access to the system. In contrast, when a person is authorized, they can access and utilize part or complete resources of the system. In other words, authentication confirms the identity while authorization identifies and grants access to the system’s resources.

In the particular context of WordPress REST API, an authenticated user can carry out CRUD tasks. However, the user must prove their authentication privileges at every step.

As an example, consider what happens when you visit your WordPress login page. How To Use The WordPress REST API Plugin Your browser sends a GET request to the server, which processes it using its own API. Once the page loads, you enter your credentials and send them through a POST request. If you want to change your password, it involves the PUT method, whereas deleting your account altogether would use DELETE.

We’ll show you examples of how to use these methods with the WordPress REST API in a minute. For now, let’s go over some other concepts you’ll need to understand first.

Authentication With the WordPress REST API

The WordPress REST API offers several options for authentication, each intended for a specific purpose.

  • Basic Authentication
  • OAuth Authentication
  • Cookie Authentication

The native WordPress authentication manner for users and their activities is currently verified by cookies.

To use OAuth authentication and Basic Authentication with WordPress REST API, you must install the particular plugins available on the GitHub WordPress REST API group. I hope that these two methods will receive native support in the subsequent versions of WordPress REST API.

Basic Authentication

Basic authentication refers to the basic type of HTTP authentication in which login credentials are sent along with the request’s headers.

How Does Basic Authentication Work?

In Basic Authentication, the client requests a URL that requires verification. The server, in turn, requests the client to identify itself by sending a 401 Not Authorized code. In reply, the client sends the same request with the credentials (in the username:password pair) appended as a base64 encoded string. This string is sent in the Authorization header field like the following:

Authorization: Basic b3dhaXMuYWxhbUBjbG91ZHdheXMuY29tOmVKNWtuU24zNVc=

Since base64 strings could be decoded without much effort, this authentication method is not very secure. Thus, these methods should only be used in scenarios where there is absolute trust between the server and the client. Another important application of this method is troubleshooting within a secure system.

Install WordPress REST API Plugin

WordPress REST API plugin allows you to add Basic Authentication to a WordPress site.

Note: “This plugin requires sending your username and password with every request and should only be used over SSL-secured connections or for local development and testing. Without SSL, we strongly recommend using the OAuth 1.0a authentication handler in production environments.”

WordPress REST API plugin is available from the GitHub WordPress REST API group. To utilize the plugin, clone it in the WordPress Plugin directory and activate it through the WordPress admin.

Send Authenticated Requests Using Postman

To start sending authentication requests, install the Postman Chrome Extension. It makes API development easier, faster, smarter, and better. For Firefox users, install  REST Easy Add-On that provides a full-featured REST client in the browser.

Postman for Chrome supports natively sending requests using the basic authentication method like most HTTP clients.

To send an authenticated request, go to the Authorization tab below the address bar:

Authenticated Request

 

Now select Basic Auth from the drop-down menu. You will be asked to enter your username and password. Next, click the Update request button.

Basic Auth

After updating the authentication option, you will see a change in the Headers tab. The tab will now include a header field for encoded username/password string:

Update Authentication

The setup for basic authentication with Postman is now complete. Now, send a test request (try deleting a post) which requires authentication:

For Example – DELETE http://wordpressmu-19393-42425-140587.cloudwaysapps.com/wp-json/wp/v2/posts/50

Where wordpressmu-19393-42425-140587.cloudwaysapps.com can be replaced with the path of your development server.

The server will return a 200 OK status if everything goes well. The status indicates that the post with the id 50 has been deleted.

OK Status

Sure Your Hosting Provider Isn’t Charging Extra?

Use the Web Hosting Savings Calculator for FREE to instantly find out the ideal host that fits your requirements best.

Send Authenticated Requests Using JavaScript

JavaScript is a high-level interpreted programming language, and that’s why these days, JavaScript can be found almost everywhere. Thus, it is very common to see popular JavaScript frameworks interacting with WordPress. A popular scenario is the usage of jQuery interacting with the WordPress API. In such cases, authorization headers could send in an AJAX request.

Consider the following DELETE request sent through jQuery.ajax() method:

  1. jQuery.ajax({
  2. url: ‘http://wordpressmu-19393-42425-140587.cloudwaysapps.com/wp-json/wp/v2/posts/50’,
  3. method: ‘DELETE’,
  4. crossDomain: true,
  5. beforeSend: function ( xhr ) {
  6. xhr.setRequestHeader( ‘Authorization’, ‘Basic ‘ + Base64.encode( ‘username:password’ ) );
  7. },
  8. success: function( data, txtStatus, xhr ) {
  9. console.log( data );
  10. console.log( xhr.status );
  11. }
  12. });

Where Base64 is an object used for encoding and decoding a base64 string, this is defined as follows, just above  jQuery.ajax() method call:

  1. var Base64={_keyStr:“ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=”,encode:function(e){var t=“”;var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t=“”;var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,“”);while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,“\n”);var t=“”;for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t=“”;var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};

In the above request, I have set the Authorization header using the setRequestHeader() for the xhr object passed as an argument to the beforeSend() method.

In addition to the above request, the Access-Control-Allow-Headers headers should allow the Authorization field on the server. This can be enabled by adding the following line to the WordPress .htaccess file:

  1. Header always set Access-Control-Allow-Headers Authorization Header always set

The above request, when completed, will echo out the response in the browser’s console.

200 Notification

The 200 status response code returned by the server shows that the post with the id of 52 has been deleted successfully.

Send Authenticated Requests Using WordPress HTTP API

On the off chance that you are connecting remotely with another WordPress website, the most suitable approach is to send HTTP requests through the WordPress HTTP API.

Consider the following code that sends a DELETE request to another WordPress installation with WordPress REST API and basic authentication enabled:

  1. $wp_request_headers = array(
  2. ‘Authorization’ => ‘Basic ‘ . base64_encode( ‘username:password’ )
  3. );
  4. $wp_request_url = ‘http://wordpressmu-19393-42425-140587.cloudwaysapps.com/wordpress-api/wp-json/wp/v2/posts/50’;
  5. $wp_delete_post_response = wp_remote_request(
  6. $wp_request_url,
  7. array(
  8. ‘method’ => ‘DELETE’,
  9. ‘headers’ => $wp_request_headers
  10. )
  11. );
  12. echo wp_remote_retrieve_response_code( $wp_delete_post_response ) . ‘ ‘ . wp_remote_retrieve_response_message( $wp_delete_post_response );

Here, I have used  wp_remote_request() that accepts two arguments; $url (the URL of the request) and $args (the array that contains additional arguments to be passed).

The $method defined in the $args array is DELETE. The $headers array contains all the header fields to be passed with the request. I have passed the authorization key with a base64 encoded username and password key string.

The response would be saved in the $wp_delete_post_response variable, which could be used with the wp_remote_retrieve_response_code() and wp_remote_retrieve_response_message() functions. These two functions are helper functions in the WordPress HTTP API, and they extract the status code and the status message from the response respectively.

If the post is deleted successfully through the above request, the following text will be echoed out:

200 OK

Cookie authentication is the basic authentication method available in  WordPress. The correct cookies are set up once there is a successful login to the WordPress dashboard. Thus, the developers only have to log in for authentication.

However, the REST API incorporates nonces to deal with CSRF issues. This ensures that all activities on the website remain segregated. However, this also requires careful handling of the API.

For developers utilizing the worked as part of Javascript API, this is naturally taken care of. This is the prescribed approach to use the API for plugins and themes. Custom data models can stretch out wp.api.models.Base to guarantee this is sent correctly for any custom requests.

Developers making manual AJAX calls must pass nonce with every request. The API utilizes nonces with the activity set to wp_rest. These can then be given to the API through the _wpnonce data parameter (either POST data or the query for GET requests) or the X-WP-Nonce header.

Note: Until recently, many software had sketchy support for DELETE requests. For instance, PHP does not transform the request body of a DELETE request into a superglobal. Supplying the nonce as a header is the most reliable approach in this scenario.

It is important to remember that this confirmation strategy depends on WordPress cookies. Thus, this method is only relevant when the REST API is utilized within WordPress and the current user is logged in. Moreover, the current user must have appropriate authorization for the activity being performed.

As an example, this is how the built-in JavaScript client creates nonce:

  1. wp_localize_script( ‘wp-api’, ‘wpApiSettings’, array( ‘root’ => esc_url_raw( rest_url() ), ‘nonce’ => wp_create_nonce( ‘wp_rest’ ) ) );

Here is an example of editing the title of a post using jQuery AJAX:

  1. $.ajax( {
  2. url: wpApiSettings.root + ‘wp/v2/posts/50’,
  3. method: ‘POST’,
  4. beforeSend: function ( xhr ) {
  5. xhr.setRequestHeader( ‘X-WP-Nonce’, wpApiSettings.nonce );
  6. },
  7. data:{
  8. ‘title’ : ‘Hello Cloudways’
  9. }
  10. } ).done( function ( response ) {
  11. console.log( response );
  12. } );

Final Thoughts

WordPress REST API is perhaps the most popular and extensively used REST API globally. It is available to everyone who uses WordPress for online stores and web apps.

I hope you have understood whatever I have written in this article. If you still have a question about the topic or would like to contribute to the discussion, please leave a comment below.

Getting Familiar With the WordPress REST API

To really understand how the WordPress REST API works, there are a few tips and concepts you need to familiarize yourself with. When we get to real examples shortly, you’ll see how everything works in practice.

REST API Concepts and Terms

When using the WordPress REST API, you’ll see the same terms popping up over and over again, which include:

  • ‘Routes’ and ‘endpoints’: A route is a URL you enter to make a request, whereas an endpoint is the combination of a URL with an HTTP method.
  • Requests: When you submit an endpoint, you’re making a request to the server.
  • Responses: If your endpoint is structured in the right way, you’ll get a response including the information you want in JavaScript Object Notation (JSON), or an error.
  • Schemas: Every response you get follows similar structures, which are governed by built-in schemas.
  • Controller classes: You can use these to build your own routes and endpoints, but this falls under more advanced WordPress REST API uses.

REST API Endpoints

In most cases, you’ll use routes and endpoints that already exist to submit requests via the WordPress REST API. Knowing what these endpoints are is the first step to mastering the WP API and using it to develop your own projects.

REST API Authentication

As you might expect, WordPress won’t let you access certain WordPress data unless it can corroborate who you are, and whether you’re requesting it via a browser or the REST API. For example, if you want to update or publish a post via commands, you’ll need to learn the basics of authentication.

WordPress REST API Use Examples

The REST API is being put to practical use on a number of major websites already. To give you some ideas for features you could implement, let’s look at a few REST API WordPress examples.

USA Today

How To Use The WordPress REST API Plugin
How To Use The WordPress REST API Plugin

The USA Today site was rebuilt using the WordPress REST API, in order to facilitate integrations with other sites and third-party services. This enables it to easily push content to services such as Facebook and Apple News.

WordPress.com

How To Use The WordPress REST API Plugin
How To Use The WordPress REST API Plugin

Naturally, the WordPress.com site makes heavy use of the WP API. In this case it’s on the back end, with admin pages that are built entirely using the API.

The New York Times

How To Use The WordPress REST API Plugin
How To Use The WordPress REST API Plugin

The New York Times leverages the WP REST API to run a live blog, where journalists can add important news developments in real-time. They’re even able to post to the blog directly from Slack thanks to the API, which enables a more seamless workflow.

How to Start Using the WordPress REST API (In 3 Steps)

We’ve gone over a lot of theory so far, so it’s time to move on to a WordPress endpoint tutorial. For this section, we’ll show you how to access the REST API, get back a list of specific data, and add new information using an endpoint. Let’s get to work!

Step 1: Access the REST API

You can ‘access’ the WordPress REST API from any application that can submit HTTP endpoints. For example, if you enter the following command within your favorite browser, you’ll get back a list of your WordPress posts in JSON format:

GET yourwebsiteurl.com/wp-json/wp/v2/posts

However, you’ll need to replace the placeholder URL with that of your own website. You’ll also need to use a version of WordPress greater than 4.4 for a REST API request to work (which you already should be doing).

If you want to really experiment with the REST API, though, a browser isn’t the best tool to do so. Instead, we recommend that you use the command line, which provides a more flexible approach.

Step 2: Fetch a Specific Post Using the REST API

The last command you ran should have returned a list of all your WordPress posts, including their post IDs. To fetch a specific post using its ID, you’d use an endpoint such as this:

GET yourwebsiteurl.com/wp-json/wp/v2/posts/535

For example, this would be ideal for showcasing a specific WordPress post translated within a mobile application. How To Use The WordPress REST API Plugin  However, the WordPress REST API enables you to fetch all kinds of data from WordPress, so its practical applications are incredibly flexible.

However, let’s say you wanted to use the REST API to add metadata to a chosen post instead of merely fetching it. In other words, you’ll be using the POST method instead of GET.

Step 3: Add Metadata to a Specific Post

Assuming that you’ve already authenticated yourself, you can add new data to any of your posts using a similar request to that presented in the last section, using POST instead of GET:

POST yourwebsiteurl.com/wp-json/wp/v2/posts/535/meta?value=NE metadata

For example, if you want to add metadata you could use to create a rich snippet for a recipe, the request may look like this:

POST yourwebsiteurl.com/wp-json/wp/v2/posts/535/meta?cookingtime=25

Depending on how much metadata you want to add, you might want to specify it using JSON objects instead, which offers a much more structured approach. In any case, once you’re familiar with what the most common endpoints are and how to put them to use, a whole world of possibilities opens up.

Add Endpoints to WordPress

The WordPress REST API supports custom routes and endpoints. How To Use The WordPress REST API Plugin These are useful if you want to create a second WordPress site and add integrations between the two.

Routes in the REST API also support unlimited endpoints. You can specify HTTP methods, callback functions, and permissions, as well as default values and several other parameters for each endpoint.

Begin Building the WordPress Website That You Envision

The WordPress REST API has been around for a few years now. If you’ve never used it before, there’s a lot you need to learn to get to the point where you can use it to develop advanced applications.

At WP Engine, we offer you all the resources you need to help you learn as much as possible about WordPress development in general, WordPress REST API, and how to use it. While this guide offers a basic introduction, you’d also do well to read our Ultimate WordPress REST API e-book, as well as our guide for non-developers!

Tags
About The Author
Rameshwar Lokhande R.P.TECHNOLOGY is a web development company india Oner Is Mr. Rameshwar Lokhande th the solution of generating the maximum Return with powerfull digital marketing solutions and with experience of developing, designing and marketing businesses in different industries & online marketing services in india. We also offer SEO services in Maharashtra which helps suitable traffic to your website. We not only Push and promote your website for the top search engines, but we also offer our monthly social media marketing. This will help your website in all the top main social media plateforms and link local listings on the Internet. we strongly provide services such as Google Adwords, social media marketing, Search Engine Optimization. 01.Our team lives and breathes for Digital Marketing. 02. We are digital conversion specialists 03. We can help take a huge step towards growing your company..
Leave Comment
  1. 1

    Why Choose WP Engine For WordPress Managed Hosting

    […] WP Engine only offers one type of service – its managed WordPress hosting – it also provides a number of tiered plans to choose from. These plans differ dramatically in […]

  2. 1

    What Is A Framework In Programming & Why You Should Use One 2023

    […] What is Angular? Angular is an open-source web application framework based on TypeScript and maintained by the Angular Team at Google. Angular features a large ecosystem of tools and solutions contributed by a wide user base. Angular is ideally suited for highly customized web apps and progressive web apps (PWAs). […]

Leave a reply

%d bloggers like this: