Serving up WordPress with React – Part 1

WordPress is an undeniably popular CMS - Content Management System, powering 31% of the internet. A feature-rich platform, WordPress provides a relatively easy interface to users of all technical aptitude. Developers, in particular, have had a long association with the PHP-powered back-end of WordPress, building complex, web applications and plugins that extend existing functionality.

Traditionally websites built around WordPress use PHP as the language of choice for communicating with the WordPress back-end. While PHP is an extremely powerful language in it’s own right, it comes with the drawbacks that most server-side languages do. The very drawbacks that led to the success of Single Page Applications, which offer a richer user experience. So, it was only a matter of time before WordPress catered to this segment. Say hello to the WordPress REST API!!

Developers can now merge the strength of WordPress powered web applications with the advantages of newer frameworks and libraries and without limitations on choice of programming language. In this series of articles, we will take a detailed look at the WordPress REST API, and create a simple web application that harnesses all it’s features, using React. So let’s get started!

What are REST APIs?

Briefly, a REST API, or Representational State Transfer based, Application Program Interface, provide users with an interface to request for specific data. Requests are made using HTTP requests, such as GET, POST, PUT, DELETE etc. Responses can be sent as JSON or as XML. JSON stands for JavaScript Object Notation, and is lightweight and human-readable and by far the more popular format with most REST APIs. For this series, we will focus on JSON format responses, as the WordPress REST API also uses them.

An important aspect to note when working with RESTful APIs are the API endpoints. These are the routes that are mapped to the different HTTP methods, that provide you with the ability to interact with the API. In order to understand how to derive the maximum from an API, you must be aware of the endpoints available to you. This needs to be backed by an understanding of the API Schema, which allows you to understand the data structure underlying each endpoint.

This article won’t go into the details of how a RESTful API works, for a more in depth look, check out this website. If you feel comfortable with the basic idea of RESTful APIs, let’s now move on to the WordPress REST API.

The WordPress REST API

The WordPress REST API offers all its content in the form of JSON objects. To access these we make use of REST API features, such as endpoints, the API Schema, Controller Classes and more. Let’s start by looking at the most important entities in the API.

To see a complete list of entities and their schemas, head over to the WordPress REST API Handbook

Let’s take a closer look at the Schema, as well as the endpoints, for the two main entities we will use in our application, Posts and Users. Do look at the remaining schemas and options available to you, as we may not cover everything during the course of this article.

Posts

WordPress functions around managing content, which is neatly categorized into Posts. For our application we will be interacting with Posts often, including retrieving a list of all the posts, posts by a specific user, a single post etc. So let’s take a selective peak at the properties Posts Schema offers us, in JSON format.

When you query for any post objects, these properties will be returned to you within the response object.

Post Schema is accessible in the following ways:

  • Get a listing of posts
    • Route : GET /wp/v2/posts
  • Create a post
    • Route : POST /wp/v2/posts
  • Retrieve a post
    • Route : GET /wp/v2/posts/<id>
  • Update a post
    • Route : POST /wp/v2/posts/<id>
  • Delete a post
    • Route : DELETE /wp/v2/posts/<id>

Users

All users registered with the site, including the admin, are stored in this table. The Users Schema gives you access to,

Users Schema is accessible to you via:

  • List users
    • Route : GET /wp/v2/users
  • Create a user
    • Route : POST /wp/v2/users
  • Retrieve a user
    • Route : GET /wp/v2/users/<id>
  • Update a user
    • Route : POST /wp/v2/users/<id>
  • Delete a user
    • Route : DELETE /wp/v2/users/<id>
  • Retrieve user
    • Route : GET /wp/v2/users/me
  • Update user
    • Route : POST /wp/v2/users/me
  • Delete user
    • Route : DELETE /wp/v2/users/me

The last three routes mentioned are for the user sending the request, not for a user by ID as specified by the earlier, Retrieve/Update/Delete requests.

Note that Create, Retrieve, Update and Delete are collectively known as CRUD operations, and every entity in the API allows you perform CRUD operations on it. So expect these basic operations from Categories, Tags, Media and Comments as well.

Connecting to the WordPress REST API

How does the Schema actually connect to the routes mentioned? When trying to access a REST API, you are provided with routes, the WordPress REST API is no different. The API matches the route to the correct endpoint, or method, depending on the URL, or Route you sent your request through. The method then processes the request and returns a response object to your HTTP request.

For you to successfully request data from a WordPress REST API, you need to add /wp-json/wp/v2 to your WordPress site URL. Please note that REST API was integrated with the WordPress core since version 4.7 and up.

For our application I created a dummy WordPress back-end at http://dev.bluekrill.com/demoWP/wp-json. So an example API call to list all posts will be in the following format :

LIST ALL POSTS 

GET  http://dev.bluekrill.com/demoWP/wp-json/wp/v2/posts

When I make this request, the WordPress API will return an array of all post objects in JSON format. Try pasting this URL in the browser and you’ll see the response sent by the server in your browser, which may be hard to read as it will be unformatted.

But that’s not all. You can customize your request to a large extent by adding parameters to your routes. These are provided by the REST API as well.

For example, if I wanted to make the same request, but only list posts that match a certain term, I can use the search parameter

GET http://dev.bluekrill.com/demoWP/wp-json/wp/v2/posts?search=term

This will return a list of posts containing the word “term”. There are many other parameter options provided with each entity, such as Order, Order By, Author, Categories and more. You’ll come across these in further detail as we go about building our application.

The Application

Our application, which I’ll title React-Press, will be built using React (didn’t see that one coming did you?). We will allow users to perform basic functions that they would be able to do with any WordPress website. To further sweeten our User Experience, I will be using Bootstrap, to give the site a clean, structured and responsive look.

Let’s look at the most basic features we want to start with:

To achieve this, we will create a few container pages, namely

  • Home
  • Sign In / Up
  • User Dashboard

These will allow users to perform all the functions stated above. Now let’s start some actual building.

Building the React App

Set up the React app with

create-react-app react-press

cd react-press

Now let’s start installing a key dependencies:

To make our HTTP requests –

npm install --save axios

To handle Routing within the app:

npm install --save react-router-dom

To animate our route transition (strictly optional)

npm install --save react-router-transition

To set up Bootstrap

npm install --save reactstrap bootstrap

To smoothen Data Flow

npm install --save react-redux redux

To allow asynchronous actions

npm install --save redux-thunk

And we’re set!

Once you’ve install all these open up your favorite Code Editor and let’s start building our Containers, Components and Store. You could also clone this application from https://github.com/kvnam/reactpress and run a quick npm install to get all the code I’ve whipped up so far.

When I’m building React applications, I like to think in terms of how data flows within a React app, which is down the component tree. So I like to create containers that hold control of the data and methods, and pass these down to smaller components. This is just my approach, feel free to structure your app differently if you feel that works better, and do share, so we can all learn. Here’s a peak at my folder structure so far.

My main Containers for this app are Blog, UserAccount and Auth. These will handle Post scope, Registered user scope and Authentication scope respectively. I then create components for Navigation, Posts and Authentication. My Redux code sits safely in the Store folder, which holds all my actions and reducers.

Don’t let this confuse you, we will still go about building our application in a serial manner, so you don’t need to create any folders in your application just yet.

We’ll continue building our application in the next part of our series, where we will:

  • Set up Redux
  • Set up our Home/Blog page
  • Set up Filtering and Searching of Posts
  • Set up User Sign Up and Sign In
  • Add Authentication

and more.

In the meanwhile if you would like to jump ahead and get peek at the application code, head on over to https://github.com/kvnam/reactpress. Feel free to fork or clone the project to get started. I’m still adding features, so if have something you would like to add, send me a pull request.

Checkout Part 2 in the series!

You can follow me on GitHub, or connect on LinkedIn, or just drop me an email at kavita@bluekrill.com.

To get a faster introduction to WordPress REST API, check out Toptal’s Guide to the WordPress REST API

If you like it, tell others:

Leave a Comment

Your email address will not be published. Required fields are marked *