One of the most interesting possibilities of using WordPress as a platform for developing apps is the flexibility for creating new Rest API endpoints and services.
However, even though the way you can create new custom routes and endpoints is somewhat easy to understand on WordPress, things become messy when you think of a system or website with dozens of new API services and endpoints.
If you are looking for something more organized and neat and, at the some time, more powerful API uses, then you’d better extend and sophisticate the existent methods and routing tools.
Fortunately for you, WP Helpers already built something like that. But more than just add here a link for a repo, we will be explaining the whole idea that led to the library we’ve working at.
Not so complicated…
Yeah. WordPress’ approach to create new endpoints is not really complex, but then again, we need to evaluate the whole coding. Considering a single custom endpoint, with nothing but the method and indication for its callback function, it looks really easy.
add_action( 'rest_api_init', function () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
) );
} );
Things get trickier though when we think about the whole picture. If we add ten new routes, that means we’ll need ten different callbacks. If we don’t use an anonymous function, it implies in more work obviously. And then, we need to consider two other factor involved: the permissions callback and the possible arguments for each of the new endpoints.
That makes our code confusing, exposes it to mistakes and takes a path that leads us far from the best practices in PHP. But this is not the end of the story: let’s say we want to operate with classes rather than callback functions. That means we’ll be building controllers to those endpoints, and callbacks and permissions, maybe in every single case.
add_action( 'rest_api_init', 'custom_endpoints' );
function custom_endpoints () {
register_rest_route( 'myplugin/v1', '/author/(?P<id>\d+)', array(
'methods' => 'GET',
'callback' => 'my_awesome_func_1',
) );
register_rest_route( 'myplugin/v1', '/other', array(
'methods' => 'POST',
'callback' => 'my_awesome_func_2',
) );
register_rest_route( 'myplugin/v1', '/yetanother', array(
'methods' => 'PUT',
'callback' => 'my_awesome_func_3',
) );
} );
function my_awesome_func_1($request) {
return $response;
}
function my_awesome_func_2($request) {
return $response;
}
function my_awesome_func_3($request) {
return $response;
}
// Don't forget the permissions_callback, and perhaps
// some other functions to deal with API responses
Now stop. Why are we talking about that? Well, thinking of this situation and considering multiple endpoints, we started working in a simple but efficient OOP way of dealing with WP custom endpoints. Furthermore, and that was one of the first things that came to our minds: what if we had controllers being automatically generated for all of those callbacks – and then we had all of them autoloaded?
A library to organize it
If WordPress is PHP-based, so using Composer is always a shortcut. And that’s exactly what we do – there is no point in creating a “developers plugin” – if something is built for PHP devs, it makes much more sense if it’s a library or dependency.
So what we intented to manage with this project? Well, we had three main topics in mind:
- Add new endpoints, including those with multiple HTTP methods, in a single line.
- Automate the callback controllers (in classes rather than functions), and make it in a well-organized and neat way.
- Generate those classes and automatically load them.
The result has been a library that can actually meet all of those requirements, while implementing some logic to the callback methods, which is usually overseen by many plugin developers. Yes, we are still working and maintaining this library, but the current version can already be required in any plugin or theme using Composer.
wp-endpoint-gen (this link opens in a new window) by carloswph (this link opens in a new window)
WordPress custom endpoints helper and class generator.
In brief, this library uses two distinct classes: a configurator and a generator. The class Config allows the user to set the endpoint namespace, the path where the generated classes will be created and also a namespace for those classes. Something like:
use WPH\Endpoints\Config;
require __DIR__ . '/vendor/autoload.php';
$config = new Config(); // Config class instance.
$config->setPsr('Foo'); // Sets generated classes' namespaces as Foo
$config->setPath( WP_CONTENT_DIR . '/foo'); // Creates and sets the generated classes' path
$config->setVersion('v1.2'); // Sets a new version for all endpoints
$config->setNamespace('foo-api'); // Sets a new namespace for the WP API endpoints
Once the configuration is done, this first class is injected into the class Generator, which gets two other argumentos: the endpoint name and the respective request methods. Endpoints set up and running, so the only thing you still need to do is generate the callback classes and autoload them, like this:
// $config as the previous instance of the Config() class
$gen = new Generator('wph-endpoint', ['GET', 'PUT'], $config);
$gen->generate();
$gen->autoload();
Take a look in the Github repo and use it and contribute. The library can be either cloned or installed using Composer: composer require carloswph/wp-endpoint-gen