WordPress REST API: A Beginner’s Guide

>>> Shared from Original Post iThemes

The WordPress REST API is changing the way things get done on WordPress. While much of what’s changing has gone unnoticed because it’s “under the hood,” the implications of the WordPress REST API are shaping the future of WordPress.

In fact, it’s not an exaggeration to say that the future of WordPress will be forever changed for both its users and codebase because of the WordPress REST API.

If you’ve yet to use WordPress REST API, you’re not alone if you’re wondering what exactly it is. So without further delay, let’s dive into the wonderful world of WordPress REST API.

In this Guide

    What is WordPress REST API?

    In a nutshell, the WordPress REST API is part of WordPress and provides developers with new ways to manage WordPress. More specifically, the REST API is a developer interface used to access the WordPress platform outside of the WordPress installation. Because the REST API can be accessed using JavaScript, it can be used for the creation of interactive apps and websites.

    To dive a little deeper into the definition of the WordPress REST API, let’s take a look at the parts of the actual name.

    • The acronym REST stands for Representational State Transfer.
    • API stands for Application Programming Interface.

    Here’s a closer look at what each term means:

    Representational State Transfer (REST) Defined

    REST provides specific standards by which web systems can interface and communicate with each other. If there was no REST, two different systems wouldn’t understand each other’s languages or send data to and from each other.

    There are five principles that an application must conform to in order to be considered RESTful.

    1. Uniform Interface

    All URLs utilized to access resources within the system must be consistent, uniform, and fully accessible by using a common approach like GET (more on that shortly).

    2. Client-Server

    Server applications and client applications have to be separated and developed independently. In other words, if a server-side technology such as WordPress changes, the server-side application (such as an app) has to still be able to access it using the same exact method.

    3. Stateless

    A server can’t change state when new API requests are made. It also doesn’t store requests that were made.

    4. Cacheable

    All of the resources have to be cacheable. This helps improve speed and compliance to Internet standards. Caching can be put into place on the client-side or on the server.

    5. Layered System

    A system that’s RESTful will allow you to use multiple layers when you want to access it. It’ll also sort data in intermediate servers, if need be. The server can’t tell when or if the final client is connected.

    All five of these constraints relate directly to applications and web pages. They help to govern the way applications interface with API.

    Application Programming Interface (API) Defined

    An API, or Application Programming Interface, as “an interface or communication protocol between a client and a server intended to simplify the building of client-side software.”

    However, if you’re not already familiar with what APIs are, that definition probably doesn’t help a lot.

    To put it in more simple language, an API is a set of code. It allows one system to interface, or interact, with another system.

    WordPress REST API

    What the REST API Means for WordPress

    There’s a good chance you’ve already been using WordPress REST API and don’t even know it.

    For example, if you have a Google map embedded in your WordPress website, you’re using the Google Maps API, which lets your WordPress site interface with Google Maps.

    WordPress currently has multiple internal APIs for things such as shortcodes, settings and plugins. The APIs are used by WordPress theme and plugin developers to interact with WordPress core software and create new tools.

    The major difference with REST API is it allows systems that are outside of the WordPress installation to interact directly with WordPress.

    Putting together REST and API means that WordPress REST API is code that is designed to allow other systems to interface with WordPress core. It also means that the WordPress REST API is built in such a way that it makes sure all systems fully understand each other.

    In simpler terms, it means that a third-party mobile app or website would be able to access your WordPress database, add data to it, and fetch data out of it.

    There are any number of uses and implications for this.

    WordPress REST API Background

    WordPress REST API began development in response to changes in how apps and websites were being developed. Developers quickly realized that they needed to open up WordPress on a wider scale.

    In December 2016, in WordPress v. 4.7, the WordPress REST API was first released in WordPress core. However, the plugin version had been around long before that time.

    It was designed to support a wide range of WordPress-built applications and to help transform WordPress from a simple CMS into a full application platform.

    WordPress.com uses the REST API very extensively. In fact, it’s Java-based interface uses REST API to interface in real time with the WordPress database.

    REST API is also used heavily by the Gutenberg editor.

    It truly widens the range and number of applications that you can use WordPress for.

    Implications for Developers and Users

    For WordPress users and developers, REST API has several implications.

    As a user, these implications include:

    • Interface changes, including with the Gutenberg editor
    • Improvements and changes to the mobile app for WordPress
    • Over time, self-hosted WordPress admin screens will begin looking more like the standard WordPress.com admin screens

    As a developer, the implications are wider and have more possibilities:

    • You can now create SPAs by using REST API. This pulls in data from WordPress by looks a lot different than WordPress
    • Integrate WordPress with other frontend systems and tech
    • Develop with WordPress as a frontend developer that doesn’t write PHP
    • If you write PHP, it’ll be important to increasingly expand your skills with JavaScript
    • Specific changes, like the requirement to build Gutenberg blocks rather than meta boxes in post and page editing screens

    As time moves on, REST API will mean that a lot more of WordPress core is going to be written in JavaScript rather than PHP. Because of this, developers are definitely going to need to learn and employ JavaScript in the future.

    Accessing the WordPress REST API

    Accessing the WP-REST API involves accessing your site via the command line.

    This is called WP-CLI in WordPress.

    Remember, you’re not going to perform any of the following steps inside your WordPress admin screen or by accessing your sites code.

    Here’s how to start.

    How To Access WP-REST with WP-CLI

    CLI stands for Command Line Interface. It allows you to access and with WordPress via a CLI (Command Line Interface) on your local workstation.

    WP-CLI will come pre-installed on many WordPress hosting plans. To access it, open up the Command Prompt on a Windows machine. If you’re using Linux or Mac, open Terminal.

    In order to access a remote site, you’ll need to SSH to your server and access it with WP-CLI. For local site access, all you need to do is use the correct directory structure in the command line.

    Just note that it’s smart to try out REST API on a test site prior to employing it on a live site.

    When you do try it out on your live site, make sure you’re running the best WordPress backup plugin in case something goes wrong.

    Now, you’re going to need to access the REST API for your site like this:

    http://yourcoolsite.com/wp-json/wp/v2

    Of course, elements can be added after this in order to access certain data types. These are referred to as endpoints.

    We’ll look more closely at that in a minute.

    Authentication

    After you’ve gained access to the site, authentication may be required. Some endpoints don’t require authentication because they’re public. Others will require authentication.

    But you’re not logging into the WordPress site admin area at this point. The REST API does things differently.

    To authenticate your site with WP-CLI, an authentication plugin will be needed. The Basic Auth plugin gets the job done and is easy to use for testing purposes.

    For live sites, however, it’s best to use a more robust authentication form, like the plugin called JWT Authentication plugin. This solution uses the JSON Web Token, making it far more secure.

    For the sake of security, another WordPress security plugin you should absolutely be running is iThemes Security.

    After this, you can use your command line to access data and include authentication.

    The below example utilizes curl to test for a connection to WordPress. It’ll output a list of drafts in your posts:

    curl -X GET --user username:password -i http://yourcoolsite.com/wp-json/wp/v2/posts?status=draft

    Note that your draft posts aren’t information available to the public. Because of this, you’ll need authentication in order to gain access to them.

    However, if you’re looking for public data, authentication won’t be needed. For example, to retrieve a list of published posts, you’d use:

    curl -X GET http://yourcoolsite.com/wp-json/wp/v2/posts

    This fetches all posts that are published because they are available to the public.

    WordPress REST API Commands Overview

    After you’ve gained access to the site and are using authentication when needed, the next step is using one of a range of commands that interact with your WordPress site.

    The commands that you’ll use are:

    GET

    The GET command retrieves data. It’s the most commonly used command. This example, which can be used after you’ve accessed your site, will fetch a list of pages that are published on your website:

    GET http://yourcoolsite.com/wp-json/wp/v2/posts/?status=published

    It’s important to note that we don’t include the full path to your site because you’ve already accessed it with WP-CLI.

    After that data is retrieved, you’ll be able to use it to inform the next step. Perhaps you’ll edit one of the posts, delete it or make an update to it. Or, you might simply want to output your posts to your web application.

    If you want to fetch your latest post, use this:

    GET http://yourcoolsite.com/wp-json/wp/v2/posts/?per_page=1

    There are quite a few arguments you can use when you’re working with WordPress posts. Take a look at the WordPress REST API Handbook to learn more.

    POST

    You can use POST when you want to add new resources or data to your WordPress site.

    As an example, if you want to create a new post, you’d begin by using a POST command, such as:

    POST http://yourcoolsite.com/wp-json/wp/v2/posts/

    This creates a brand new, empty draft post.

    To update the post, simply use the PUT command.

    With POST commands, you’ll be able to add additional resources beyond posts. This includes other post types and attachments.

    Adding a page to your site would look like this:

    POST http://yourcoolsite.com/wp-json/wp/v2/posts/pages

    This creates an empty page in the same way we would create an empty post.

    PUT

    PUT commands allow you to edit existing resources, including your posts.

    To start, fetch a list of all of your draft posts:

    POST http://yourcoolsite.com/wp-json/wp/v2/posts/?status="draft"

    The system gives you a list of every current draft post. To change the status of one, simply us it’s ID:

    PUT http://yourcoolsite.com/wp-json/wp/v2/posts/567

    This will access the post and allow you to make edits to it. Then, you can change its status by using a status argument:

    {
     "status" = "publish"
     }
     Conversely, you might want to add some content to your post and publish it:
     {
     "status" = "publish"
     "content" = "content here"
     }

    When complete, the server returns a 200 – OK status. This tells you that the PUT request successfully edited your post.

    DELETE

    The DELETE command does exactly what you probably suspect it does: deletes resources.

    However, it doesn’t automatically delete resources permanently. By default, it’ll only put deleted posts into the trash.

    To move a post you just created into the trash, use this:

    DELETE http://yourcoolsite.com/wp-json/wp/v2/posts/566

    If you do want to permanently delete a post, you can use the force argument:

    DELETE http://yourcoolsite.com/wp-json/wp/v2/posts/566?force=true

    Use this option with caution. It will permanently delete the post with no undo option.

    When WordPress REST API Isn’t the Right Tool

    WordPress REST API won’t always be the best approach to developing apps or websites. The following are a few considerations to be aware of before using REST API in WordPress development.

    Overall Compatibility

    If your app is used on devices not running JavaScript or by users who will likely turn it off, it won’t run if you’re using REST API.

    PHP-coded WordPress sites output HTML to avoid this problem.

    Devices not using JavaScript are becoming more rare. But if you’re developing specifically for one of them, REST API won’t be an option.

    Also, if your application users will likely turn off JavaScript, working with REST API will probably cause a lot of problems.

    Keep in mind there are users that turn off JavaScript in their web browsers for security or accessibility reasons.

    Accessibility

    Apps and sites that are developed using JavaScript aren’t typically as accessible as ones that output in HTML.

    The biggest reason is because of how JavaScript is used to deliver dynamic content that might not play correctly with certain screen readers. This causes problems for people with photosensitive epilepsy or other visual impairments.

    SEO

    Frequently-refreshing Single Page Applications sometimes causes issues with SEO. This happens because the content that doesn’t get delivered when the page initially outputs might not be indexed by the search engines.

    Google, DuckDuckGo and other search engines are quickly catching up with the knowledge that many websites are now powered by SPA and have begun indexing them in the appropriate way.

    It’s a good idea to do a full SEO audit of any website that you develop by using REST API.

    How to Disable the WordPress REST API

    Keep in mind that your public data is accessible by anyone who has an Internet connection. You can disable the REST API if you don’t want applications to access site data.

    To disable the REST API, the easiest thing to do is install and activate the iThemes Security plugin. IN the WordPress Tweaks setting, you’ll find a few options for disabling the REST API.

    The REST API setting within the plugin allows you to restrict access to most REST API data. This means that most requests will require a logged in user or a user with specific privileges, blocking public requests for potentially-private data. We recommend selecting this option.

    You can also keep access to REST API data set to default. Information including published posts, user details, and media library entries is available for public access.

    If you’d rather not use a plugin, you can add some code into the functions.php file of your theme or write a plugin. In reality, it would be better to write your own plugin because this functionality isn’t theme-specific.

    In your plugin, add two lines:

     add_filter( 'json_enabled', '__return_false' );
     add_filter( 'json_jsonp_enabled', '__return_false' ); 

    This completely disables the REST API for your website. It could potentially have some knock-on effects for admin screens, so be sure to check that everything is functioning correctly after the lines are added.

    How to Create Secure Application Passwords for REST API

    Another helpful setting in the iThemes Security Pro plugin is Secure App Passwords for REST API, which gives you the ability to limit an application password to only being usable for REST API requests.

    This setting allows for using username/password authentication for REST API requests so you can lock down the REST API (per our recommendation) while still allowing external tools that use the REST API to connect.

    visit Users > Your Profile from the WordPress dashboard.

    Click the “Add a new application password” button.

    From here, you’ll be prompted to name your new application password.

    You’re also given the following options:

    API Types:

    • Valid for REST API requests
    • Valid for XML-RPC requests

    REST API Permissions:

    • Read and Write: The application password can access and modify data.
    • Read-Only: The application password can access data but cannot modify data.

    Once you’ve completed your settings for your new application password, click the “Create application password” button. Copy the generated password and make sure to save it in a secure location.

    iThemes Security will keep a general record of all the generated app passwords including the password name, API types, REST API permission, date created, date last used and the last IP.

    app-passwords-list

    You can always revoke passwords at any time using the individual “Revoke” buttons or the “Revoke all application passwords” button at the bottom of the list.

    WordPress REST API Real-World Applications

    REST API does present exciting possibilities for WordPress both now and in the future. There are some large examples of sites and applications that use the WordPress REST API to link WordPress to other technologies and sites, or to create SPAs.

    WordPress.com is one of these.

    The admin screens in WordPress.com are built using REST API to provide a SPA that a user interacts with when managing their website.

    This creates a dynamic communication line between the server and interface, resulting in an incredibly user-friendly interface.

    Expect self-hosted WordPress.org sites to mimic this in the near future.

    The Gutenberg block editor is another application that makes use of REST API. It does this by communicating with your database and creating blocks.

    For a post type to work with the Gutenberg block editor, it must have REST API enabled. This means that if you’re trying to register a custom post type using Gutenberg, you will have to add a line that enables the editor for that particular post type:

    "show_in_rest" = true;

    Then there’s the WordPress plugin called Event Espresso. This is a plugin that lets a user organize and publicize their events.

    This plugin uses the REST API to allow users access outside of WordPress. What this means is that you could build SPAs or mobile apps to manage events.

    UsTwo is a well-known digital agency that built their website as a Single Page Application using REST API. The build combines a front-end that uses React and a backend that’s powered by WordPress.

    They have modular content on their single page, with a much different structure than a standard or typical WordPress page. For this, they utilize a custom page builder plugin that allows their design team to include modular content on the site.

    USA Today’s site was rebuilt using WordPress REST API and integrating it with existing modules and systems within the site.

    REST API has allowed the content of the site to be pushed to other media outlets, like Apple News and Facebook Instant Articles, using JSON.

    Recently, they wrote an online social game for the USA Today sports section that was built using JavaScript.

    The Endless Possibilities of WordPress REST API

    As you’re just beginning to see, WordPress REST API is opening up a ton of opportunities within the quickly-growing WordPress ecosystem. And while it presents some interesting challenges, it also opens up an entirely new world of opportunities for WordPress developers and users.

    REST API truly is the future of WordPress. It’s likely to radically change the way you and I develop with, and use, WordPress.

    WordPress REST API

    The post WordPress REST API: A Beginner’s Guide appeared first on iThemes.

    >>> Read the Full Story at iThemes