REST API
The WordPress REST API (or simply WP API) allows users (HTTP Clients) to remotely manage the site, for example, to retrieve/create posts, taxonomy items, users, comments, etc. This is done through standard HTTP requests, known as "routes." A JSON object with data is always returned in response to a request.
The REST API was fully added to the core of WordPress in version 4.7.
Brief Overview of REST API (WP API)
The WordPress REST API (hereinafter simply REST API or WP API) is developed based on REST technology to have understandable URLs and use HTTP response codes to indicate successes or errors. It uses built-in HTTP functions such as HTTP authentication and HTTP methods (GET, POST), which can be understood by many HTTP clients. The WP API allows convenient and secure interaction with WordPress from a client application.
REST API:
-
Provides a structured, extensible, and simple way to retrieve or send data to WordPress.
-
Uses JSON as the request and response format, including error responses.
-
Provides different data: public and private (available only after authentication). After authentication, the REST API allows managing site content.
-
Allows working with any programming language that can handle HTTP requests and interpret JSON, such as Node.js or Java.
-
Enables the creation of new ways to manage the site. For example, you can create a plugin that allows site administration or create a completely new interactive interface on the frontend.
- Can replace the way AJAX requests are handled. See: admin-ajax API.
Despite its simplicity, the REST API may seem complex, so studying this topic will be broken down into logical parts, making it easier to master the material. The main complexity lies in the new terminology — these include resources, endpoints, routes. They are necessary for creating and applying standards, but understanding how it works does not require all these terms.
To understand how the REST API works, it is sufficient to:
- Study just one function register_rest_route().
- Familiarize yourself with WP routes.
- Learn to use any client to communicate with the WP API, such as Postman.
Creating a Route
In WordPress, there are predefined routes. You can also create your own by using the register_rest_route() function.
Let's create our own route.
// creating a route add_action( 'rest_api_init', function(){ // namespace $namespace = 'myplugin/v1'; // route $route = '/author-posts/(?P<id>\d+)'; // endpoint parameters (route) $route_params = [ 'methods' => 'GET', 'callback' => 'my_awesome_func', 'args' => [ 'arg_str' => [ 'type' => 'string', // the parameter value must be a string 'required' => true, // the parameter is required ], 'arg_int' => [ 'type' => 'integer', // the parameter value must be a number 'default' => 10, // default value = 10 ], ], 'permission_callback' => function( $request ){ // only authorized user has access to the endpoint return is_user_logged_in(); }, ]; register_rest_route( $namespace, $route, $route_params ); } ); // endpoint handler function (route) function my_awesome_func( WP_REST_Request $request ){ $posts = get_posts( [ 'author' => (int) $request['id'], ] ); if ( empty( $posts ) ) { return new WP_Error( 'no_author_posts', 'No records found', [ 'status' => 404 ] ); } return $posts; }
Now, by visiting the link http://example.com/wp-json/myplugin/v1/author-posts/1
, we will see the JSON response returned by our function my_awesome_func().
Code explanations:
-
The route must be registered specifically on the rest_api_init hook to avoid performing any operations if the REST API is disabled.
-
Why the namespace is called
myplugin/v1
, read here. -
The route
/author-posts/(?P<id>\d+)
is specified as a regular expression to determine the number, so that the URL/author-posts/123
returns posts by the author with ID 123. -
A GET request to the URL
http://example.com/wp-json/myplugin/v1/author-posts/1
is the endpoint we described when registering the route.The route can have multiple endpoints, and different parameters can be specified for each endpoint:
- methods — HTTP methods to be used for accessing the endpoint
- callback — callback function for responding to the request
- permission_callback — callback function for checking access rights to the endpoint.
- args — request parameters that can be passed to the endpoint. Each parameter is described as an array element. Each parameter can have its own options, such as whether it is required (required) or the default parameter value (default), and a value validation function (validate_callback). For more details, see the section Parameter Types.
For more details on creating routes, read the section Creating a Route.
Key Concepts of REST API
See the section Basic Knowledge of REST API.
You need to understand each concept to comprehend what is written and what this guide is about!
How to Determine if the Current Request is a REST Request
You can check for the presence of the constant REST_REQUEST
:
if( defined('REST_REQUEST') ){ // This is a REST request }
IMPORTANT! This constant is declared quite late on the parse_request hook (the order of hooks see here), so there is no way to know if it is a REST request until this hook.
The only option to do this before this hook is to write a custom check, for example, by checking the current URI:
if( rest_get_url_prefix() === explode( '/', $_SERVER['REQUEST_URI'] )[1] ?? '' ){ // this is a REST request }
For more details on the stages of loading REST read here.
PHP SDK for Convenient Work with WordPress REST API
https://github.com/madeITBelgium/WordPress-PHP-SDK
The library is installed via composer. Example usage:
use MadeITBelgium\WordPress\WordPressFacade as WP; $users = WP::post()->list(); // list of posts $result = WP::post()->create( $data ); // create a new post $user = WP::post()->get( $id ); // record by ID $result = WP::post()->update( $id, $data ); // update record $result = WP::post()->delete( $id ); // delete record
Useful Links
- Postman — Client for communicating with WP API.
- REST API Handbook — official guide to the REST API (in English).
- Changelog for REST API
- JSON Formatter — a small Chrome extension for conveniently reading JSON responses.
- JsonDiscovery — a more powerful Chrome extension for conveniently reading JSON responses.
- REST API Seminar (video)
- WP REST API Changelog
--
This section was created based on the official guide: REST API Handbook. However, we simplify/clarify/improve/restructure the content as much as possible, provide examples, and ultimately strive to present the information more clearly.