WordPress REST API: The Next-generation CMS Feature
For a while, WordPress seemed to had fallen behind. As the web became more reliant on JavaScript to create immersive, interactive experiences, it became increasingly clear that WordPress needed to offer new ways for users and developers to interact with its content.
In this post, Toptal Freelance Developer Brian Coords explores the amazing new features of WordPress’s REST API, showing why WordPress is still on the cutting edge of web development.
For a while, WordPress seemed to had fallen behind. As the web became more reliant on JavaScript to create immersive, interactive experiences, it became increasingly clear that WordPress needed to offer new ways for users and developers to interact with its content.
In this post, Toptal Freelance Developer Brian Coords explores the amazing new features of WordPress’s REST API, showing why WordPress is still on the cutting edge of web development.
Brian loves solving problems with WordPress. In his previous career, he was a high school and college English teacher.
Expertise
PREVIOUSLY AT
More than a quarter of the web runs on WordPress. It’s a pretty remarkable feat, considering it’s been around for more than a decade, which makes it fairly old in tech years.
What’s WordPress’s secret sauce? Easy – it’s the simplest yet most extensible way to manage your content. However, for a while, WordPress seemed to have fallen behind.
As the web has become more reliant on JavaScript to create immersive, interactive experiences, it became increasingly clear that WordPress would need to offer new ways for users and developers to interact with their content.
While WordPress is built on – and will continue to be built on – PHP, the WP REST API is an attempt to create a bridge between the legacy of the PHP WordPress core and the potential and power of JavaScript web applications, as well as native mobile and desktop applications.
The WordPress REST API brings the content of any WordPress website into an easily-consumed API, allowing WordPress to serve as a storage and retrieval system for publishing content on the web.
Bringing REST to the WordPress API
If you think the WordPress REST API popped up out of nowhere, you’re wrong.
Adding a completely new feature to WordPress is no simple task. By nature of being open-source software, WordPress development is dependent on the community at large to make progress.
Development for the API started a few years ago as a separate feature plugin, which allowed developers to experiment with, and contribute to, the project in a controlled environment.
Throughout many iterations and enhancements, and two completely separate versions, the contributors behind the REST API had to test and evaluate the benefits, and immense consequences, of providing open API access to the data on tens of millions of websites.
WordPress 4.4, codename “Clifford,” brought the initial infrastructure of the project into WordPress core, while the endpoints did not appear until WordPress 4.7, “Vaughan.”
Essentially, this allowed the developers time to test out the functionality that powers the API without actually exposing the data itself.
Now that the initial content endpoints have been merged into all current versions of WordPress, plugin developers and theme authors can experiment with exciting new ways to retrieve, view, and change the data outside of the traditional wp-admin experience.
Breaking Apart the Abbreviations: From HTTP to a JSON REST API
To understand the significance of the WP REST API, it may help to understand the foundation of how we share data online and where the Internet might be headed.
HTTP is the foundation for most web traffic we deal with daily. If you type a URL into a browser, you’re making a request. The corresponding server receives your request and provides a response. This transaction is the basis for nearly everything we do online. Browsers make requests, and servers provide responses.
The type of request we make can affect the type of response we get. Most of the time, we’re making a simple GET request: “Hey Google, GET me your landing page.” Google provides a response.
As the web became more interactive, we began to take advantage of other HTTP requests, including PUT, POST, and DELETE.
For example, we fill out a search bar on a website: “Hey Google, POST my email address and password into your login page.” Google begins a new session for us and provides a different response.
This protocol is the basic foundation we build our WordPress sites on.
We use forms and PHP to GET and POST data into our database. Contrary to popular opinion, this underlying foundation of WordPress is not going to change anytime soon. All that WordPress is doing now is providing developers a new way to interact with their WordPress data via a RESTful API.
Representational State Transfer (REST)
WordPress developers should be familiar with APIs in general, such as the Shortcode API and the Options API. These APIs define the functionality for the components that comprise WordPress, so theme and plugin authors can expand on WordPress’ core capabilities. The WordPress REST API, however, is a little different.
A REST, or RESTful, API is about securely exposing your data to HTTP requests from external sources. It’s also about setting up a common architecture and set of protocols for responding to those requests. While there are more advanced ideas and principles behind this type of service, those are beyond the scope of this article.
The existence of the WP REST API, specifically after WordPress 4.7, means that all of your site’s content, including posts, pages, comments, and any public post meta, is now directly accessible as raw data. It also means that you can make changes to this data from outside of the tradition wp-admin if you’d like, perhaps through a mobile or desktop app.
Instead of thinking of your data as simply rows in a database, you can now have serialized access to it in the form of JSON.
JSON - What happened to XML?
WordPress vets have a lot of experience with XML, a common format for sharing content between sites.
Similar to XML, JSON is simply a mechanism that allows us to easily transfer data by bundling it into a specific syntax. JSON is actually a string, a textual representation of a JavaScript object, storing your data in a set of key-value pairs. A common JSON representation of a WordPress post may look like this:
{
“id”: 1,
“title”: {
“rendered”: “Hello World”
},
“content”: {
“rendered”: “Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!”
}
}
(You can use a JSON formatter tool to prettify the JSON response if necessary.)
A full JSON response via the WP REST API will include additional information about the post, including metadata. By conveniently bundling this data into the JSON format, you can interact with your WordPress content in new and exciting ways.
It’s no coincidence that JSON is best paired with JavaScript. As more WordPress developers begin to “Learn JavaScript Deeply”, we’ll be seeing more and more advanced uses of WordPress as a backend.
How We Find the Data: Follow the Route to a WordPress API Endpoint
With WordPress, to fetch data from its API is as simple as composing a URL.
For any WordPress site running at least version 4.7, add the following string to the end of your site’s url: /wp-json/wp/v2
(e.g., http://example.com/wp-json/wp/v2
). Put that URL in your browser, and see what comes up.
The result probably looks like a big mess of data, unless you’ve installed a browser extension that cleans up JSON. That big mess of data is the content and meta information of your particular WordPress site in JSON format.
By loading that content, you’ve just defined a route and asked your browser to GET it for you.
A route is a URL that’s mapped to a specific method. WordPress core reads that route, with every slash ‘/’ representing a particular path, or parameter, that should be followed.
The path concludes at an endpoint, where functions deep inside of WordPress core can make decisions about what data to provide and what to do with any data that was provided.
An example endpoint may be ‘/wp-json/wp/v2/posts/1’, where we’ve added the paths ‘/posts’ and ‘/1’. This particular endpoint tells our site to go through our data, pull up our posts, and pull up the post with the ID of 1.
What makes the REST API in WordPress so useful is the fact that it is extensible, meaning that you can take any data within your website, and add it as an endpoint. Most of the core WordPress functionality currently is (or soon will be) supported.
However, theme and plugin developers can start adding their custom content and settings as endpoints, allowing users to interact with their websites in new ways.
If you’re curious about the endpoints currently available on your WordPress site, a browser application like Postman provides a GUI specifically for exploring APIs.
Headers and Authentication
Typing URL endpoints into the browser appears simple, but it actually includes a set of default headers along with the request. In turn, a set of headers are also sent back with the response. These headers include a lot of useful information, but the most important ones for our purposes have to do with the type of request we are making and whether or not we are authenticated.
If you jump into your browser’s “developer tools,” you can examine the HTTP headers for any asset that is loaded into the browser window, including HTML files, CSS stylesheets, images, and more.
The first header to consider is the Request Method, which corresponds directly to those HTTP requests we learned about earlier. Here you’ll most likely see GET
as the request method, if we are simply viewing a page.
An application calling your REST API may choose to change the header’s Request Method to POST.
A POST method tells your website to enter new data or change existing data in your WordPress database. By sending information through the POST method, other applications have the ability alter your data, without logging into wp-admin.
No need to worry, however, because unless they’ve also included headers that provide the proper credentials for authentication, your website will deny them.
NOTE: The methods for authenticating calls to your REST API are still not finalized, though, which makes authentication the largest barrier to entry for developers wanting to work with the REST API to add or change data.
For now, there are options available, including a plugin from the developers behind REST API. As the standard procedures surrounding authentication make their way into core, the last hurdles will be clear for widespread use of the WP REST API.
WordPress REST API Example Application
What makes the WP REST API so powerful is the fact that it’s consistent, so we can expect the same basic results from any site running WordPress 4.7 or higher. However, WordPress is a distributed API, meaning there isn’t just one place to get all the data from.
Each website running WordPress is a unique application, with unique users and authentication. While it may require distinct authorization techniques to edit content through the REST API, we can actually access the posts of most WordPress-run blogs pretty easily.
To demonstrate, we’ll make a quick codepen demo that loads excerpts of the latest posts from some popular WordPress-related blogs which, of course, all run on WordPress. While we’re at it, we’ll include a search form, so we can actually search all of these sites at once, and pull up the relevant articles from each.
Finally, we’ll be sure to include the link to read the full article text on the original website.
Phase 1: Getting Recent Posts
We’ll start by setting up a quick Vue instance and mounting it to an element. We’ll also include Bootstrap so we can have a grid and basic styling on the form elements we’ll be adding later on.
When we define the data, we’ll want a place to store the name of the site (which isn’t included in the default response), the URL, and the posts once we get them. Here’s an example:
{
“name”: “wordpress.org”,
“url”: “https://wordpress.org/news/wp-json/wp/v2/posts?per_page=3”,
“posts”: []
}
You’ll notice that we also included our first parameter to the end of the URL, per_page
. Typically, the WP REST API will paginate the results following the same rules as it would paginate a normal WP_Query loop. We’ll limit our queries to the first three posts.
Next, we’ll define the method loadPosts()
, which will loop through our list of sources, get the results with vue-resource, and populate the empty posts
array of each source with the results.
loadPosts : function(){
var self = this;
self.sources.forEach(function(source, index){
self.$delete(source, 'posts');
// Get API with vue-resource
self.$http.get(source.url).then(function(response) {
self.$set(source, 'posts', response.data);
}, function(response) {
console.log('Error');
});
});
}
We’ll also include a initial call to loadPosts()
when our Vue instance is successfully mounted.
mounted : function(){
this.$nextTick(function(){
// Load posts on initial page load
this.loadPosts();
});
}
Keeping loadPosts()
as a separate method will come in handy in the future as we begin to make multiple calls to the API. In our HTML, we’ll be using Vue’s simple list rendering directives and template syntax to output all of our posts.
See the embedded Pen for a working demo:
See the Pen WP REST API Search Example (Phase One) by Brian Coords (@bacoords) on CodePen.
Phase 2: Filtering Results
Let’s add a sidebar, and create some filters to show/hide the various sources. To do this, we add a new property to the sources
object, a boolean we’ll name on.
While we’re adding filters, let’s generate a Vue filter to help us display the date properly as well. WordPress stores the date and time of the post as a Unix timestamp.
We’ll use the third-party library Moment.js to convert the date to a more readable format.
filters: {
// Using Moment.js to convert post date to a readable format
prettyDate: function(value){
// Return if date is empty
if(!value) return '';
// Convert date to Moment.js
var date = moment.utc(value);
// Return formatted date
return date.format("MMM DD, YYYY,");
}
},
See the embedded pen for a working demo:
See the Pen WP REST API Search Example (Phase One) by Brian Coords (@bacoords) on CodePen.
Final Phase: Search Queries
Here we’ll add a new parameter to our API request. Already, we’ve added the per_page=3
parameter to limit the number of results we get from each site. If there’s anything written in the search bar, we’ll add it in as an additional parameter.
This will allow us to use each site’s built-in search functionality, just as if we were querying the search bar on that website.
We’ll add a search bar, and tie it to a variable using Vue’s v-model directive.
Rather than immediately call all of the APIs, when the user starts typing, we’ll add a button and bind an event to the form submission. Then we’ll add a method to our Vue instance that adds the search parameters (URL encoded, of course) to the URL.
generateUrl : function(source){
var self = this;
// Add search parameters.
if(self.searchQuery){
return source.url + '&search=' + encodeURI(self.searchQuery);
}else{
return source.url;
}
}
See the embedded pen for a working demo:
See the Pen WP REST API Search Example (Phase One) by Brian Coords (@bacoords) on CodePen.
While this is a simple example of the WordPress REST API, we could imagine a potential application for something like this within WordPress itself. For example, there’s already the ‘WordPress News’ metabox.
We could easily transform this demo into a WordPress plugin, displaying it on the WordPress dashboard. Now we’ve integrated the ability to search for help from some of the top WordPress and web design tutorial sites right from our own website.
Future Potential of the WordPress REST API
Although the example above only scratches the surface of the WP REST API’s capabilities, it should convey some of the possibilities that begin to emerge when you start to play with the data. Whether it’s used to enhance the user experience on the website itself, or to collect and manipulate the data from an external source, it’s a powerful tool.
While some industry experts have voiced concerns about the possibility of having your content ‘scraped’ and displayed elsewhere, it’s important to remember that this functionality is similar to RSS feeds, and it’s vital for site maintainers to have clear control of what data is and is not public.
As the WP REST API becomes more ingrained into the fabric of WordPress, we’ll begin to see it’s effects, perhaps without even realizing it. Examples have ranged from simple (Chris Coyier’s Quotes on Design), to complex, single page applications (Guggenheim site).
Another popular use case for the WP REST API is mobile application development.
Because content is so accessible through the REST API, developers can create native apps for iOS and Android, and avoid having to create duplicate data sources.
As users interact with these mobile apps, they will be able to retrieve, and directly transform the original website’s data, without the developer having to create any complex infrastructure to support this.
These visitor-facing applications of the REST API are only the beginning, however, as the real implications are much deeper. One of the goals for the core development team is to begin using it throughout the wp-admin interface.
With future WordPress updates, we’ll begin to see admin-ajax replaced in favor of the API, hopefully increasing the speed of basic functions, like editing menus or publishing posts.
This could potentially go hand-in-hand with WordPress’ increased focus on the Customizer and the Editor as the user-friendly starting points for WordPress newbies.
While the WP REST API is tremendously useful as is, there’s still more to be done. The API is not complete. There are still more features and endpoints to add.
Eventually, you’ll be able to interact with your WordPress site without even visiting it. And while many services now use custom APIs to interact with WordPress, the move to one standard WordPress REST API means that more sites and services can interconnect, speaking the same language.
WordPress started as blogging platform, a way for bloggers to connect, and share their thoughts and ideas. With the development of the WordPress REST API, we’ll start to see a new level of connecting and sharing behind the scenes. This will allow users to build on their thoughts and ideas in ways never previously considered, taking WordPress and its users to entirely new frontiers.
Brian Coords
Aliso Viejo, CA, United States
Member since November 28, 2016
About the author
Brian loves solving problems with WordPress. In his previous career, he was a high school and college English teacher.
Expertise
PREVIOUSLY AT