Thursday, July 20, 2017

A Quick Start Guide To The WordPress REST API

The web has grown quite a bit over the last decade, and WordPress has fallen behind ever so slightly. More and more applications are being brought to the web with JavaScript, and more and more dynamic websites are being built with languages like Python and Ruby.

The developers of WordPress core, and even a few professional WordPress developers, feel that WordPress' heavy reliance on PHP and minimal use of JavaScript has become far too outdated. This is something the WordPress REST API is meant to solve.

This doesn't mean WordPress is moving away from PHP, but it does mean developers should consider learning JavaScript if they want to take advantage of what this API has to offer.

What is the WordPress REST API?

The REST API is not a new concept. In fact, Roy Fielding defined the term "representational state transfer" in the year 2000 when he used it to design HTTP 1.1 and Uniform Resource Identifiers, better known as "URIs."

You probably already know that APIs are the structure of software applications that contain sets of tools and protocols developers can use to build those applications. REST API is similar to that except it performs its requests and receive its responses through HTTP protocol.

Regular APIs typically use PHP, Python and Ruby to build applications. You can use other languages, but these are the most popular. REST APIs, through the use of HTTP protocol, make it easier to utilize other programming languages, such as JavaScript.

WordPress REST API

I've already explained how WordPress REST API is more about moving WordPress closer to where the rest of the web is and less about moving away from PHP. It's about making it easier for developers to use languages like JSON and JavaScript so WordPress can become a fully-fledged platform capable of being used to build much more than traditional websites and blogs.

Here's WordPress' explanation of incorporating JSON in the WordPress REST API:

The WordPress REST API provides API endpoints for WordPress data types that allow developers to interact with sites remotely by sending and receiving JSON (JavaScript Object Notation) objects. JSON is an open standard data format that is lightweight and human-readable, and looks like Objects do in JavaScript; hence the name. When you send content to or make a request to the API, the response will be returned in JSON. This enables developers to create, read and update WordPress content from client-side JavaScript or from external applications, even those written in languages beyond PHP.

It's essentially designed to bridge the gap between the PHP WordPress core is built on and the JavaScript many web applications use today. The infrastructure for the WordPress REST API was added to WordPress core in version 4.4 (codename "Clifford") in December 2015. You needed a plugin to use the REST API at that time. However, the rest of this API, the content endpoints to be exact, was added to WordPress core in version 4.7 (codename "Vaughan") in December 2016, negating the need for the WP REST API plugin.

How the WordPress REST API works

In order to understand how the WordPress REST API works, you need to understand how HTTP requests and responses work. When you enter a URL in the address bar of a browser, that's a request. When the server displays the website or application for that URL, that's a response.

You'll see a few different types of requests or "HTTP methods" when you start using the WordPress REST API. Here are the four main types of HTTP methods the web uses:

  • GET – Used to retrieve data from the server
  • POST – Used to send data to the server
  • PUT – Used to change or update data on the server
  • DELETE – Used to remove data from the server
  • With those simple definitions in mind, entering a URL in a browser is a GET request. Entering your login information for a website is a POST request. Changing your current password to a new one is a PUT request while terminating your account is a DELETE request.

    Additional terms you'll notice are "routes" and "endpoints." A route is typically the URL or a part of the URL you're trying to access while an endpoint is typically the response you receive from the server.

    When external sources send HTTP requests to the server hosting your WordPress site, the REST API exposes your data in a secure manner by responding to those requests with a common architecture and its own set of protocols.

    This allows WordPress content, such as posts, pages, and comments, to be processed as raw data. We'll get a glimpse of this in a minute. The overall point of this is to allow you to make changes to your site's content without having to access the WordPress admin area. This is how you can make changes to your site using JSON whose responses give developers a number of different ways to interact with their sites.

    Let's get our hands a little dirty to see how this all works.

    Using WordPress REST API

    We're going to get into how to actually use the WordPress REST API, but unfortunately, there are a few key concepts we need to go over first so it all makes sense. Here are the key concepts that make up this API:

  • Routes & Endpoints
  • Requests
  • Responses
  • Schema
  • Controller Classes
  • Let's get to it.

    Routes & Endpoints

    The technical definition of a route is a URL that can be mapped through different HTTP methods. The mapping between a route and an HTTP method is called an "endpoint." You can access the WordPress REST API and see which routes and endpoints are available for your site by adding the route "/wp-json/" to the end of your URL.

    You can see this at WordPress.org by visiting https://www.wordpress.org/wp-json/:

    WordPress WP Json

    Install an extension called JSON Viewer for Chrome (JSON viewer for Firefox available here) to clean this mess up:

    WordPress WP Json Clean

    If you don't use pretty permalinks, use "?rest_route=" instead of "wp-json". Either way, what you're seeing here is an example of a route and an endpoint. "/wp-json/" and "/?rest_route=/" are routes. They allow you to access the WordPress REST API through the GET HTTP method. The WordPress REST API displayed to you, or the data if you will, is an endpoint served to us via a JSON response.

    Requests

    The WordPress REST API processes requests with a class named WP_REST_Request. It's a primary class in the WordPress REST API infrastructure. It's used to store and retrieve information for all of the requests you make.

    You can send requests remotely using the HTTP methods we went over or you can make them internally as you normally would via PHP.

    Responses

    Responses are processed with the WP_REST_Response class. A response is the data you receive from a request, as stated before. The API uses this class to return data sent from endpoints. It can also return errors.

    Schema

    Schema is a concept inside of the WordPress REST API that serves a variety of purposes. API schema defines the data structures endpoints can use, and it contains a list of the properties the WordPress REST API can return. It also contains the parameters the API can accept and provides security for it by validating the requests the API receives.

    Controller Classes

    The WordPress REST API registers routes and endpoints, handles requests, utilizes Schema to define the data and properties it can use, and generates API responses on top of all of that. The API, and you as the developer, needs a way to manage all of these moving parts. That's what controller classes are for. They allow you to gather all of these elements and organize them in a single place.

    Using the WordPress REST API to access your content through endpoints

    A route is the URL you use to access an endpoint, and an endpoint is the response you receive from the server. If you want to get your site's posts through the WordPress REST API, use the route "/wp/v2/posts/". WordPress explains that "/wp-json/" isn't included in these longer routes because it's the "base path for the API itself." The ending URL is "example.com/wp-json/wp/v2/posts".

    If you want to access a specific post through the API, simply add the post's ID to the end of the URL so it looks like this: "example.com/wp-json/wp/v2/posts/123"

    If you want to search for posts that use a specific phrase or keyword, use this route: "/wp/v2/posts?=search[ insert keyword here]" so the URL looks like this: "example.com/wp-json/wp/v2/posts?search[insert keyword here].

    If you want to access a specific user's profile through the API, add "/users/" to the route as well as that user's user ID. The URL looks like this: "example.com/wp-json/wp/v2/users/2". Similarly, if you want to access a site's users, drop the ID so the URL looks like this: "example.com/wp-json/wp/v2/users/".

    You can view more endpoints here.

    Extending the REST API

    We're going to skip a few steps and learn how to use the properties of the REST API to extend it. You should learn about things like global parameters, pagination, linking and embedding, and authentication before doing this, but we're going to skip ahead for the purposes of this quickstart guide.

    Here are a few things you can accomplish by extending the REST API:

  • Add Custom Endpoints
  • Create Routes for Custom Post Types and Custom Taxonomies
  • Modify Responses
  • If you're an experienced developer, you're likely already familiar with the concepts required to add a custom endpoint to the REST API. It's just a matter of learning how to connect the two.

    You'll start off by creating a function that can be simple or complicated depending on the sophistication of the functionality you're trying to add to the REST API. Here's the simple function WordPress provides in their handbook, a function designed to grab the titles of your site's latest posts by author:

    <?php /** * Grab latest post title by an author! * * @param array $data Options for the function. * @return string|null Post title for the latest,
 * or null if none. */ function my_awesome_func( $data ) { $posts = get_posts( array( 'author' => $data['id'], ) ); if ( empty( $posts ) ) { return null; } return $posts[0]->post_title; }

    After that, you'll need to register a route to make this function available to the API by using another function called register_rest_route. Here's the function WordPress uses to register the route for the previous function:

    <?php add_action( 'rest_api_init', function () { register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array( 'methods' => 'GET', 'callback' => 'my_awesome_func', ) ); } );

    There are a couple of things happening here. First, there are three properties passing through this function. They are the namespace ("myplugin/v1"), the route we need to register ("my_awesome_func") and the options we want to use ("author/(?P<id>\d+)"). The register_rest_route function is also being called on a callback function called "rest_api_init". This cuts back on the amount of unnecessary work that's performed when the API isn't being used.

    As WordPress explains, this route is designed to match anything with "/author/{id}" where "{id}" is an integer. This is the URL you would visit to use this route – http://example.com/wp-json/myplugin/v1/author/(?P\d+). This specific route uses one endpoint, but routes are capable of having multiple endpoints. You can see we also defined the HTTP method this endpoint would use.

    Other concepts you'll need

    There are a few additional concepts you'll need to learn if you want to extend the REST API, provided you're not already familiar with them. We used a namespace in the function above, which is why the first part of the URL above is "myplugin/v1". They're used as prefixes to prevent clashes with custom routes.

    Arguments are another concept you should be familiar with as they allow you to run sanitization and validation by registering them when you register routes. You should also familiarize yourself with return values as this is what you'll use to define the type of response you receive from the server. You can even use them to return errors, such as a 404 error that's displayed if an author hasn't published any posts.

    Callbacks are another concept you should know, such as functions known as permissions callbacks that check whether or not a user is able to perform an action before the function attempts to call the actual callback. Finally, familiarizing yourself with internal classes and controller patterns will help you manage every aspect of the endpoints you create.

    Final thoughts & where to go from here

    Understanding the key concepts of the WordPress REST API and learning how to use and extend it can be overwhelming, but the makers of WordPress are fairly confident it'll be the force the CMS in ways it needs to grow far beyond its capabilities as a platform to build simple websites and blogs.

    Learning JavaScript should be a top priority right now, as stated before, as this is the language the makers of WordPress want developers to incorporate more often in WordPress projects.

    You should also go through the WordPress REST API handbook to gain a better understanding of WordPress' take on the REST API. The Using the REST API section contains guides on how to use global parameters, pagination, embedding and linking, and authentication, which are all key concepts of this API.

    Once you've gained a pretty good understanding of all of that, you can go through the Extending the REST API section to learn how to extend the API in depth. You'll learn more about adding custom endpoints and will also learn how to use custom content types and modify responses.


    Source: A Quick Start Guide To The WordPress REST API

    No comments:

    Post a Comment