Class declaration error when using ResourceBase I tried following this guide: https://www.drupal.org/docs/8/api/restful-web-services-api/custom-rest-resources for the REST API.

However, when enabling the module, I get:


  Fatal error: Cannot declare class Drupal\my_module_rest_api\Plugin\rest\resource\MyModuleResource, because the name is already in use in [PATH]\modules\my_module\src\Plugin\rest\resource\MyModuleResource.php on line 0


It seems like it could be a simple class naming error, but I really tried following the guide to a tee. Here is MyModuleResource.php in full:

&lt;?php

namespace Drupal\my_module_rest_api\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a REST API Resource
 *
 * @RestResource(
 *   id = "my_module_resource",
 *   label = @Translation("My Module Resource"),
 *   uri_paths = {
 *     "canonical" = "/my_module_rest_api/my_module_resource"
 *   }
 * )
 */
class MyModuleResource extends ResourceBase {

    /**
     * Responds to entity GET requests.
     *
     * @return \Drupal\rest\ResourceResponse
     */
    public function get() {
        $response = ['message' =&gt; 'Hello, this is a rest service'];
        return new ResourceResponse($response);
    }
}


Here is the rest.resource.my_module_resource.yml file:

id: my_module_resource
plugin_id: my_module_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - json
    supported_auth:
      - basic_auth
It looks like the problem was not with the REST API routes, but with the module name vs. namespace: in trying to pay attention to the details of the REST API extension, I missed that my module name was different from the namespace. In the above example, the module name is


  my_module


while the namespace is


  Drupal\my_module_rest_api\Plugin\rest\resource