R.P.TECHNOLOGY PVT LTD
R.P.Technology PVT LTD -Digital marketing company in India, India offers best digital marketing services like SEO, PPC, SMO, ORM, design/development. & business rapidly. Call @ 8308958903
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.
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.
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:
However, I will start this tutorial with some theoretical discussion on the definition of 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.
The WordPress REST API offers several options for authentication, each intended for a specific purpose.
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 refers to the basic type of HTTP authentication in which login credentials are sent along with the request’s headers.
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.
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.
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:
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.
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:
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.
Use the Web Hosting Savings Calculator for FREE to instantly find out the ideal host that fits your requirements best.
Consider the following DELETE request sent through jQuery.ajax() method:
Where Base64 is an object used for encoding and decoding a base64 string, this is defined as follows, just above jQuery.ajax() method call:
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:
The above request, when completed, will echo out the response in the browser’s console.
The 200 status response code returned by the server shows that the post with the id of 52 has been deleted successfully.
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:
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:
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.
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.
Here is an example of editing the title of a post using jQuery AJAX:
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.
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.
When using the WordPress REST API, you’ll see the same terms popping up over and over again, which include:
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.
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.
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.
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.
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 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.
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!
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:
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.
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:
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.
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:
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.
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.
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!
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 […]
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). […]