More than a quarter of the web runs on WordPress. It’s quite an achievement when you consider it’s been around for more than a decade, making it rather old in the technology world.
What is the key to WordPress’s success? It’s simple: it offers the easiest yet most adaptable method for managing your content. However, WordPress seemed to lag behind for a period.
As the web has grown more dependent on JavaScript for creating rich, interactive experiences, it became evident that WordPress needed to provide 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 initiative aimed at bridging the gap between the legacy of the PHP WordPress core and the capabilities and strength of JavaScript web applications, as well as native applications for mobile and desktop devices.
The WordPress REST API makes the content of any WordPress website accessible through an easy-to-use API, allowing WordPress to function as a content storage and retrieval system for online publishing.
Integrating REST into the WordPress API
The WordPress REST API didn’t just magically appear.
Incorporating a brand new feature into WordPress is a complex undertaking. Because it is open-source software, WordPress development relies heavily on the contributions of its community.
The API’s development began several years ago as a standalone plugin, providing a controlled setting for developers to experiment with and contribute to the project.
Over numerous iterations, enhancements, and two distinct versions, the REST API contributors had to rigorously test and assess the benefits and significant implications of granting open API access to data residing on tens of millions of websites.
WordPress 4.4, codenamed “Clifford,” incorporated the project’s initial framework into WordPress core, while the endpoints didn’t appear until WordPress 4.7, “Vaughan.”
Essentially, this approach allowed the developers to thoroughly test the functionality underpinning the API without actually exposing the data itself.
With the initial content endpoints now integrated into all current WordPress versions, plugin and theme developers can explore innovative ways to retrieve, display, and modify data beyond the conventional wp-admin interface.
Deconstructing the Acronyms: From HTTP to a JSON REST API
To fully grasp the significance of the WP REST API, it’s helpful to understand the fundamentals of online data sharing and the potential trajectory of the Internet.
HTTP forms the bedrock of most web traffic we encounter daily. Typing a URL into a browser initiates a request. The corresponding server processes the request and delivers a response. This transaction underpins almost everything we do online. Browsers make requests, and servers provide responses.
The nature of our request can influence the type of response we receive. Most often, we make straightforward GET requests: “Hey Google, GET me your landing page.” Google responds accordingly.
As the web became increasingly interactive, we started utilizing other HTTP requests, such as PUT, POST, and DELETE.
For instance, when we fill in a search bar on a website: “Hey Google, POST my email address and password to your login page,” Google initiates a new session for us and provides a different response.
This protocol forms the fundamental basis upon which we build WordPress sites.
We employ forms and PHP to GET and POST data into our database. Contrary to popular opinion, this underlying foundation of WordPress isn’t going away anytime soon. WordPress is simply offering developers a novel way to interact with their WordPress data through a RESTful API.
Representational State Transfer (REST)
WordPress developers are generally familiar with APIs, such as the Shortcode API and the Options API. These APIs define the functionality for WordPress components, enabling theme and plugin authors to extend WordPress’ core capabilities. However, the WordPress REST API stands apart.
A REST, or RESTful, API is designed for securely exposing your data to HTTP requests originating from external sources. It also establishes a standard architecture and set of protocols for handling these requests. While there are more intricate concepts and principles behind this type of service, they fall outside the scope of this article.
The presence of the WP REST API, particularly after WordPress 4.7, signifies that all of your site’s content – posts, pages, comments, and any public post meta – is now directly accessible as raw data. This also means you can modify this data from outside the traditional wp-admin environment, potentially through a mobile or desktop app.
Instead of viewing your data merely as rows in a database, you can now access it serially in the form of JSON.
JSON - What Happened to XML?
Seasoned WordPress users have extensive experience with XML, a prevalent format for content sharing between sites.
Like XML, JSON is simply a mechanism that facilitates easy data transfer by packaging it into a specific syntax. JSON is essentially a string, a textual representation of a JavaScript object, storing your data in key-value pairs. A typical JSON representation of a WordPress post might look like this:
| |
(You can use a JSON formatter tool to make the JSON response more readable if needed.)
A complete JSON response from the WP REST API will include additional information about the post, including metadata. By conveniently packaging this data in JSON format, you can interact with your WordPress content in new and exciting ways.
It’s not a coincidence that JSON pairs well with JavaScript. As more WordPress developers embrace “Learn JavaScript Deeply”, we’ll witness increasingly sophisticated uses of WordPress as a backend system.
How to Locate the Data: Follow the Route to a WordPress API Endpoint
Retrieving data from the WordPress API is as simple as constructing a URL.
For any WordPress site running version 4.7 or higher, append the following string to the end of your site’s URL: /wp-json/wp/v2 (e.g., http://example.com/wp-json/wp/v2). Enter that URL into your browser and observe the output.
The result might appear as a jumbled mess of data unless you have a browser extension installed to format the JSON. That seemingly chaotic data represents the content and meta information of your WordPress site in JSON format.
By loading that content, you’ve defined a route and instructed your browser to GET it.
A route is a URL mapped to a specific method. WordPress core interprets that route, with each slash ‘/’ representing a particular path or parameter to follow.
The path culminates in an endpoint, where functions within WordPress core determine what data to provide and how to handle any received data.
An example endpoint could be ‘/wp-json/wp/v2/posts/1’, where we’ve added the paths ‘/posts’ and ‘/1’. This endpoint instructs our site to navigate through the data, retrieve the posts, and specifically fetch the post with the ID of 1.
The extensibility of the WordPress REST API is what makes it so valuable. You can take any data within your website and expose it as an endpoint. Most core WordPress functionality is either already supported or will be soon.
Furthermore, theme and plugin developers can begin adding their custom content and settings as endpoints, enabling users to interact with their websites in novel ways.
If you’re curious about the endpoints currently available on your WordPress site, browser applications like Postman provide a graphical interface specifically for exploring APIs.
Headers and Authentication
Typing URL endpoints into the browser seems simple, but it implicitly sends a set of default headers with the request. Likewise, a set of headers is returned with the response. These headers contain valuable information, but the most critical ones for our purposes pertain to the type of request being made and whether or not we are authenticated.
By accessing your browser’s “developer tools,” you can examine the HTTP headers for any asset 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 the HTTP requests we discussed earlier. You’ll likely see GET as the request method if you are simply viewing a page.
An application communicating with your REST API might choose to change the header’s Request Method to POST.
A POST method instructs your website to add new data or modify existing data in your WordPress database. By transmitting information through the POST method, other applications can alter your data without needing to log in to wp-admin.
Rest assured, though, because unless these requests also include headers providing valid authentication credentials, your website will reject them.
NOTE: The methods for authenticating calls to your REST API are still under development, making authentication the most significant obstacle for developers wanting to use the REST API to add or modify data.
Currently, options exist, including a plugin from the developers of the REST API. As standard authentication procedures are integrated into core, the final barriers to widespread adoption of the WP REST API will be cleared.
WordPress REST API Example Application
The consistency of the WP REST API is a key strength, ensuring we can expect similar results from any site running WordPress 4.7 or higher. However, WordPress operates as a distributed API, meaning there isn’t a single source for all data.
Each website powered by WordPress is a distinct application with unique users and authentication mechanisms. While editing content through the REST API might require specific authorization techniques, we can actually access the posts of most WordPress-run blogs fairly easily.
To illustrate this, we’ll create a quick CodePen demo that loads excerpts from the latest posts of some popular WordPress-related blogs, all of which naturally run on WordPress. Additionally, we’ll incorporate a search form to enable simultaneous searching across all these sites, retrieving relevant articles from each.
Finally, we’ll make sure to include links to read the full articles on their respective websites.
Phase 1: Retrieving Recent Posts
We’ll start by setting up a basic Vue instance and mounting it to an element. We’ll also include Bootstrap for grid layout and basic styling of the form elements we’ll add later.
When defining the data, we need a place to store the site name (not included in the default response), the URL, and the posts once we retrieve them. Here’s an example:
| |
Notice that we’ve already added our first parameter to the URL, per_page. The WP REST API will typically paginate results using the same rules as a regular WP_Query loop. We’ll limit our queries to the first three posts.
Next, we’ll define the method loadPosts(), which will iterate through our list of sources, fetch the results using vue-resource, and populate each source’s empty posts array with the data.
| |
We’ll also call loadPosts() initially when our Vue instance is successfully mounted.
| |
Keeping loadPosts() as a separate method will prove useful as we start making multiple API calls. In our HTML, we’ll use Vue’s straightforward list rendering directives and template syntax to display all our posts.
See the embedded Pen for a working demo:
Phase 2: Filtering Results
Let’s add a sidebar and create filters to show or hide specific sources. To achieve this, we’ll add a new property to the sources object, a boolean named on.
While we’re adding filters, let’s create a Vue filter to format the date properly. WordPress stores the post’s date and time as a Unix timestamp.
We’ll use the third-party library Moment.js to convert the date into a more readable format.
| |
See the embedded pen for a working demo:
Final Phase: Search Queries
Now, we’ll introduce a new parameter to our API request. We’ve already added the per_page=3 parameter to restrict the number of results per site. If the search bar contains any text, we’ll include it as an additional parameter.
This allows us to leverage each site’s built-in search functionality, just like performing a querying the search bar directly on that website.
We’ll add a search bar and bind it to a variable using Vue’s v-model directive.
Instead of immediately calling all 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 appends the search parameters (URL encoded, of course) to the URL.
| |
See the embedded pen for a working demo:
This example demonstrates a simple use case for the WordPress REST API, but imagine its potential within WordPress itself. For instance, consider the existing ‘WordPress News’ metabox.
We could easily transform this demo into a WordPress plugin and display it on the WordPress dashboard. Now, we’ve integrated the ability to search for help from leading WordPress and web design tutorial sites directly within our own website.
Future Potential of the WordPress REST API
This example merely scratches the surface of the WP REST API’s capabilities. It hints at the possibilities that emerge when you start manipulating data. Whether used to enhance the user experience on the website itself or to gather and process data from an external source, it’s a potent tool.
While some industry experts have expressed concerns about the potential for content “scraping” and unauthorized display, it’s crucial to remember that this functionality is similar to RSS feeds. Site administrators must retain clear control over what data is publicly accessible.
As the WP REST API becomes more deeply embedded within WordPress, we’ll begin to see its effects, perhaps even unknowingly. Examples have ranged from straightforward implementations (Chris Coyier’s Quotes on Design) to complex, single-page applications (Guggenheim site).
Mobile application development is another popular use case for the WP REST API.
The REST API’s accessibility makes it easy for developers to create native iOS and Android apps without having to establish separate data sources.
When users interact with these mobile apps, they can retrieve and directly modify the original website’s data, eliminating the need for developers to build complex infrastructure for support.
However, these visitor-facing applications represent just the beginning. The true implications of the REST API run much deeper. One goal of the core development team is to integrate it throughout the wp-admin interface.
Future WordPress updates will likely see admin-ajax replaced in favor of the API, potentially improving the speed of basic functions like editing menus and publishing posts.
This transition could go hand-in-hand with WordPress’s increased focus on the Customizer and the Editor as user-friendly entry points for new WordPress users.
While the WP REST API is incredibly useful in its current state, there’s still work to be done. The API isn’t complete, and more features and endpoints are yet to come.
Eventually, you’ll be able to interact with your WordPress site without even visiting it directly. And while many services currently rely on custom APIs to communicate with WordPress, the move towards a unified WordPress REST API means greater interconnectivity between sites and services, all speaking the same language.
WordPress began as a blogging platform, a place for bloggers to connect and share their thoughts and ideas. With the development of the WordPress REST API, we’re witnessing a new level of connection and sharing behind the scenes. This will empower users to build upon their thoughts and ideas in ways never before imagined, propelling WordPress and its users to uncharted territories.