Before we dive into what WordPress REST API is, let’s get a little acquainted with WordPress itself for the benefit of the uninitiated.
WordPress, launched way back in 2003, was built to create and publish web pages easily, especially for people less acquainted with web development or programming in general. Over the years WordPress has evolved from a blogging platform to a full-fledged web development tool capable of building feature-rich web applications and e-commerce stores.
WordPress expanded its services further by introducing WordPress REST API in Dec 2015. This powerful feature opened doors to a whole new way of using WordPress by allowing developers to separate the front-end from data management. The REST API also allows them to take advantage of the WordPress codebase in other web and mobile projects.
Detailed documentation is available on that you can refer to if you are interested in using the WordPress REST API. However, people who are not familiar with the basic concepts of REST APIs might need to understand what it is and how it works!
In this guide, I’ll cover the basic concepts as well as the anatomy of REST API to get you up and running with WordPress REST API.
Here is everything I’ll cover
What is an API
An Application Programming Interface, or API, is a set of instructions that is used for communication between two or more applications.
APIs allow multiple application to communicate with each other or with a centralized back-end to perform a specific task that can also involve database access.
An application using the API is only allowed to access the endpoints (explained later) for posting and reading data. It’s not allowed to make any logical changes nor is it allowed to access the back-end code of the API.
In short, it’s a secure method of giving access to third-party applications to use your program and database.
There are several types of APIs, such as:
- SOAP (Simple Object Access Protocol)
In this article, I’m only discussing the REST API. Before I explain what a REST API is, let’s look at some important use cases where APIs come handy.
- Google API (Allows the users to login with their Gmail accounts)
- Google MAPS (Allows you to integrate MAPS functionality inside your web or mobile application)
- Facebook API (Allows you to add ‘Log in with Facebook’ functionality and to post through the application.)
- Twitter API (Makes Twitter sharing easy)
REST, short for Representational State Transfer, is a type of API which is not a protocol but rather a set of architectural principals.
Allow me to explain that in plain English.
Hopefully, that was simple enough for you to understand.
Why Use REST API
REST APIs have become industry standard and have been adopted by technology giants like Google, Facebook, and Amazon. Developers also find it easier to work with due to its structure and fast data exchange.
Why REST APIs are popular? Well, it’s because they use JSON for data formatting. JSON represents data in key/value pairs which is less confusing and more predictable. APIs that use JSON are faster in terms of data exchange and have simpler code compared to XML formatting.
Here are some advantages of using REST APIs:
- JSON (which is typically used with REST APIs) parse faster due to a simpler structure.
- They are easier to work with.
- They offer better browser support and are ideal for caching especially static information.
- REST API consumes less bandwidth and is easier to integrate with existing web projects.
Giants like Yahoo, eBay, Amazon, and Google have adopted it.
Now that you have a basic understanding of what an API is and what are the advantages of using a REST API, let’s dive in to explore the anatomy of a WordPress REST API.
Anatomy of WordPress REST API
REST APIs are built to keep both the server and the client side separated, and it’s easier to manage, update, and deploy.
Imagine if both the server side and client side code is written in a single file and you need to make changes after a few months? Well, good luck in understanding your code first, let alone going through the hassle of updating the file.
The primary goal of any REST API is to perform CRUD (Create, Read, Update, and Delete) tasks.
Typically, an API is requested with the following requests from the client:
GET: This command fetches the data from the server. For example; retrieving client’s information.
POST: This command allows you to add data to the server. For example; registering a client.
PUT: This command allows you to update existing data. For example; updating a visitor’s password.
DELETE: As the name suggests, this command lets you delete data from the database.
Routes & Endpoints
Routes and Endpoints are two fundamental elements of WordPress REST API. An endpoint is simply a URL through which a connection is built with the server and Routes are the individual micro-services which can be accessed to perform the specific operation.
Here’s an example:
In the URL above, /wp-json/ is the route which fetches the information related to WordPress, namespaces, and routes.
Any task you perform using WordPress REST API is in the form of a request. This request is handled by the default class named WP_REST_Request. This class stores the information of all the requests you make using WP REST API.
Typically, a request is made to a certain endpoint and can also contain parameters. One such example is to fetch post data of a certain category.
The response contains the desired information you asked for while making the request to an API. WordPress REST API response contains the data in JSON format which is easy to work with. If anything goes wrong or validation fails, you get an error inside the same response.
The easiest way to see the response is by using the Chrome developer’s tool. Simply right click on the window and click on Inspect. This should open a new window inside which you can either go to Console for console messages and to Network tab for a detailed view of an API request.
As you can see, it contains useful information such as requested URL, the request method, Status code, and response headers.
Controller Classes further extends the functionality of the WordPress REST API. It allows you to build your custom endpoints and routes and to manage all the elements responsible for running the API.
Schema allows you to define the data structures endpoints can use and the parameters the REST API can accept.
How to Use WordPress REST API
Enabling REST API in WordPress
In order to use WP REST API, make sure that it’s already installed by running the following command (you can run the command inside the SSH terminal):
I got the following error after running the above command which means that I need to install wp-cli on my server.
Installing the REST API on WordPress is easy. You just have to run the following command:
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
Now change the file’s permission to make it executable:
chmod +x wp-cli.phar sudo mv wp-cli.phar /usr/local/bin/wp
Now you can run the WP-CLI commands without any issues.
Updating REST API in WordPress
In case you need to update the REST API, just login to your SSH terminal and run the following command.
wp cli update
This command will update the REST API in WordPress with the most recent, stable version of WP REST API.
Basic authentication with WordPress REST API is easy to set up. In this type of authentication, the user requests a URL that requires verification. The credentials user sends to this request is encoded in the base64 string. However, this is not considered the most secure method of authentication as a base64 string can easily be decoded.
In order to use this type of authentication, download the Basic Auth plugin from Github and upload it to your WordPress site using the Plugins tab.
Other two types of authentications are Cookie Authentication, used by plugins and themes running on the same site, and OAuth Authentication, used for external clients.
The primary advantage of using the REST API in WordPress is its ability to connect WordPress to any other application.
wp_remote_post function can be used for posting data. This function accepts two parameters: Endpoint or the URL you wish to use and the arguments you wish to send with it.
For example, if you need to add a new post using WordPress API you can do so through the following method.
$args['body'] = array( 'title' => 'WP REST API', 'status' => 'draft', 'content' => 'content' ); $response = wp_remote_post( 'http://username:firstname.lastname@example.org/wp-json/wp/v2/posts/', $args );
In the code above, I requested my WordPress site to add a new blog post using WordPress REST API.
The wp_remote_post function can also be used in fetching the data from your WordPress site.
For example, if you need to fetch posts by a certain category, simply request it using the following line of code:
$response = wp_remote_get( 'http://username:email@example.com/wp-json/wp/v2/posts/?categories=3');
In the code above, I requested posts of a certain category only using the WordPress REST API. However, this can return an error if I try to access the Restricted resources without passing the set authentication criteria.
WordPress REST API is a powerful tool which can be utilized to build new plugins, upgrade existing web projects, and to automate tasks. Using the REST API is the fastest and the best way to connect your web projects with WordPress.
In this tutorial, I’ve explained what a REST API is, how it works, and how WordPress REST API works. I suggest you test it out and experiment with it to understand the real power of this amazing feature.
Also, don’t forget to share your experience in the comments below.