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:
A Beginner’s Guide to HTTP and REST by Ludovico Fischer
Demystifying REST by Jeffrey Way
Introducing JSON by Michael James Williams
Storing Data with JSON (screencast) by Andrew Burgess
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:
GET: Used to read or retrieve a resource
POST: Used to create a new resource
PUT: Used to update a resource
DELETE: Used to delete a resource
HEAD: Used to check if a resource exists without returning its representation
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.
A 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:
1: GET wp/v2/posts
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:
2: GET wp/v2/posts/100
A 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:
3: POST wp/v2/posts
And the following PUT request will update a post having an id of 100:
4: PUT wp/v2/posts/100
A 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:
1: GET wp/v2/posts
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:
2: wp/v2/posts
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:
3: POST wp/v2/posts
This endpoint, when triggered with supplied parameters, will create a new post entity.
Consider the following route:
4: wp/v2/posts/100
This route points to the Post entity having an id of 100. It has the following three endpoints:
GET wp/v2/posts/100: Which can be used to retrieve the post having an id of 100. It triggers the get_item() method.
PUT wp/v2/posts/100: Can be used to update the post having an id of 100. It triggers the update_item() method.
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.
Leave a Reply