Drupal - How to enable endpoint without RESTUI module?

Ok, I finally found out how to enable an endpoint to be accessible without RESTUI module. This gives more flexibility to keep everything in code and one custom module.

This instructions applies to Drupal > 8.2 only.

First you need to know how to create a custom rest resource, which can be found here or here.

So, let's say we have a custom module named 'custom_rest' that contains REST plugin resource. Module returns only a single node json data. The structure of the module looks like this:

|custom_rest
|--|config
|  --|optional
|      --rest.resource.custom_rest_resource.yml
|--|src
|  |--Plugin
|     |--rest
|        |--resource
|           --CustomRestResource.php
|--custom_rest.info.yml
|--custom_rest.module

The most important files for us are:

 -  CustomRestResource.php
 -  rest.resource.custom_rest_resource.yml

CustomRestResource.php is a plugin with the custom rest resource. My get method looks like this:

  public function get($nid) {
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }
    $data = node_load($nid);
    return new ResourceResponse($data);
  }

This method returns a json node structure for an existing node. That's it, it's just for testing purposes only. It can do anything you want.

As for the enabling an endpoint it needs an extra yml file that should be located in:

/custom_rest/config/optional/rest.resource.custom_rest_resource.yml

The contents of the rest.resource.custom_rest_resource.yml file for this particular endpoint looks like this:

langcode: en
status: true
dependencies:
  module:
    - custom_rest
    - hal
    - serialization
    - user
id: custom_rest_resource
plugin_id: custom_rest_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - hal_json
      - json
      - xml
    supported_auth:
      - cookie

Of course, the name of the file, dependencies, id, plugin_id, configuration should be adjusted to your needs.

If you have all of this and you will enable the module this endpoint should be accessible in browser or any app that handles http requests (postman, etc.).

Notice that this yml file won't be triggered if you already enabled the module. If you've added this file after module enable, you should uninstall the module and enable it again.

Tags:

8