Advertisement
  1. Code
  2. WordPress
Code

Introducing the WP REST API

by
Difficulty:BeginnerLength:MediumLanguages:
This post is part of a series called Introducing the WP REST API.
WP REST API: Setting Up and Using Basic Authentication

With its inception in 2003, WordPress has grown up from merely a blogging platform to a full fledged content management system. Over these past years, it has matured enough to cater the need of vast majority of online audience and this is the reason it’s empowering more than 20% of the web today.

With many new features being added to WordPress, one of the latest to-be addition is the REST API that allows other apps and platforms to interact with WordPress. It’s a revolutionary addition that will help developers build custom applications and integrated systems with WordPress. Since it provides the capability to add and retrieve content from any other client or site, without the need of having WordPress installed on that site, it allows WordPress to be used with any programming language or platform.

In this multi-part series, we will be taking a look at the WP REST API and how it could be used to create user experiences that were otherwise impossible or at least, arduous with WordPress. We will first take a look at basic concepts including REST and JSON, and then explore the options available to us through the WP REST API.

Below are a few resources that I found useful for basic concepts including HTTP, REST, and JSON. I highly recommend you to taking a look at them if you haven’t already:

Before we start off with our topic, let’s have a brief look at what actually is the REST architecture and also get familiar with its common terminology.

Back to School With REST

To start with the topic, let’s take a look at the REST (Representational State Transfer) architecture and some of its most common concepts. Understanding them is an essential when developing applications using the REST architectural style.

REST is an architectural style that helps create and organize a distributed system. It describes the web as a distributed hypermedia application whose linked resources communicate by exchanging representations of resource state.

Resources are the main building blocks of the REST architecture. In fact, they are the main building blocks of the web itself to the extent that the web is sometimes referred to as “resource-oriented”.

When talking about WordPress, these resources are discrete entities like posts, pages, comments, users, and custom post types etc. To interact with resources, URIs (Uniform Resource Identifier) are used, and as the name suggests, it’s an identifier for a resource.

A RESTful service treats URIs as the primary way to address an underlying resource. These resource may have several representations. For example, an image file might be available in .JPG, .GIF, or .PNG formats. The relationship between resources and URIs is one-to-many. A URI can only point to one specific resource but a resource may have more than one URIs.

The list of all the resources currently supported by the WP REST API is as below:

  • Posts
  • Pages
  • Media
  • Custom Post Types
  • Post Meta
  • Revisions
  • Comments
  • Terms
  • Users

We can perform different actions on these resources using HTTP verbs.

HTTP Verbs

A REST API basically allows to perform CRUD (Create Read Update Delete) operations on resources using HTTP. For this purpose, REST makes use of limited set of HTTP request verbs which are as the following:

  1. GET: Used to read or retrieve a resource
  2. POST: Used to create a new resource
  3. PUT: Used to update a resource
  4. DELETE: Used to delete a resource
  5.  HEAD: Used to check if a resource exists without returning its representation
  6. OPTIONS: Used to retrieve all the verbs supported by a resource

In a RESTful service, these verbs have a well defined meanings. The first four verbs in the above list are part of CRUD actions i.e. they retrieve, create, update and delete entities. The last two verbs assist a client in determining whether a resource exists and what HTTP verbs are available for it to perform further operations.

GET request retrieves information and is idempotent i.e. a client can call it many times but it will not affect the state of a resource.

To get all the posts using the WP REST API, we use the following endpoint:

The above endpoint will return a collection of all the post entities.

When the following endpoint is triggered, it returns a particular entity i.e. a post having an id of 100:

POST request creates a new entity and a PUT request replaces that entity with a new version.

The following POST request can be used to create a new post (sending along the request body that we will be taking a look at in the later part of the series) using the WP REST API:

And the following PUT request will update a post having an id of 100:

DELETE request deletes a resource from the system. This type of request, along with PUT request are repeatable, meaning that calling these methods will have the same effect on the system. For example, if you call a PUT request multiple times on a resource (with the same arguments), the result will be the same. The same goes for a DELETE request. Deleting a resource multiple times will have the same effect i.e. the resource will be deleted (or an error would be returned in case of an already deleted resource).

In addition to these CRUD actions, a RESTful service provides two more verbs that are OPTIONS and HEAD. These verbs come in handy when a client needs to check what resources are available on the system and what actions they support, thus providing a self-documenting way for the client to further explore the system and perform actions. We will see these two methods in action later in this tutorial.

More About Routes and Endpoints

Note that in the very first example above, we used the following endpoint:

Endpoints are functions that are available through the API and they perform several actions like retrieving posts (that we are doing above), creating a new user, or updating a post meta. Alternatively, we can say that an endpoint triggers a method that performs a specific task. These endpoints are dependent on the HTTP verb associated with them. In the above example, we are using the GET verb to retrieve all posts.

The route for the above endpoint is the following:

A route is basically a name to access the endpoint. A route can have multiple endpoints based on HTTP verbs. So the above route has the following endpoint to create a new post:

This endpoint, when triggered with supplied parameters, will create a new post entity.

Consider the following route:

This route points to the Post entity having an id of 100. It has the following three endpoints:

  1. GET wp/v2/posts/100: Which can be used to retrieve the post having an id of 100. It triggers the get_item() method.
  2. PUT wp/v2/posts/100: Can be used to update the post having an id of 100. It triggers the update_item() method.
  3. DELETE wp/v2/posts/100: It deletes the post having an id of 100. It triggers the delete_item() method.

We will learn more about the internals of the WP REST API, it’s class structure, and internal methods in the final part of this series.

Let’s now refresh our knowledge about some common HTTP response codes and what they mean.

HTTP Response Codes

A server responds to a request by returning a response that contains an HTTP status code. These codes are numbers with predefined meanings associated with them. For example, anyone using the web would be familiar with the 404 status code that summarizes that the resource, user was looking for, was not found.

The response of the server is also dependent on the type of HTTP verb or method we use in the request sent, as we will see next.

Following are some common HTTP response codes along with their meanings, that we will encounter when working with the WP REST API and their meanings:

  • 200 - OK: Means that the request has been completed successfully and the server has returned the response. Usually returned after a successful GET request.
  • 201 - Created: Usually returned after a successful POST request. Summarizes that the resource has been created.
  • 400 - Bad Request: It’s returned from the server when a request was sent with some missing or invalid parameters. Usually returned in response to POST or PUT requests.
  • 401 - Unauthorized: Means that user was not authorized to perform certain action. For example, a user tried to create or delete a resource without providing authentication credentials.
  • 403 - Forbidden: Means that server understood the request but refused to complete it due to authentication. It happens when a user provides authentication credentials but it doesn’t have sufficient rights to perform the action.
  • 404 - Not Found: The most (in)famous of all the status codes. Summarizes that a resource, the user was looking for, was not found.
  • 405 - Method not Allowed: Means that an HTTP verb supplied in the request was not supported by the resource. An example might be a user trying to update a read-only resource.
  • 410 - Gone: Means that a resource has been moved to another location. An example might be trying to delete an already deleted resource that has been moved to trash.
  • 500 - Internal Server Error: It’s returned when a server encounters an unexpected condition and doesn’t complete the request.
  • 501 - Not Implemented: Means that the server doesn’t support the functionality to complete the request. Usually occurs when a server receives a request method that it doesn’t recognize.

We will look into these HTTP verbs and response codes more closely when we actually begin working with the API. But before that, let’s take a look at the reasons for using REST API with WordPress and the advantages it provides to both the developer and the user. After all, I need you to be genuinely interested to follow along with me during this series.

Why Use JSON REST API for WordPress?

REST and JSON together provide a mechanism for creating powerful applications using the WordPress back-end. The most prime examples being mobile apps that require the exchange of data between the client (the device) and the server. Keeping in view the bandwidth limitations when using cellular data, JSON provides a lightweight alternative to XML based solutions.

Since JSON is a text based format for storing data, it can be used seamlessly with the majority of the programming languages. Hence JSON serves as a global connector when exchanging data between different platforms that is equally readable by both machines and humans.

With the use of API like the one being discussed, the content of your WordPress site is not limited to itself only, but can be accessed by other sites and clients. As API exposes some parts of the internal functionality, remote clients can interact with your site to update or create new content. It also allows to retrieve some content from an existing WordPress site and show it on some other site.

With the rise of client-side JavaScript frameworks like Angular, Backbone or Ember, it has now become possible to use one of these to create rich user experiences while still using the WordPress back-end.

With that said, some possible use cases for the WP REST API are:

  • Mobile apps
  • Custom admin panels for WordPress
  • Single Page Applications (SPAs)
  • Integration with other server-side platforms (like Ruby, .NET, and Django etc.)
  • and much more…

It really opens up a new world of possibilities where the only limit is one’s imagination.

A Short History of JSON REST APIs in WordPress

Prior to JSON based REST APIs, the API used to remotely interact with WordPress was XML-RPC API that is still part of the WordPress core. The problem with XML is that it’s not as lightweight as JSON format and its parsing is not efficient. Traversing XML is also one big of a headache, while traversing a JSON object is as easy as handling a native JavaScript object.

The first ever REST API plugin to be introduced for WordPress was JSON API that was released in 2009. It was built at The Museum of Modern Art for their blog Inside/Out. This blog’s front-end was powered by Ruby on Rails, so to retrieve posts from and adding comments to the WordPress backend, an API was developed. This plugin provides interfaces for retrieving content and submitting comments to the WP backend. Although, not updated for more than two years, this plugin is still present in the official repository and is up for grab.

Apart from the JSON API plugin, WordPress.com has already been providing JSON API via the  JetPack plugin.

The WP REST API, as we know it today is a feature plugin that was proposed by Ryan McCue as part of GsoC (Google Summer of Code) 2013. It is yet to be included (completely) in the WordPress core in a future release. The current version 2.0 of the plugin is in beta state and is partially included in the WordPress core in version 4.4. It’s a community driven project lead by Ryan McCue and Rachel Baker. The official repository page of the plugin is located on GitHub and the official documentation can be found on its website.

Current State of the WP REST API

As mentioned above that the WP REST API is currently in plugin state and is being developed actively on GitHub. It has been partially included in the WordPress core in version 4.4 and Ryan has described the plan in his merge proposal on WordPress.org.

According to the merge proposal, the WP REST API would be incorporated into the WP core in two stages as described below:

Infrastructure Code Merge

According to the proposal, at the initial stage, only the infrastructure level code will be merged into the WP core in the release 4.4. This infrastructure code is the actual base of the WP REST API as it includes JSON serialization/deserialization, linking, embedding, and the most important of all - the routing layer that drives the API. This code doesn’t include endpoints and their controller classes, but it does provide a base for building APIs inside WordPress.

At the time of writing, this state has been completed and the infrastructure code has been merged in the WordPress core in version 4.4.

Endpoints Merge

The endpoints for posts, pages, users, and taxonomies etc. will be incorporated in the WP core in the release 4.5, i.e. one release later than the infrastructure code merge. The endpoints are what makes the API useful to general clients. They include much complexity including mapping the external data in JSON format to native WordPress data types, and vice versa. They account for the two-third code of the API itself with approximately 5500 lines.

The strategy here is to build developer confidence in the API by first providing the infrastructure code in the core. This would allow theme and plugin developers to build custom APIs to be included in their themes and plugins. But since, endpoints will not be included at this stage, this would limit the utility of the API initially.

The gap between the two releases would give the WP core committer team enough time to review the API endpoints.

Another advantage that the WP REST API would bring to the WordPress community is the usage of GitHub in version controlling the project. Since all the contributions to WordPress are made through SVN and Trac, the WP REST API team is quite confident about improving the contribution process by bridging the gap between Trac and GitHub.

After the merge of the API into the core, we can hope to see rapid developments in others areas including the OAuth 1.0a authentication.

Tools of Trade

To begin testing with the WP REST API we will need an HTTP client that will be used to send requests to the server and view the response. It’s really a matter of your choice but I’ll be using Postman for Google Chrome during this series. Other alternatives to Postman are:

Postman allows us to create quick HTTP requests of different methods, view the response from the server and test configuration for the authentication. All of these features will come in extremely handy when working with the WP REST API.

The next thing we need to have on our server is WP-CLI. With WP-CLI, we can remotely manage our WordPress installation from within the console without the need to open browser window. We will need to use WP-CLI in the next part of this series when setting up OAuth 1.0a authentication. You can find the installation instructions on the official site.

Apart from an HTTP client and WP-CLI, we also need demo data for our WordPress installation. I suggest checking out Theme Unit Test (XML) or the Demo Data Creator plugin that allows to create multiple posts, pages, and users.

Installing the Plugin

At the time of writing this tutorial, the current stable version is 1.2.2 which can be found on the official repository. In this series, we will be working with version 2.0 as it has been re-written from the ground up and contains many breaking changes. You can grab the version 2 beta from its official plugin page or from its GitHub repository

Please note that it’s highly not recommended to install the current beta on your production environment. I’ve set up a local WordPress environment and I recommend you doing so for development and testing purpose.

To install the plugin from the GitHub repository, open up your terminal and pull the plugin after going into your /wp-content/plugins/ directory:

The plugin will be downloaded in the /WP-API/ directory.

You can activate it from your WordPress admin to continue testing with it.

In order to the WP REST API plugin to work, you need to enable pretty permalinks with WordPress. It’s assumed here that you already know to perform this basic action. If you don’t, no worries as WordPress.org has got you covered.

Assessing the API Availability

After the plugin has been installed, we can assess the availability of the API on our server. We are not limited to using the API on our site only, in fact, you we use it on any site that has it installed and enabled. To check for the API on other sites, we can send a HEAD request to the site as the following using your HTTP client:

This will return something like the following in the response header:

Response Header

The Link header points to the root route of the WP API which in our case is the following:

The API can also be discovered through in-browser JavaScript (or jQuery) by querying the DOM for the appropriate <link> element like the following:

From here we can start retrieving the content from the site through the WP REST API. Please note that only authenticated requests can edit or update the content on the site and I’m saving the subject of setting up authentication for the next two parts of this series.

What’s Up Next?

In this introductory part of the series we learnt quite a lot about the REST architecture, the WP REST API and HTTP itself. We first looked at basics concepts like what REST architecture is and how it can help developers create better applications. Then we learned about HTTP, its verbs, and response types. We also looked at short history about APIs in WordPress and how the WP REST API is different from its predecessors.

In the final part of this tutorial, we installed the plugin from GitHub. After that we familiarized ourselves with a HEAD request that can be used to determine the availability of the API on our server as well as on other servers.

Having set up the basic working environment we are ready to work with the features the WP REST API provides. In the next part of the series, we will be looking at ways to set up authentication methods that are supported by the API. These authentication methods will be required when sending request to retrieve, create, update or delete content. So stay tuned.


Advertisement
Advertisement
Looking for something to help kick start your next project?

Envato Market has a range of items for sale to help get you started.