How to create Custom Rest Resources for GET methods in Drupal 8

One of the biggest changes in Drupal 8 is the integration of Rest services in the core. With use of Views it become very easy to create RESTful Services.

Let's see how can we create Rest Resource using GET method in Drupal 8. 

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 custom module ‘custom_rest’

Module Setup :

custom_rest.info.yml

name: 'Custom Rest API'
type: module
description: 'Create custom rest API'
version: '8.x'
core: '8.x'
project: 'custom'
datestamp: 1524255487
custom_rest.routing.yml

custom_rest.get:
  path: '/my-api/get.json'
  defaults:
   _controller: '\Drupal\custom_rest\Controller\customRestController::getData'
  methods:  [GET] 
  requirements:
   _permission: 'access content'
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\Controller\customRestController.php



/**
 * @file
 * @author Waliullah Khan
 * Contains \Drupal\custom_rest\Controller\customRestController.
 * Please place this file under your custom_rest(module_root_folder)/src/Controller/
 */
namespace Drupal\custom_rest\Controller;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\taxonomy\Entity\Term;
/**
 * Provides route responses for the Example module.
 */

class customRestController extends ControllerBase {
   /**
* Entity query factory.
*
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
protected $entityQuery;

/**
* Constructs a new CustomRestController object.

* @param \Drupal\Core\Entity\Query\QueryFactory $entityQuery
* The entity query factory.
*/
public function __construct(QueryFactory $entity_query) {
$this->entityQuery = $entity_query;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.query')
);
}
/**
* Return the 50 most recently updated nodes in a formatted JSON response.
*
* @return \Symfony\Component\HttpFoundation\JsonResponse
* The formatted JSON response.
*/
    public function getData() {
       // Initialize the response array.
$response_array = [];
$node_query = $this->entityQuery->get('node')
->condition('status', 1)
->condition('type', 'content_type_machine_name')
->sort('changed', 'DESC')
->range(0, 50)
->execute();
         if ($node_query) {
           $response_array[] = [
            'title' => htmlspecialchars($node->title->value),
             
           ] 
         } 
        return $response;
    } 


}

Here in get method we will be defining the logic what we want as output.

That's it! We hope you found this post helpful.

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...