Why is my custom API endpoint not working?

Maybe start with just GET. Your route looks weird as well. Try just:

register_rest_route('my-project/v1', '/action/', [
  'methods'  => WP_REST_Server::READABLE,
  'callback' => 'api_method',
]);

And your callback is not returning a valid response. Let your callback look more like this:

$data = [ 'foo' => 'bar' ];

$response = new WP_REST_Response($data, 200);

// Set headers.
$response->set_headers([ 'Cache-Control' => 'must-revalidate, no-cache, no-store, private' ]);

return $response;

Finally you must combine wp-json, the namespace my-project/v1 and your route action to the URL you now can check for what you get:

 https://my-domain.local/wp-json/my-project/v1/action

Leave a Comment