REST API
A REST API lets external clients and JavaScript on the page read and write data over HTTP without a full page load.
Getting started
Section titled “Getting started”The REST API is disabled by default. Run the activate command to enable it and scaffold an example endpoint:
wp instance activate rest-apiThis sets enabled => true in config/rest-api.php and creates app/RestAPI/ExampleRestAPI.php.
Creating a route
Section titled “Creating a route”Use the generate command to scaffold a new endpoint class:
wp instance make rest-api Cats# → app/RestAPI/CatsRestAPI.phpOr 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!' ]); }}Register the route
Section titled “Register the route”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!"}Methods
Section titled “Methods”| Method | Enum value | Description |
|---|---|---|
| GET | HTTPMethodsEnum::GET | Read a resource |
| POST | HTTPMethodsEnum::POST | Send data to the server |
| PUT, PATCH | HTTPMethodsEnum::PUT | Update an existing resource |
| DELETE | HTTPMethodsEnum::DELETE | Delete a resource |
| GET, POST, PUT, PATCH, DELETE | HTTPMethodsEnum::ALL | Allow all methods |
Consuming the API from JavaScript
Section titled “Consuming the API from JavaScript”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();
