0

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:

<?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' => '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
  • 1
    The error suggests you have two copies of the same file, in different modules. If not, run composer dump-autoload; drush cr and try again – Clive May 21 '18 at 13:48
  • Unfortunately it didn't work (no change). I have added the REST resource YML content if it helps. – Ynhockey May 22 '18 at 9:11
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.