What is API?
Basically, API or Application Programming Interface is a structure of software applications comprising of set of tools and protocols that developers can use to build those applications. In layman’s language, it is a set of standardized methods in which particular software can be used. These are the rules made for interaction with the wider audience which decide the way other pieces of software can communicate with a program and how it will respond.
For example, when a user visits a website, his browser sends a request to the server on which that site is located.
Actually, that server’s API receives the browser’s request, interprets it, and sends back all the data needed to display the site.
What is REST API?
The REST API is an old concept. It is defined as “Representational State Transfer” by Roy Fielding in the year 2000 when he designed HTTP 1.1 and Uniform Resource Identifiers also known as URLs. In simple language, it is a way in which programs can communicate in the simplest possible way.
REST is an HTML-based architecture used for building APIs. In a RESTful architecture, HTTP requests are used to post, read, update, and delete data between two sources.
What is JSON REST API?
Generally, JSON is an alternative to XML-based solutions which makes it perfect for mobile apps with limited bandwidth.
Working of WordPress REST API
To learn about the working of the WordPress REST API, you need to understand the working of HTTP requests and responses. When a URL is entered in the address bar of a browser, it is a request made. When the server displays the website or application for that URL, it is a response to your request.
There are a few different types of requests or “HTTP methods” when you start using the WordPress REST API. Check below the four main types of HTTP methods the web uses:
- GET – For getting data from the server.
- POST – For sending data to the server.
- PUT – For changing or updating data on the server.
- DELETE – For removing data from the server.
Keeping these definitions in mind, when you enter a URL in a browser, it is a GET request. When you enter your login information for a website, it is a POST request. If you change your current password to a new one, it is a PUT request while if you terminate your account, it is a DELETE request.
Other terms you’ll come across are “routes” and “endpoints”. A route is basically the URL or a part of the URL you’re trying to access while an endpoint is basically the response you get from the server.
When HTTP requests are sent by external sources to the server hosting your WordPress site, the REST API exposes your data securely by responding to those requests with a common architecture and its own set of protocols.
Due to this WordPress content, such as posts, pages, and comments, is allowed to be processed as raw data. The point is that it allows you to make changes to your site’s content even if you can’t access the WordPress admin area.
This helps you to make changes to your site using JSON whose responses give developers different ways to interact with their sites.
Understanding the Basics of WordPress REST API
Below are some concepts about WordPress REST API that you should be aware of:
- Routes & Endpoints
- Controller Classes
Routes & Endpoints
In technical terms route is a URL that can be mapped via different HTTPS methods. This mapping between the route and an HTTP method is known as an “endpoint”. WordPress REST API is accessible and you can check which routes and endpoints are available for your site by including the route “/wp-json/” at the end of the URL.
This can be seen at WordPress.org by visiting https://www.wordpress.org/wp-json/:
For Chrome, you can install an extension called JSON Viewer (JSON viewer for Firefox can be installed from here) to clean this mess up:
In case you don’t use pretty permalinks, use “?rest_route=” instead of “wp-json”. Whatever you use, you will see here is an example of a route and an endpoint. “/wp-json/” and “/?rest_route=/” are routes. With this, you can access the WordPress REST API through the GET HTTP method. The WordPress REST API gets displayed to you is an endpoint served to us via a JSON response.
The requests are processed by the WordPress REST API using a class names WP_REST_Request. It is a primary class in the infrastructure of WordPress REST API. You can store and retrieve information for all the requests made.
Requests can also be sent remotely using the HTTP methods that we saw above or you can make them internally similar to what you do via PHP.
The WP_REST_Response class is used to process the responses. A response is generally the data you get from a request. This class is used by the API for returning the data sent from endpoints. The result can be errors too.
A concept within the WordPress REST API that serves a variety of purposes is called as schema. API schema identifies the data structures, endpoints can use, and it comprises of a list of the properties the WordPress REST API can return. It also contains the parameters the API can accept and offers security for it by confirming the requests the API receives.
The WordPress REST API handles requests, registers routes and endpoints, utilizes Schema to define the data and properties it can use, and generates API responses on top of all of that. The API as well as you as the developer, needs a way for managing all of these moving parts. Controller classes are available for that. They help you to collect all of these elements and organize them in a single place.
Steps to Start Using WordPress REST API
The first step is to get the authentication – which is a bit difficult. There are three types of authentications available:
- Cookie Authentication – For plugins/themes that run on the same site.
- OAuth – For external clients.
- Basic Authentication – For testing only.
In this article, we will see the basic auth for the purpose of learning, but make sure you do not use it wildly – it isn’t very safe at all.
First install the Basic Auth plugin, available only via Github. Download the zip and install the zip file in the plugins section.
To showcase the ways to access a WordPress installations API, we are going to use some PHP code on our localhost which will access the metadata of a post on our actual website.
To get the publicly available data you can use the wp_remote_get() function as below:
$response = wp_remote_get( 'http://danielpataki.com/wp-json/wp/v2/posts');
By using the $response variable, you will see a slot of data, including the list of posts. If the same method is used for a restricted resource you’ll get an error: “Sorry, you cannot view the meta for this post”. This is where you feel the need for authentication.
With basic auth, we can send our username and password along for each request which will give us the proper privileges.
$response = wp_remote_get( 'http://username:firstname.lastname@example.org/wp-json/wp/v2/posts/445/meta');
With this, we will be able to see all the post meta related with post 445. The disadvantages of this method should be obvious.
It is required to send your username and password with each request as plain text. Remember this is fine for testing and learning about the API but it shouldn’t be used in production.
But when it comes to more complex procedures where we send data, often with parameters, it becomes difficult.
Check the example below that creates a post via the REST API:
$args['body'] = array( 'title' => 'API TEST', 'status' => 'draft', 'content' => 'content' ); $response = wp_remote_post( 'http://username:email@example.com/wp-json/wp/v2/posts/', $args );
Just taking a glance at the schema will help you know what to add to the request body. It comprises of the parameter names, the data types, the description and context.
In the response you get a bunch of information about our new post, including the ID, which would be easy to use, if we want to manipulate the postmeta once the post added.
Check below the steps to start using WordPress REST API:
1. Access the REST API
REST API is accessible using any application that can submit HTTP endpoints. For instance, if you enter the below command in your browser, it will result into a list of your WordPress posts in JSON format:
Don’t forget to replace the placeholder URL with that of your own website. For a REST API request to work, you’ll need to use a version of WordPress greater than 4.4 (which you already might be using).
For really experimenting with the REST API though, a browser isn’t the best tool. Instead, it is recommended to use the command line for a more flexible approach.
2. Fetch a Specific Post Using the REST API
With the above command you might have got a list of all your WordPress posts, along with their post IDs. For fetching a specific post using its ID, you should use an endpoint as below:
For instance, this would be needed for showcasing a specific post translated within a mobile application. But, the WordPress REST API helps you to fetch all types of data from WordPress, so its practical applications are extremely flexible.
Let’s say that you wanted to use the REST API for adding metadata to a selected post instead of just fetching it. In other words, using the POST method rather than GET.
3. Add Metadata to a Specific Post
If you have authenticated yourself, you can add new data to any of your posts with a similar request to that shown in the last section using POST instead of GET:
For example, in case you want to add metadata that can be used to create a rich snippet for a recipe, the request may look as below:
Based on the amount of metadata you want to add, you can specify it using JSON objects instead, which offers a highly structured approach. In any case, once you are known to what the most common endpoints are and how to put them to use, a lot of possibilities arise.
The Reasons for Using WordPress REST API
Check below five solid reasons for using WordPress REST API:
1. Cutting the Cord with PHP
PHP still powers over 80% of modern websites, and is actively endorsed by web giants such as Facebook, and of course WordPress itself.
But in the last decade, there have been enormous advances in other languages such as Ruby, Python and Go, in terms of speed, tooling and available frameworks.
These languages get instant access to the complete range of WordPress’ native functionality with the REST API. This single reason should be enough to get any developer or site owner to think about using REST API.
For getting an instant hold of the potential on offer, you should consider using plugins. Any WordPress plugin today can be perfectly integrated into other frameworks, such as Ruby on Rails or Django.
When it comes to the luxury of the WordPress ecosystem and the way its aspects are monetized, the ability to port to brand new platforms is appealing in terms of achievable revenue for developers.
2. True Mobile Integration
WordPress has proven to be the best as compared to other content management systems in terms of dealing with the challenge of displaying website on all types of devices (via responsive themes). But, the actual integration with the respective iOS and Android apart from the browser remains hard to pin down.
Native WordPress apps help in using the application itself on iOS as well as Android but true third-party integration still remains unachievable.
With REST API, mobile developers will start treating WordPress installs similar to another server, with defined endpoints in terms of their apps. This only fact alone proves WordPress as a possible true backend for native mobile apps and overlays the way for all types of future integrations.
Note that the app usage on mobile remains around the 80% level and this makes it clear that WordPress will need to take a step towards the app environment and this will be possible with the REST API.
While considering the number of websites developed in WordPress that also run independent app versions of their online offerings, there is a high scope for future integration.
3. The Front-End Will Be Strictly Optional
This point is wider: the use of the front-end of WordPress will become strictly optional.
When we consider the viewpoint of API, the WordPress front-end is just another external application that hits its endpoints. The allegations of this are large.
WordPress is now just one item that can be easily added to any modern developer’s toolbox without the need of following its templating system, log in or deal with the internal working of WordPress.
You will surely see a revolution in theming and plugin use cases as it will have a positive impact on developers and site owners globally.
4. The WordPress Backend is Ready to Be Reimagined
Since making changes to the core WordPress website was only possible via admin account, it kept other users dependent on the admin for even small changes.
But, REST API has opened the doors to the core WordPress and the developers can now take their own decision on it instead of just customizing it.
One of the example of this it WordPress.com’s unique take on the admin panel – though that is powered by the separate WordPress.com API.
WordPress has become a potential partner with these technologies with the REST API instead of a competitor. When considering the support for Angular JS and React, this is a smart position to consider.
So, now the developers and theme designers can freely explore the new technologies together along with sharpening their existing WordPress skills.
With this, you will get a complete idea about WordPress REST API.