Introducing REST APIs

Welcome back to our tutorial on building themes with JavaScript. In part one, we considered the JavaScript web landscape and looked at where we are today. I suggested that while JavaScript lets us render content in new and interesting ways, there are challenges when it comes to fetching the content in the first place.

Watch the video presentation or read the written transcript below.

Screencast

Demo Materials

You’ll find accompanying material for this screencast available in a public GitHub repo — each screencast has a corresponding folder with very simple theme that can be activated.

Time for a REST

With traditional WordPress themes, we’ve been able to use all manner of loops and custom queries to get data. In shifting our approach to be less PHP-centric, where will our data come from?

The missing piece of our puzzle is a REST API, essentially an HTTP interface for getting data from a source. The REST part stands for REpresentational State Transfer. Think of it as a way of accessing WordPress queries directly through a URL. We can type a URL into our browser and include parameters just like we would with a custom loop, and in the browser we can see pure data from our website.

A REST API also allows you to post data, so the WordPress REST API allows you to add and update content directly without using the admin interface. Certain types of requests do need authentication, the REST API only publicly exposes content which is already revealed by WordPress through other avenues, like RSS feeds.

This all means that you don’t have to worry about connecting to a database, you just use a series of URLs to access different types of content on your site — these are known as endpoints.

The WordPress REST API is due to be fully incorporated in WordPress 4.5, due in the spring of next year. In fact, the infrastructure of the WordPress REST API will be included with WordPress 4.4 and has already been merged into trunk.

Exploring the WordPress REST API

Next, let’s look at some of the basic things we can do with the WordPress REST API.

I have a WordPress environment set up locally where I have installed WP API. Ahead of its inclusion in core, WP API is available as a plugin on the WordPress plugin repository. With the plugin activated, I can navigate to the URL /wp-json/. At this URL I can see an overview of everything that the REST API makes available to me.

Screen Shot 2015-11-25 at 17.39.08

As the URL suggests, WP API uses JSON formatted data. This is not compulsory for REST APIs, but most REST APIs will use either JSON or XML formatted data. More recently JSON is the preferred format as it’s less verbose and generally easier to work with. I’m also using a Chrome extension called JSON View, which adds sane line breaks and some colours to make it easier to read the JSON. Without JSON View, the JSON data is quite hard for a human to read!

The REST API adds namespaces to its endpoints. This is to ensure that extensions and future versions of the API don’t break functionality for sites and software that use it. The primary namespace at the moment is wp/v2. This means that we can build our website against version 2 of the REST API. If, in the future, it’s decided that the REST API should be structured differently, this restructure would happen under the namespace of wp/v3. Therefore the REST API could completely change, but what we built for v2 would be safe with the inherent backwards compatibility of the v2 namespace.

So, if we navigate to /wp-json/wp/v2/ we can see all of the information about this namespace. As newcomers, we don’t have to worry about this at the moment, but it’s worth understanding the path we take to what we’re really trying to get from the REST API.

If we add posts/ to the end of the above URL, we finally start seeing the data from our website. By default, posts/ will show us the same content that a generic loop on our homepage would. On a clean install of WordPress, this is usually the 10 most recent posts.

Screen Shot 2015-11-25 at 17.39.35

We can further narrow down our request to the REST API by adding a post’s ID to the URL. So in this instance, /wp-json/wp/v2/posts/1241/ will show us just the one post with ID 1241.

The REST API provides typical things that we might want in relation to a post. We can see the date, modified date, permalink, title, content, excerpt, format, whether or not it’s sticky, and more.

Now let’s consider an example where we use the REST API to render content on a page using JavaScript.

I’ve set up a basic HTML document set up in my text editor, including a div with the id "page", an anchor link with text “Hello world,” and an empty h1 and div element. The div has an id of "content".

Beneath that, we have some inline JavaScript inside a script tag. To begin, we use JavaScript’s native XMLHttpRequest API to fetch our data. This is what’s behind jQuery’s Ajax functions, you may remember this from part 1 when I spoke about the website YouMightNotNeedjQuery.com.

What this does is fetch the URL from the REST API that we were just looking at. If it’s successful, it will parse the JSON response so that we can access the different elements as a JavaScript object. We then use the querySelector and innerHTML methods to change the data in the HTML on this page. At the moment we aren’t dealing with errors, we would want to deal with these if we were doing this in production.

Let’s see how this works. If I activate the session 2 theme on my test site, we can see what this does. There we go, the data from the REST API is being rendered in my theme demo.

One last thing before we end this tutorial. We still have that link that I added at the top — let’s look at how this is connected.

Well, if we go back to the index of our little theme and scroll down, you can see we also have a function, changePost. This does exactly the same thing as the other bit of JavaScript, but it gets a different post (with ID 1). Beneath this, you can see that we add an event listener to the link. The link listens for a click, if it gets clicked it fires the function. Let’s see what happens.

There we have it.

You can now see how a very basic WordPress REST API-based theme can work. In the next screencast we will consider more advanced approaches to theming and the challenges we face when taking this approach.

The Series

  1. JavaScript, jQuery and the web landscape today
  2. Introducing REST APIs
  3. Challenges in JavaScript-Based Theming
  4. Bringing React into our theme
  5. Et voila, a JavaScript WordPress theme that uses the WordPress REST API

The ThemeShaper JavaScript Theme Tutorial

Dive into the brave new world of JavaScript WordPress theming, looking at best practices and pitfalls along the way.

Introduction

WordPress theming hasn’t changed very much over the past few years. It’s certainly become more refined, and projects such as Underscores (_s) have helped promote best practices and robust standards. That said, we can still go as far back as Kubrick and find plenty of common ground with the most recent WordPress themes.

This isn’t a bad thing, and it’s probably one of the reasons WordPress is so popular and so many people have been able to get involved in theming. But the web has changed substantially since WordPress welcomed its first default theme in 2006. More than half the web’s users now access it from mobile devices. We have HTML5, and with it a whole host of browser APIs that didn’t exist in 2006. These advances have helped a whole new ecosystem of JavaScript-based web apps blossom.

Some aspects of this ecosystem have found their way into WordPress themes. Most of us have probably seen our fair share of jQuery-enabled carousels. We have JavaScript-enhanced tiled galleries and lightboxes available through plugins like Jetpack. Yet very few of us would consider building a theme entirely in JavaScript. The thought may even send shivers down many of our spines.

Building a WordPress theme with JavaScript might be considered lunacy by some, who may wonder why you’d want to attempt such a thing. Others may have questions about SEO, performance, accessibility, plugin compatibility, among a myriad of issues. There are definitely challenges to building a theme with JavaScript, and before reading any further you should know that this is still an experimental area of WordPress theme development.

But, and this is a big “but,” a JavaScript-based approach to theme-building opens up a wonderful world of new possibilities to the curious developer, including:

  • Storing and pre-fetching content using the browser’s Web Storage API to allow server-less, seamless transitions — using the browser’s History API — between posts and pages.
  • Animations within themes, for more natural and intuitive interactions.
  • The ability to create entirely offline experiences using all new Service Workers.

Along with these exciting improvements, the WordPress REST API is being integrated into Core. The REST API makes it much easier for us to build themes with JavaScript. There is no better time to start getting familiar with how the WordPress ecosystem is changing.

The Series

In this five-part tutorial, we’ll expose you to the brave new world that WordPress theme development might inhabit in the coming years. While the best practices for building a theme in this way are still to be established, we’ll do our very best to guide you into the secret garden of the future.

Stay tuned for:

  1. JavaScript, jQuery and the web landscape today
  2. Introducing REST APIs
  3. Challenges in JavaScript-Based Theming
  4. Bringing React into our theme
  5. Et voila, a JavaScript WordPress theme that uses the WordPress REST API

Theming with the REST API – Meet Picard

If there’s one thing that has been making waves in the WordPress ecosystem this year, it is the new REST API. Officially known as WP-API, and currently available as a plugin, it is due to be rolled into core at some point this year.

A REST API?

A REST API may not initially seem like a useful feature for theme developers. It is clearly very useful for those looking to use WordPress as an application platform, but how the REST API can be used within a theme is perhaps more opaque.

The Theme Division at Automattic have had an eye on the potential uses of a REST API powering a theme for at least a couple of years now, and in recent months some concepts have started to take shape.

The Future is JavaScript

There are many potential benefits to building themes that rely more than ever before on JavaScript and the REST API, including but not limited to:

  • Design: We can have smooth transitions between the different types of content on our websites.
  • Speed: We can store content from the REST API in localStorage (effectively the browser’s memory). This means that on the initial site load we can store any post that is retrieved. Imagine a user clicking a ‘read more’ link and the full post being displayed without the need of a further server request.
  • Offline: By handling interactions with JavaScript, as developers we gain control of what happens if the user goes offline while browsing our site. We can let them know that the server doesn’t appear to be reachable and we can present content that we know is stored in their browser in a graceful way.

Picard Screenshot

Picard

In February of this year, the team worked together on a prototype REST API theme that has become known as Picard (a geeky nod to “the next generation” of themes). To create Picard, we used React, a JavaScript library for building user interfaces. Coupled with vanilla JavaScript and a number of other libraries sourced through npm, we were quickly able to produce an engaging, working prototype.

Recently, I have been talking about building themes with the REST API and our approach to building Picard at a number of WordCamps so far this year, culminating in a workshop at the inaugural LoopConf.

Today, Picard is now publicly available on GitHub.

Tango

We intend to continue developing Picard and working on some of the harder problems that we have not yet solved. We aren’t stopping at Picard either. Our experiments have led us in various directions. My colleague Kirk Wight has created another experimental theme called Tango. Tango is an extension of the concepts we are exploring with Picard, blended with the bulletproof Underscores starter theme.

Make It So

The future of WordPress theming may dramatically shift with the official adoption of the REST API but you don’t have to wait for the future to take advantage of it now. Clone Picard and Tango. Experiment and see what you can do. These are exciting times for themes!

Further Reading and Resources


 

Photo credit: JD Hancock/flickr