WP_REST_Server::get_namespace_index PHP Method

get_namespace_index() public method

Retrieves the index for a namespace.
Since: 4.4.0
public get_namespace_index ( WP_REST_Request $request ) : WP_REST_Response | WP_Error
$request WP_REST_Request REST request instance.
return WP_REST_Response | WP_Error WP_REST_Response instance if the index was found, WP_Error if the namespace isn't set.
    public function get_namespace_index($request)
    {
        $namespace = $request['namespace'];
        if (!isset($this->namespaces[$namespace])) {
            return new WP_Error('rest_invalid_namespace', __('The specified namespace could not be found.'), array('status' => 404));
        }
        $routes = $this->namespaces[$namespace];
        $endpoints = array_intersect_key($this->get_routes(), $routes);
        $data = array('namespace' => $namespace, 'routes' => $this->get_data_for_routes($endpoints, $request['context']));
        $response = rest_ensure_response($data);
        // Link to the root index.
        $response->add_link('up', rest_url('/'));
        /**
         * Filters the namespace index data.
         *
         * This typically is just the route data for the namespace, but you can
         * add any data you'd like here.
         *
         * @since 4.4.0
         *
         * @param WP_REST_Response $response Response data.
         * @param WP_REST_Request  $request  Request data. The namespace is passed as the 'namespace' parameter.
         */
        return apply_filters('rest_namespace_index', $response, $request);
    }

Usage Example

 public function test_get_namespace_index()
 {
     $server = new WP_REST_Server();
     $server->register_route('test/example', '/test/example/some-route', array(array('methods' => WP_REST_Server::READABLE, 'callback' => '__return_true'), array('methods' => WP_REST_Server::DELETABLE, 'callback' => '__return_true')));
     $server->register_route('test/another', '/test/another/route', array(array('methods' => WP_REST_Server::READABLE, 'callback' => '__return_false')));
     $request = new WP_REST_Request();
     $request->set_param('namespace', 'test/example');
     $index = rest_ensure_response($server->get_namespace_index($request));
     $data = $index->get_data();
     // Check top-level.
     $this->assertEquals('test/example', $data['namespace']);
     $this->assertArrayHasKey('routes', $data);
     // Check we have the route we expect...
     $this->assertArrayHasKey('/test/example/some-route', $data['routes']);
     // ...and none we don't.
     $this->assertArrayNotHasKey('/test/another/route', $data['routes']);
 }