In version 4.4 of WordPress the REST API was being introduced to the project and would make WordPress more extensible than ever. The WP REST API makes it possible for developers to push and pull data to and from WordPress from outside of WordPress. This allows you to create all kinds of cool and useful software applications that may not necessarily use the traditional WordPress user interface but is powered by or integrated with WordPress. It allows you to communicate with other software applications regardless of the programming language an application was written in.
Some of you may already know what a REST API is and may even be surprised that one wasn’t built into WordPress sooner. Let’s try to break it down Barney style, you know that big annoying purple dinosaur that kids used to be obsessed with and made parents want gouge their eyes and ears out.
Some refer to the WP REST API as the JSON REST API
An Application Programming Interface is basically a bunch of functions and tools built into a software application used by developers to interact with that software application either internally or externally usually via the internet between web applications.
Depending on how the API was set up, leveraging an API could allow you to push and pull content and data in or out of another application effectively integrating 2 or more applications.
The WordPress REST API allows you to interact with the WordPress database from outside of your WordPress website.
REST stands for Representational State Transfer which is an architectural style for defining HTTP based communications between web applications.
There are 4 main types of requests or HTTP methods for working with RESTful APIs.
GET
POST
PUT
DELETE
These can also be called CRUD tasks or create, read, update, and delete. Whatever you want to call these self explanatory verbs, they are used in HTTP requests to an API to perform actions.
There are guiding principles for building a REST API and each of the following constraints must be met for an interface to be deemed RESTful.
Client-Server
Stateless
Cacheable
Uniform Interface
Layered System
Code on Demand
JavaScript Object Notation, kind of wish my name was Jason so I could pronounce my name JSON, is an open standard text format for sending readable text in data objects like arrays and name value pairs. Based on your HTTP request, you will be returned a JSON response that you can write code to get the data from the objects within that response.
Well, with the WP REST API you can do just about anything you might need to do from within the traditional WordPress dashboard but from anywhere, it’s also a standard and secure way to do so. Below are some examples of what you could use the WP REST API for:
Allowing Public Access to WordPress Data—The API is on by default on the latest versions of WordPress allowing anyone to easily grab any of your public content such as posts, pages, media, and comments. Although not public by default you can make any Custom Post Type and any of its data publicly available via the WP REST API. You can also create custom endpoints that are open to the public for anybody to retrieve whatever data you specify.
Allowing CRUD access to manage WordPress Data—So exactly the opposite of what we just talked about. If you want a 3rd party app to be able to manage WordPress data you need to have authorization to do so. The WP REST API allow you to authenticate a few different ways so you can create, read, update, and delete on a WordPress user’s behalf. Basically, once properly authenticated you can manage all of your WordPress data from outside of WordPress. We will cover the current authentication methods in this chapter shortly.
Exchanging Data between WordPress Websites—This is a pretty common use case, imagine the possibilities of easily exchanging data between two or more WordPress websites.
Headless WordPress Websites—The term headless just means that you aren’t using the WordPress front end at all but instead are just using the backend for whatever reason. You may want to set up a headless WordPress install strictly to store data you will use in another application via the WP REST API.
WordPress powered Mobile Apps—At AppPresser we do this all day every day. Utilizing the WP REST API you can build mobile native apps that use WordPress as the datasource. If you are building a stand alone app and don’t need a website you could use a headless WordPress install to power your app. If you have an existing website you can build a mobile app to compliment it and share its data.
Asynchronous Data Syncs—Developers commonly run into issues when they are building new WordPress websites from snapshots of production WordPress databases, which is usually done to preserve all of the original content and also give developers real data to work with while building the new website. Usually content like posts, comments, and users could be getting created on the production website while the new website is still being developed, this can be a PITA when it’s time to launch the new website. Depending on the project, you might want to do a content freeze on the production website and import any new data into the development website that will become the production website, or maybe it makes sense to move any new data on the development database like settings or new posts type posts and meta or whatever into the production website. If you have done a lot of new WordPress website launches from existing WordPress websites you can probably tell where I’m going here. By the time you are ready to launch the new website you might have data that you need in both the production and development websites, now you are stuck writing custom scripts that cherry pick the data that you need from either environment. Hmmm, maybe use the WP REST API to update the development website with any new or updated data in real time as it happens on the production website. A solution like this could save you lot’s of time from manually syncing your data prior to launching a new website.
Virtual Reality and Gaming—Imagine immersive VR environments with custom content delivered via the WP REST API? How about you’re building a race car game and you want the billboards on the road to display custom content.
Alexa and Google Home—Alexa, make me a sandwich.
Authentication is important if you want to use the WP REST API for more than just pulling public content from a WordPress website. The WP REST API provides options for authentication that can be utilized depending on what you are building.
Cookie authentication is the default and at this time the only authentication method built into core WordPress, but you can use the other authentication methods via 3rd party plugins or build your own if you choose or need to. For cookie based authentication a user just has to be logged into WordPress, when any API requests are made they are governed by what actions that logged in user can perform.
The WP REST API also uses nonces to address cross-site request forgery or CRSF, so somebody trying to be malicious can’t just use your cookie to do whatever they want, they would also have to have a valid nonce. The recommend way to use the WordPress REST API for custom themes and plugins is to leverage the built-in Javascript API which the nonces are created automatically for you. You can also make manual requests but you would need to pass the nonce with each request that you make.
Cookie authentication makes it super easy to build cool features and functionality into the front-end of your website via a theme or plugin so your users can interact with WordPress data without going to the backend.
Example
Basic authentication is a quick and dirty solution for developing apps for external clients that integrate with WordPress data. First things first tho, you do not want to use this method of authentication in any of your client’s production environments or any WordPress websites you wouldn’t want to get hacked (should be all of them). Basic authentication should really only be used for development purposes because it requires a base64 encoded username and password be sent through the header of every WP REST API request. Base64 encoded strings can be intercepted and decoded so you can see the problem this could cause for you.
If you would like to quickly be able to test the WP REST API with an external to WordPress application you are building you should check out the following plugin:
example
OAuth or Open Authorization, released in 2007, is an open standard for token-based authentication and authorization. OAuth is the prefered method for developing apps for external clients that integrate with WordPress data. OAuth basically acts as a middle man between the user and WordPress, it allows a user to authenticate without ever exposing their password in any requests. An OAuth Flow is the process of obtaining a token that is then used to authorize specific account information for a user to be shared with an application.
Currently there are two versions of OAuth, 1.0 and 2.0. The major difference between the two versions is that 2.0 requires that API requests are authorized via HTTPS or SSL/TLS. There are also two OAuth WordPress plugins that the WordPress REST API Team has developed to work with each version of OAuth.
https://github.com/WP-API/OAuth1—This plugin actually uses OAuth 1.0a because it does not require SSL for any endpoints while OAuth 1.0 does does require SSL for some. Because WordPress does not require SSL, or that your website be HTTPS, this is currently the more developed and popular plugin to use.
https://github.com/WP-API/OAuth2—This plugin may also be an option for you but please note that it is still an early beta version.
You could always build your own from scratch or leverage an existing library but why on earth would you want to spend all that time reinventing the wheel. Both of these OAuth plugins use what is referred to as three-legged authentication, where each leg is a seperate role that is involved with the authentication process:
Client—The 3rd party application you want to communicate with WordPress.
Server—The WordPress install that the 3rd party application will make API requests on.
Resource Owner—The end user that has a login to the WordPress install and is using the 3rd party application.
OAuth uses token credentials that are issued by the Server, when the Resource Owner authenticates using their credentials. These tokens that are linked to the Resource Owner are used by the Client to gain access to the Server. These token credentials can be revoked by the Server at any time by the Resource Owner, they will also eventually expire which will require the Resource Owner to re-authenticate.
The OAuth Flow in more detail:
The client sends a signed request to the server for obtaining a Request Token, also known as Temporary Credentials. This request is sent to the Temporary Credentials endpoint URI, and it contains the following:
oauth_consumer_key: provided by the server
oauth_timestamp
oauth_nonce
oauth_signature
oauth_signature_method
oath_callback
oauth_version (optional)
The server verifies the request and if it’s valid, grants a Request Token that contains:
oauth_token
oauth_token_secret
oauth_callback_confirmed
The client then sends the resource owner (the user) to the server to authorize the request. This is done by constructing a request URI by adding oauth_token obtained in the previous step to the Resource Owner Authorization endpoint URI.
The resource owner (the user) authorizes at the server by providing credentials.
If the oauth_callback URI was provided in the first step, the server redirects the client to that URI and appends the following as query string:
oauth_token: obtained in the second step
oauth_verifier: used to ensure that the resource owner who granted access is the same returned to the client
If the oauth_callback URI was not provided in the first step, then the server displays the value of the oauth_verifier so that the resource owner could inform the client manually.
After receiving oauth_verfier, the client requests the server for token credentials by sending a request to the Token Request endpoint URI. This request contains the following:
oauth_token: obtained in the second step
oauth_verfier: obtained in the previous step
oauth_consumer_key: provided by the resource provider (the server), before starting the oauth handshake
oauth_signature
oauth_signature_method
oauth_nonce
oauth_version
The server verifies the request and grants the following, known as Token Credentials:
oauth_token
oauth_token_secret
The client then uses Token Credentials to access protected resources on the server.
The above information can either be transported by a query string appended to request URIs or by including it in the Authorization header, though the latter is recommended due to better security. This is a lengthy process and should be taken into account when developing our own clients to interact with the API. The purpose of the client is to manage all this jargon and facilitate the user in the authentication process. Since we will be using a package provided by the WP REST API team, the above details will be abstracted away and we will be able to gain token credentials in a minimum number of steps. In the above discussion, we came across three endpoint URIs, namely: Temporary Credential Request endpoint Resource Owner Authorization endpoint Token Credentials Request endpoint These URIs are provided by the server in various ways. One of these ways is by exposing them in the server response when checking for the API. The OAuth authentication API for WordPress REST API uses the same method, as we will see in the next section.
For the rest of our WP REST API examples in this chapter we are going to use the OAuth1 plugin mentioned and linked to above. You can also get the most current version directly from the WordPress plugin repository: https://wordpress.org/plugins/rest-api-oauth1/
Go ahead and install then activate this plugin like you would any other WordPress plugin.