close

Day 10: The WordPress REST API: A Christmas Present for Front-End Developers

WordPress 4.7 was released in December 2016, bringing with it content endpoints for the new REST API. Front-end developers can use these endpoints to build content-rich website and applications using WordPress out-of-the-box, all while never touching a single line of PHP. Today we’ll unwrap what the REST API is, why you should use it, and how you can start working with it in your projects now.

A headless CMS

The new REST API in WordPress is a game-changer for developers. It transforms WordPress into a headless CMS, meaning the front-end delivery can decoupled from WordPress itself. Front-end developers no longer need to rely on WordPress’s built-in PHP templating system, and back-end developers can focus solely on WordPress without having to worry about tinkering with the front-end — Everybody can focus more on the areas they enjoy.

Additionally, content authors can continue to use the editorial tools within WordPress that make publishing easy and fast. The data created within WordPress can then be used to power multiple front-ends: traditional websites, native mobile apps, single-page applications, third-party apps such as Apple News, Facebook Instant Articles, Google AMP—anywhere users can consume content.

Decoupled development

For front-end devs, using a headless CMS means we can build the front-end completely independently of the backend. This has lots of advantages:

  • It’s fast to setup, so new projects can get off the ground quickly
  • There is more flexibility to change tools in future; We can easily change our front-end to use The Next Big Thing without worrying about how this will affect content
  • We can build multiple front-ends using one set of data
  • Changing the endpoint to switch between different sets of data makes it easy to develop locally using live content
  • You don’t need any prior WordPress knowledge to get started, just the URLs of the endpoints you want to use

So what exactly is the REST API?

The REST API is a way to communicate with WordPress, without using the WordPress interface itself. APIs allow two programs to interact with each other, either inside a single piece of software or with a third-party. WordPress already has many internal APIs, such as the plugins API, which makes developing and extending WordPress easier. The term REST refers to the architectural style of the API, where the interaction is made through basic HTTP requests. Applications make requests to certain URLs, called endpoints, and receive data back in a standardised JSON format. This portable data can then be used by multiple technologies to display and distribute content. Data can also be posted to endpoints to push new content back into WordPress.

Retrieving content and data from WordPress

Endpoints give us a clear path to access data created in WordPress from any other application. The ones that have just been introduced into WordPress core are known as content endpoints, and give us access to public content such as posts, pages, users, and taxonomies out-of-the-box. So, we can easily start playing with the content within any website which is running WordPress 4.7 or later, including this one!

Retrieving posts

We can add the endpoint /wp-json/wp/v2/posts to any up-to-date WordPress website to get an array of JSON objects which contain post data. You can see a live example of what that looks like here:

http://OFFLINEZIP.wpsho/wp-json/wp/v2/posts

(I recommend the JSON Viewer Chrome extension for making JSON more human-readable).

Each post has lots of data attached to it, including post author, category, date published, etc. This is all standard data that is associated with every WordPress post, allowing us to build around this data knowing the structure will be the same for every site we want to get data from.

One property that is particularly useful when developing with the REST API is the _links object. This contains links to other endpoints in the API that are associated with this post. Each of these links can then be called if needed, to pull in peripheral data for each post. Notice that a few of these links, including author and category, have a property of "embeddable": true. This means we can embed the data from this link in our original request. To do this, we can pass a URL parameter of _embed:

http://OFFLINEZIP.wpsho/wp-json/wp/v2/posts?_embed

This adds a new property of _embedded to each post object, which contains all the data that is embeddable from the original post. We now have access to full author and taxonomy information without having to make further requests.

We can also modify the content we receive from WordPress by adding other query parameters to the URL. For example, if we want to retrieve a list of all the posts written by a certain author on a website, we can pass the ID of the author to get them:

http://OFFLINEZIP.wpsho/wp-json/wp/v2/posts?author=1

Similarly for all posts from a certain category, just pass the category ID:

http://OFFLINEZIP.wpsho/wp-json/wp/v2/posts?category=23

This gives us lots of control over exactly what content we display, filtering it before we use it. A full list of all the parameters available is on the WP-API docs site.

Retrieving other types of content

The word posts in the endpoint refers to the Posts content type, one of the default post types that is built into WordPress. We can swap this word out to retrieve other kinds of content, including pages, users, categories, and tags (see the full list of all the current endpoints available in WordPress). These endpoints present data in exactly the same way as to posts endpoint, allowing you to navigate around and pull in the data as you need it. It is possible for endpoints to be added for customised data, however this requires some additional PHP to implement. Let’s keep it simple here!

Pulling in content

Now we have seen where to get the content from, let’s take a look at a way to pull it into our work. The WordPress REST API has often been associated with React, with many websites and applications using the API and React together to build interactive experiences and fast-flowing websites. Because of this pairing, many people feel they need to learn React in order to work with the REST API—this is not the case. The REST API can be consumed using any programming language. Here is a very basic example that pulls in content using just a few lines of plain JavaScript:

If vanilla JavaScript is not your flavour, you can also use your weapon of choice: React, Angular, Vue; you can even get started with jQuery:

Because all WordPress sites will output the data in a standardised format, the above code will work with any website running WordPress 4.7—Try swapping out the 12 Devs of Xmas domain for CSS Tricks, for example. The WP-API site also has a demo site you can play around with.

Displaying content

Once we’ve retrieved the content, you can display it and use it however you like. One advantage of using the REST API means we can fetch lots of content in one request, then display it from local memory. Here is a simple example of how this could work using plain JavaScript; Each article has a button at the bottom to load in the next one:

The content is displayed instantly because everything is preloaded and available in the browser.

From here, we can start taking it one step further to improve performance and perceived page speed. We can asynchronously prefetch more content once the initial page has loaded, so it is ready and waiting to be displayed when the user clicks a link. This is great for news-style websites—you could load your top ten most popular articles in the background while the user browses headlines. Combine saving these in local storage and using service workers on top of that for offline management, and you’re on your way to building a fast, progressive app with a great content-driven backend. Who knew you could do that with WordPress?

Start playing!

Hopefully this has given you a few ideas about how you can start using WordPress as part of your development workflow. If you’d like a short project to get you started, how about creating a single-page website that showcases the 12 Devs of Xmas articles? You could also use this as an opportunity to build something with a new technology you’ve been meaning to play around with. I’d be really interested to see what you come up with, send me a tweet @sambulance with your creations!