Rest API Controllers

Introduction

Onyx offers a simple RestController class to facilitate the WordPress's REST API's. See more information at register_rest_route() and custom endpoints

All REST API controllers are created inside the ./core/app/Api folder, with the namespace Onyx\Controllers and extend the Onyx\RestController class.


Registering

After creating the controller, it is necessary to register it in ./core/config/rest.php as in the example below.

namespace Onyx\Controllers;
return [
ExampleRestController::class,
MyOtherRestController::class,
];

Parameters and Methods

VariableTypeDescriptionRequired
$namespacestring/arrayRoute Namespace

It is required to set the namespace property as well as initialize the $this->initialize() method as we can see in the following example.

Helpers Methods


Creating a REST API Controller

In this example we will create the endpoint /(api|wp-json)/onyx/v1/example with the POST and GET methods.

namespace Onyx\Controllers;
use \Onyx\RestController;
class ExampleRestController extends RestController {
/**
* The namespace for the rest endpoint api
*
* @var string
*/
protected $namespace = 'onyx/v1';
/**
* Constructor
*
* @return void
*/
public function __construct() {
$this->initialize();
}
/**
* Register routes
*
* @return void
*/
public function register_routes() {
// register examples routes
$this->route( 'POST', '/example', 'generic_callback' );
$this->route( 'GET', '/example', 'generic_callback' );
}
/**
* Generic Callback
*
* @param \WP_REST_Request $req
* @return \WP_REST_Response|mixed
*/
public function generic_callback( \WP_REST_Request $req ) {
return rest_ensure_response( $req->get_params(), 200 );
}

Methods Helpers

route()

VariableTypeDescriptionRequired
$methodWP_Rest_Server/mixed(GET, POST, PUT, PATCH, DELETE)
$routestringRoute endpoint
$callbackcallableController callback method to execute
$optionsarrayEndpoint options
$overrideboolReplace existing route. Default: falso

@return bool
@throws \Exception If the $namespace does not exist

rest_response()

Alias for \WP_REST_Response