1. What is the WordPress REST API?
The WordPress REST API is an application programming interface (API) that provides developers with programmatic access to WordPress’s content management system (CMS) and data structures. It allows developers to create, read, update, and delete WordPress content, as well as manage and configure WordPress settings.
2. What are the benefits of using the WordPress REST API?
The WordPress REST API provides developers with a powerful and flexible way to interact with WordPress. It allows developers to create custom applications and websites that can interact with WordPress data, such as posts, pages, users, and more. Additionally, the WordPress REST API can be used to create mobile applications, integrate with third-party services, and create custom content management systems.
3. How do I get started with the WordPress REST API?
Getting started with the WordPress REST API is easy. First, you’ll need to install the WordPress REST API plugin. Once installed, you can begin exploring the API by using the WordPress REST API documentation. Additionally, there are many tutorials and resources available online to help you get started.
4. What are the best practices for using the WordPress REST API?
When using the WordPress REST API, it’s important to follow best practices to ensure that your code is secure and efficient. Some best practices include using the latest version of the API, using secure authentication methods, and using the appropriate HTTP methods for the task at hand. Additionally, it’s important to use the appropriate data formats and to test your code before deploying it.
The WordPress REST API is in the process of changing WordPress. You may not have noticed, as a lot of it is under the hood, but the implications of the REST API make a huge difference to the future of WordPress, both in terms of its codebase and its uses.
If you haven’t worked with the WordPress REST API, you might be wondering just what it is. So let’s kick off by looking at what the REST API is.
What is the WordPress REST API?
The WordPress REST API is an interface that developers can use to access WordPress from outside the WordPress installation itself. You access it using JavaScript, which means it can be used to create interactive websites and apps.
REST stands for Representational State Transfer and API stands for Application Programming Interface. Let’s take a look at what each of those means.
What is an Application Programming Interface (API)?
An Application Programming Interface, or API, is defined as:
“An interface or communication protocol between a client and a server intended to simplify the building of client-side software.”
If you aren’t familiar with APIs, that may not help very much. To put it more simply, an API is a set of code that allows one system to interact (or “interface”) with another. If you’ve ever added a Google map to your WordPress site, you’ve used Google’s Maps API, which allows your WordPress site to interface with Google Maps.
These systems don’t need to be completely separate. WordPress already has multiple APIs, for things like plugins, settings, and shortcodes. These can be used by plugin and theme developers to interact with WordPress core and make things happen (like creating shortcodes and adding settings screens to the WordPress admin).
The difference with the REST API is that it allows systems outside your WordPress installation itself to interact with WordPress, which is where the REST part comes in.
What is Representational State Transfer (REST)?
Representational State Transfer, or REST, provides standards that web systems can use to interface with each other. Without REST, two systems wouldn’t be able to understand each other and so send data back and forth.
For an application to be RESTful, it must conform to five principles:
- Uniform interface. The URLs used to access resources in the system have to be uniform, consistent, and accessible via a common approach such as GET (more of which shortly).
- Client-server. Client applications and server applications must be separate, so they can be developed independently of each other. If the server-side technology (i.e. WordPress) changes, the server-side application (an app, for example) must still be able to access it via the same simple method.
- Stateless. The server doesn’t change state when a new request is made using the API. It doesn’t store the requests that have been made.
- Cacheable. All resources must be cacheable, to improve speed and conformance to web standards. Caching can be implemented on the server or client-side.
- Layered system. A RESTful system lets you use multiple layers to access it, storing data in intermediate servers if it needs to. The server can’t tell if the final client is directly connected to it.
All of these constraints relate to web pages and applications and govern the way an application can interface with the API.
What Does This Mean for WordPress?
Putting REST and API together means that the WordPress REST API is a set of code designed to make it possible for other systems to interface with WordPress and that it’s built in a way that ensures these systems will understand each other.
It means that a third-party website or a mobile app, for example, can access your WordPress database, fetch data from it, and add data to it.
There are a number of implications and uses for this, though.
Understanding the WordPress REST API
The WordPress REST API was developed in response to changes in the way websites and apps are developed and a need to open up WordPress more widely.
Background to the WordPress REST API
The WordPress REST API was released as part of core in version 4.7 in December 2016, but it was around as a plugin before then.
It’s designed to support a range of applications built on WordPress and to transform WordPress from a content management system to an application platform.
It’s used extensively by WordPress.com, whose JavaScript-based interface uses the REST API to interface with the WordPress database. It’s also used by the Gutenberg editing interface, which became part of core in 2019.
The REST API widens the range of applications that WordPress can be used for. While a content management system excels at running a complex website, an application platform can also be used to power web-based single-page applications or SPAs (if you’ve ever used Google docs, you’ve used one of those).
In these, the content is refreshed when the user takes action, instead of loading new pages. Because it uses JavaScript (a client-side language) instead of PHP (a server-side language), it can make things happen in the user’s browser without having to constantly send requests to the server.
Implications for WordPress Users and Developers
If you’re a user and/or developer working with WordPress, the REST API has a number of implications.
For users, these include:
- Changes to the interface, including the Gutenberg editor.
- Changes and improvements to the WordPress mobile app.
- Self-hosted WordPress admin screens looking more like WordPress.com screens over time.
For developers, there are wider implications and possibilities:
- The ability to create SPAs using the REST API, pulling data in from WordPress but looking very different from WordPress.
- The ability to integrate WordPress with other frontend technologies and systems.
- The ability to develop with WordPress if you’re a frontend developer who doesn’t write PHP.
- For PHP developers, an increasing need to expand your skills to include JavaScript.
- Specific changes such as the need to build Gutenberg blocks instead of meta boxes in page and post editing screens.
Over time, the WordPress REST API will mean that more of WordPress core will be written in JavaScript and not PHP. If you’re a WordPress developer, this means you will need to learn JavaScript.
How to Access the WordPress REST API
How do you access the WordPress REST API?
To access the WP-REST API, you’ll need to access your site via the command line. With WordPress, this is called WP-CLI. You don’t do any of this via your admin screens or by directly accessing the code on your site.
Let’s take a look at how you get started.
Accessing WP-REST via WP-CLI
WP-CLI is the WordPress Command Line Interface. It lets you access and work with WordPress via the Command Line Interface (CLI) on your computer. WP-CLI is pre-installed with all Kinsta hosting plans.
To access the CLI, open Terminal on a Mac or in Linux, or Command Prompt in Windows.
To access a remote site, you need to SSH to your server to access it via WP-CLI (Can’t connect via SSH? Learn how to fix the SSH “Connection Refused” Error).
To access a local site, you simply need to use the correct directory structure from the command line. It’s a good idea to experiment with the REST API on a local test site before trying it on a live site.
You’ll need to specifically access the REST API for your site, like this:
http://yoursite.com/wp-json/wp/v2
You can then add elements after this to access certain types of data, which we’ll look at in more detail shortly. These elements are called endpoints.
Authentication
Once you’ve accessed your site, you may need to go through authentication. Some endpoints are public and don’t require authentication, while others do.
You’re not logging into your site admin here: the REST API does things a bit differently.
To be able to authenticate your site via WP-CLI, you’ll need to install an authentication plugin. For development installations, the Basic Auth plugin does the job and is straightforward to work with.
However, for live sites, you should use a more robust form of authentication such as the JWT Authentication plugin, which uses JSON Web Token and is more secure.
You can then use the command line to access data and include authentication.
The example below uses curl
to test the connection to WordPress. It will output a list of draft posts.
curl -X GET --user username:password -i http://yoursite.com/wp-json/wp/v2/posts?status=draft
Draft posts aren’t public information, so you need authentication to access them. But if you’re looking for data that is public, you don’t need authentication. So to retrieve a list of posts which have been published, you could use:
curl -X GET http://yoursite.com/wp-json/wp/v2/posts
This would fetch all published posts because those are public.
Overview of WordPress REST API Commands
Once you’ve accessed your site and you know how to use authentication (and indeed whether you need to), you’ll need to use one of a range of commands to interact with your site.
The commands you’ll need to use are:
GET
retrieves a resource such as a post or some other data.POST
adds a resource to the server, such as a post, attachment or another resource.PUT
can be used to edit or update a resource that’s already on the server.DELETE
removes a resource from the server. Use it with care!
Let’s take a look at each of these in turn.
GET
The GET
command is probably the most commonly used: it retrieves data. The example below (which you use once you’ve successfully accessed your site) would fetch a list of all published pages in your site:
GET http://yoursite.com/wp-json/wp/v2/posts/?status=published
Note that I haven’t included the full path to your site in the line above as you’ve already accessed that using WP-CLI.
Having retrieved that data, you can use it to inform your next step. You might delete one of those posts, edit it, or update it. You could simply output posts to your web app.
Let’s say you wanted to fetch the latest post. You’d use this:
GET http://yoursite.com/wp-json/wp/v2/posts/?per_page=1
There are a number of arguments you can use when working with posts. See the WordPress REST API Handbook for more.
POST
Use POST
to add new data or resources to your site.
So, for example, if you wanted to create a post, you would start by using a POST
command:
POST http://yoursite.com/wp-json/wp/v2/posts/
This would create a new empty draft post.
You can then update the post by using a PUT
command to edit it.
With a POST
command, you can also add other resources other than posts, including attachments and other post types.
To add a page to your site, you might use something like this:
POST http://yoursite.com/wp-json/wp/v2/posts/pages
This would create an empty page in just the same way as you would create an empty post.
PUT
The PUT
command lets you edit an existing resource, including posts.
Let’s say you have a number of draft posts on your site. You want to check them and update one to make it published.
You could start by fetching a list of all the draft posts:
POST http://yoursite.com/wp-json/wp/v2/posts/?status="draft"
The system will give you a list of all current draft posts. You can change the status of one of them using its ID:
PUT http://yoursite.com/wp-json/wp/v2/posts/567
This accesses that post and allows you to edit it. You can then change its status using the status argument:
{
"status" = "publish"
}
Or you could add content to the post and publish it:
{
"status" = "publish"
"content" = "content here"
}
The server will return a 200 - OK
status telling you the PUT request has successfully edited the post.
DELETE
The DELETE
command does what you would expect: it deletes a resource. By default, if you use it to delete a post it will put it in the trash instead of permanently deleting it.
So if you wanted to move the post you just created to the trash, you would use this:
DELETE http://yoursite.com/wp-json/wp/v2/posts/567
However, if you wanted to bypass the trash and delete it permanently, you would use the force
argument:
DELETE http://yoursite.com/wp-json/wp/v2/posts/567?force=true
This permanently deletes the post with no option to undo, so it should be used with caution.
When Not to Use the WordPress REST API
The WordPress REST API won’t always be the right approach to developing a website or app. Here are some considerations you should be aware of before using it for development:
Compatibility
If your app is going to be used on devices that don’t run JavaScript or by users who are likely to have it turned off, then it won’t run if you’re using the REST API.
A WordPress site coded in PHP will output HTML so it won’t suffer from this problem. Devices that don’t use JavaScript are getting rarer but if you are developing specifically for those, the REST API won’t work.
Similarly, if your users are likely to turn JavaScript off, then working with the REST API will cause problems. Some users turn off JavaScript in their browsers for accessibility or security reasons.
Accessibility
Sites or apps developed using JavaScript aren’t always as accessible as those output in HTML.
This is largely because of the way JavaScript is used to deliver dynamic content which may not play nicely with screen readers and may cause problems for people with visual impairments or photosensitive epilepsy.
Using the REST API to access your WordPress site and output data in a form that is designed to be accessible means you can overcome these problems, but it is worth checking your site for accessibility while you’re developing it.
SEO
Single Page Applications, which refresh frequently, can sometimes cause SEO issues. This is because content that isn’t delivered when the page is first output may not be indexed by search engines.
Google and other search engines are catching up with the fact that many websites now are SPA-powered and are indexing them appropriately. But it does pay to do a thorough SEO audit of any site you develop using the REST API.
How to Disable the WordPress REST API
If you don’t want applications to be able to access data from your site using the REST API, you can disable it. Remember that public data could be accessible by anyone, not just you.
To do this, you can install the Disable WP REST API plugin. This disables the REST API for anyone who isn’t logged in to your site.
Alternatively, you can add some code to your theme’s functions file or write your own plugin. It’s better to write a plugin as this isn’t theme-specific functionality.
In your plugin, add just two lines:
add_filter( 'json_enabled', '__return_false' );
add_filter( 'json_jsonp_enabled', '__return_false' );
This will completely disable the REST API for your site. It may have knock-on effects for your admin screens so make sure everything works OK once you’ve added it.
Real-World Applications using the WordPress REST API
The REST API presents some exciting possibilities for the future of WordPress. Here are some examples of applications and sites using the WordPress REST API to create SPAs or to link WordPress to other sites and technologies.
WordPress.com
The WordPress.com admin screens are built entirely using the REST API to provide a SPA that users interact with to manage their site.
This makes for dynamic communication between the interface and the server and results in a user-friendly interface that WordPress.org is likely to mimic in time.
The Block Editor (Gutenberg)
Also in the WordPress admin screens, but this time in self-hosted WordPress as well, the Gutenberg block editor makes use of the REST API to communicate with your database and create blocks.
For post types to work with the Gutenberg editor, they must have the REST API enabled. Which means that if you’re registering a custom post type and using Gutenberg, you’ll need to add the following line to enable the block editor for that post type:
"show_in_rest" = true;
Event Espresso
Event Espresso is a WordPress plugin that lets users organize and publicize events. It makes use of the REST API so that users can access data from it from outside of WordPress. This means you can build mobile apps or SPAs to manage your events.
UsTwo
UsTwo is a digital agency whose site was built using the REST API as a Single Page Application. This combines a front-end built using React with a backend powered by WordPress (suggested reading: Your Guide to Starting and Running a Successful WordPress Agency).
The content of their single page is modular, with a structure that’s different from a standard WordPress page. To make this work, they use a custom page builder plugin that lets their team add modular content to the site.
USA Today
USA Today’s website was rebuilt using the WordPress REST API integration with existing systems and modules in the site.
The REST API allowed for the site’s content to be pushed to other outlets such as Facebook Instant Articles and Apple News, using JSON. They also wrote an online social game for their sports section, built using JavaScript.
Summary
The WordPress REST API presents some exciting challenges but also interesting opportunities for both WordPress users and developers. It’s the future of WordPress and is likely to radically change the way we develop with WordPress and the way we use it.
What’s your take on REST API? Have you used it for some of your projects? Tell us in the comment section below!