How to Use the WordPress REST API (and the Companies Already Using it Successfully)

There is a lot of buzz around the upcoming REST API for WordPress, and rightly so! After the introduction of custom post types way back in version 2.9, this may be the biggest step toward making WordPress a true application framework.

In a nutshell, the REST API it allows developers to completely de-couple the front-end from the core WordPress package. This will lead to better mobile apps, highly customized themes and – hopefully – clever implementations we haven’t even thought of yet.

In this article, I’ll show you how to get started with the REST API and some companies already using it successfully.

A quick note: this article is aimed at developers with a solid understanding of PHP and WordPress.

Getting Started With the WP REST API

Right now, you’ll need the REST API Plugin to get started and the latest version of WordPress. You’ll also need some knowledge of the WordPress HTTP API to make calls.

As our first project for this tutorial, let’s create a local WordPress installation, which will pull posts from our live site using the REST API. Make sure you have the REST API plugin installed on the live site and create an empty widget plugin on your local site. Here’s the boilerplate code I used to get started:

This code is contained within a rest-api-test-widget folder in the plugins directory, in a file named rest-api-test-widget.php. It contains the plugin header, which is used when listing the plugin in the admin and a tiny bit more than the bare minimum for creating a widget.

If you aren’t familiar with creating widgets fear not, we have an article on building WordPress widgets like a pro. In this article, we’ll mostly focus on the widget() function, which governs the output of the widget.

We’ll also be using the WordPress HTTP API to make requests and read responses from the WordPress API. If you’re new to HTTP, take a look at our handy guide on using the HTTP API.

Grabbing Some Posts

Just as with any REST API, we’ll need a couple of things to make each request. We need to know the following:

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

The base path of the API is always /wp-json/wp/v2/. All routes I’ll describe will be relative to this path. So the full base URL would be http://mywebsite.com/wp-json/wp/v2/. The route for getting posts is /posts so the full route URL is http://mywebsite.com/wp-json/wp/v2/posts/.

Each route can have a number of endpoints which are differentiated by the HTTP method. The route to a single article might be something like /posts/325. This route has three endpoints:

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

For our example, we’ll be using the http://mywebsite.com/wp-json/wp/v2/posts/ route with the GET endpoint to retrieve posts. Using the HTTP API, this is a simple line of code.

In our case, the response is favorable if it is not a WP_Error object and if it returns some posts. The data is returned in the body of the response which we can grab using the wp_remote_retrieve_body() function. The body will contain a JSON encoded string with post data. Here’s the full code for displaying them in our widget.

This seems like a simplistic example – and it is – but the potential it holds is amazing. If you replace the HTTP API functions with cURL or something else, our example is basically WordPress-agnostic. We could be working in Laravel, Joomla or a mobile application. The fact that we’re displaying posts from WordPress in another WordPress system is pure coincidence.

This means that you could create a mobile app for your WooCommerce store which is completely iPhone/Android native, yet interacts with your WordPress site perfectly, including taking orders, managing shipments and receiving payments. It turns WordPress into an app platform which should make all our websites that much better.

Doing More With the REST API

This basic example shows 90% of how you work with the WP API. There are three more things that it is worth looking into briefly:

  • Caching responses
  • Authentication
  • Discovering more to do

Caching Responses

It doesn’t do to continuously bother servers with calls when they aren’t needed. In our example above we’ve displayed a list of posts which probably won’t change within seconds. Caching this response for an hour, maybe even a day, would be a good idea.

There are a number of approaches to solve this, including JP REST API CACHE which is a composer library, caching plugins and using native transients. I’ll show you a quick transients example here.

The idea of a transient is that it stores data with an expiration date. By default it will go into the database but some setups allow storage in memory which makes it even faster. When we retrieve the posts we want to put them in a transient and set the expiration to an hour. Until the expiration time arrives the posts are retrieved from our own database. After expiration they are retrieved from the external site once again and put into the transient.

Here’s how I would modify the widget function (creating an additional function in the process).

Authentication

The method above should work without authentication but you should always authenticate yourself. Take a look at the Authentication section in the documentation for more info. When working with external requests like this you have two options: basic authentication and OAuth.

Basic authentication is the simplest but should never be used in production as it is quite unsafe, it requires you to send your actual username and password with each request. It is a good method for testing though so I’ll show you how to get it up and running.

Basic Authentication

To enable basic authentication, you need to install a plugin on the target site. Once this has been activated you’ll be able to make authenticated calls.

To get started you need to set an authorization header with the value Basic <Base64 encoded username:password>. Assuming your username is mrawesome and your password is awesomepass you could create this header and authenticate a call like so:

Take care, if you use your own website URL and are properly authenticated this will delete the post with the ID of 1183! As you can see, manipulating data is extremely simple with the API, it really is a joy to work with.

OAuth Authentication

This method of authentication also requires you to install a plugin. Once the API is merged into core this plugin will be included so you won’t need to worry about multiple separate plugins. Unfortunately at the moment the documentation for OAuth is a mess so I won’t be able to show you how to get this done right now.

It involves installing using WP-CLI a command line interface for WordPress, installing a community extension for it, the WP Client CLI and using those two together. This would not really pose a problem, but a command listed isn’t available and it is making our lives harder than it needs to be.

Once easy-to-use instructions are available I’ll report back on how to do this. For now, we can stick to testing the waters with the basic authentication.

Discovering More To Do

I highly recommend reading the Discovery page of the documentation and just browsing around in general. You’ll find all the methods that allow you to interact with users, post types, media, meta data and everything else you might need.

A part of learning any API is familiarizing yourself with all the options and the WordPress API is no exception. You’ll find some quirks like not being able to delete users and other minor issues, but keep in mind that this is still work in progress and is shaping up beautifully.

Companies Using The REST API Right Now

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

Here’s a list of just some of them testing the waters:

  • Event Espresso, a popular event management plugin is using it to provide access to its data
  • Human Made is using it to create client sites when the client wants something more flexible in the front-end.
  • A premium plugin called Editus is using it to power it’s front-end editing capabilities
  • WP Search Live – a free plugin – uses it to power its search functionality
  • JoinIn is using it to power an embeddable JS widget
  • Modern Tribe is using it to power both Handlebars and full page React templates in their themes
  • Simmer – a recipe publishing tool – is using it to build their own developer APIs and to help others make cookbooks into mobile apps that they can easily sell.
  • According to the Who’s using this thing? post on Make WordPress a lot of people are using the API to create mobile apps for their websites.

Where Do You Fit In?

Are you using the WP REST API? We’d love to hear how you are using it, or plan to use it.

What do you think about the opportunities it provides? Do you see it as the way forward for the WordPress community or is it just a passing fad?

Let us know your thoughts on the REST API in the comments below.