Skip to content

REST API

A REST API lets external clients and JavaScript on the page read and write data over HTTP without a full page load.

The REST API is disabled by default. Run the activate command to enable it and scaffold an example endpoint:

Terminal window
wp instance activate rest-api

This sets enabled => true in config/rest-api.php and creates app/RestAPI/ExampleRestAPI.php.

Use the generate command to scaffold a new endpoint class:

Terminal window
wp instance make rest-api Cats
# → app/RestAPI/CatsRestAPI.php

Or create it manually in app/RestAPI/:

  • Directorylumbermill
    • Directoryapp
      • DirectoryRestAPI
        • CatsRestAPI.php
<?php
namespace App\RestAPI;
use WP_REST_Request;
use WP_REST_Response;
class CatsRestAPI
{
public function hi(WP_REST_Request $request): WP_REST_Response
{
return new WP_REST_Response([
'message' => 'Miauw!'
]);
}
}

Add the route to config/rest-api.php:

<?php
use App\Lib\Enum\HTTPMethodsEnum;
return [
'enabled' => true,
'routes' => [
'lumbermill/v1' => [
'cats' => [
'methods' => HTTPMethodsEnum::GET,
'callback' => [new App\RestAPI\CatsRestAPI, 'hi'],
],
],
],
];

Visit https://your-site.ddev.site/wp-json/lumbermill/v1/cats to test it:

{
"message": "Miauw!"
}
MethodEnum valueDescription
GETHTTPMethodsEnum::GETRead a resource
POSTHTTPMethodsEnum::POSTSend data to the server
PUT, PATCHHTTPMethodsEnum::PUTUpdate an existing resource
DELETEHTTPMethodsEnum::DELETEDelete a resource
GET, POST, PUT, PATCH, DELETEHTTPMethodsEnum::ALLAllow all methods
async function sayHi() {
const response = await fetch(
window.LUMBERMILL_GLOBAL.rest_routes.lumber_mill_v1_cats
);
const json = await response.json();
console.log(json); // {message: 'Miauw!'}
}
sayHi();