
In one of the earlier blog post we had explored, How to create Custom Rest Resources for POST methods in Drupal 8. Let's see how can we create Rest Resource using GET method in Drupal 8.
RESTful services were introduced in Drupal 8 into the core, this was inspired by Drupal 7. With Drupal 8 REST, you can enable other websites or applications to view, edit or update information. REST, among other Drupal 8 web services like XML and JSON is a method to provide customizable data in the form of API.
Normally we can use view but here we will be learning how to create drupal 8 REST using custom code.
So let’s create an example module ‘example_rest’
Module Setup :
Example_rest.info.yml
name: Example Rest | |
type: module | |
description: Example module Rest service. | |
core: 8.x | |
package: Example |
Now we will be defining the rest resource. In this we will be fetching all the existing node title in the existing drupal.
Let’s create rest resource with GET method.
src\Plugin\rest\resource\ExampleGetRestResource.php
<?php | |
namespace Drupal\example_rest\Plugin\rest\resource; | |
use Drupal\Core\Session\AccountProxyInterface; | |
use Drupal\rest\Plugin\ResourceBase; | |
use Drupal\rest\ResourceResponse; | |
use Symfony\Component\DependencyInjection\ContainerInterface; | |
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; | |
use Psr\Log\LoggerInterface; | |
/** | |
* Provides a resource to get view modes by entity and bundle. | |
* | |
* @RestResource( | |
* id = "example_get_rest_resource", | |
* label = @Translation("Example get rest resource"), | |
* uri_paths = { | |
* "canonical" = "/example-rest" | |
* } | |
* ) | |
*/ | |
class ExampleGetRestResource extends ResourceBase { | |
/** | |
* A current user instance. | |
* | |
* @var \Drupal\Core\Session\AccountProxyInterface | |
*/ | |
protected $currentUser; | |
/** | |
* Constructs a Drupal\rest\Plugin\ResourceBase object. | |
* | |
* @param array $configuration | |
* A configuration array containing information about the plugin instance. | |
* @param string $plugin_id | |
* The plugin_id for the plugin instance. | |
* @param mixed $plugin_definition | |
* The plugin implementation definition. | |
* @param array $serializer_formats | |
* The available serialization formats. | |
* @param \Psr\Log\LoggerInterface $logger | |
* A logger instance. | |
* @param \Drupal\Core\Session\AccountProxyInterface $current_user | |
* A current user instance. | |
*/ | |
public function __construct( | |
array $configuration, | |
$plugin_id, | |
$plugin_definition, | |
array $serializer_formats, | |
LoggerInterface $logger, | |
AccountProxyInterface $current_user) { | |
parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger); | |
$this->currentUser = $current_user; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { | |
return new static( | |
$configuration, | |
$plugin_id, | |
$plugin_definition, | |
$container->getParameter('serializer.formats'), | |
$container->get('logger.factory')->get('example_rest'), | |
$container->get('current_user') | |
); | |
} | |
/** | |
* Responds to GET requests. | |
* | |
* Returns a list of bundles for specified entity. | |
* | |
* @throws \Symfony\Component\HttpKernel\Exception\HttpException | |
* Throws exception expected. | |
*/ | |
public function get() { | |
// You must to implement the logic of your REST Resource here. | |
// Use current user after pass authentication to validate access. | |
if (!$this->currentUser->hasPermission('access content')) { | |
throw new AccessDeniedHttpException(); | |
} | |
$entities = \Drupal::entityTypeManager() | |
->getStorage('node') | |
->loadMultiple(); | |
foreach ($entities as $entity) { | |
$result[$entity->id()] = $entity->title->value; | |
} | |
$response = new ResourceResponse($result); | |
$response->addCacheableDependency($result); | |
return $response; | |
} | |
} |
Here in get method we will be defining the logic what we want as output.
As example we are loading all node present in the drupal installation and return node title as key value pair. Node id will be key and title will be respective value.
Let’s enable the module and Drupal rest api.
This module will be dependent on Rest and Drupal Rest UI module so we need to enable these two module as well. Rest is included in drupal core but drupal 8 Rest UI is a contributed module so we need to download and enable it.
Once we enable all required module we need to enable our rest api.
1.Goto admin/config/services/rest
2.Search for rest api (in our case its “Example get rest resource”) and enable it.
3.Once you click on enable it will open the setting page of the respective api we need to select Get and Supported formats as xml, Authentication providers as cookie.
4.Click on “save config”
5.Now goto /example-rest?_format=xml
Result :