Học Creating a custom RESTful Web Service tại Drupal 9

Học Creating a custom RESTful Web Service tại Drupal 9

The web is progressing and it has become quite intense for interaction between clients and websites or apps, multiple sites, databases and devices. For that the internet was demanding a new technology. One such technology which can handle this type of interaction is REST.

Before creating our own custom REST API in Drupal, we need to know what REST API actually is? It is an application programming interface (API or web API) that allows interaction with RESTful web services. Where, REST is known as REpresentational State Transfer, which was defined by Computer Scientist “Roy Fielding”.

While designing APIs, there is always a need to specify which HTTP method will be used for performing CRUD operations on data. Here, it can be made possible by using several HTTP requests like POST (Create the data), GET (Retrieve/Read the data), DELETE (Delete the data) or PATCH/PUT (Update the data). To learn how to create custom web services, we would create a custom module exposing RESTful API which can display a list of taxonomy terms from our Drupal 9 site.

Step 1

Create a custom module in the “\web\modules\custom” folder.

Folder structure to be followed while creating a custom module in Drupal 8/9

Step 2

Create an info.yml file as “sample_rest_resource.info.yml” along with a blank module file as "sample_rest_resource.module"

name: Sample Rest Resource
type: module
description: Module for implementing Custom Rest Service.
core_version_requirement: ^8.8 || ^9
package: Example

Now the folder structure will look like this:

Folder structure after adding info.yml and module file to a module in Drupal 8/9

We are now moving forward towards implementation of a rest resource using the GET method. By GET method, we need to fetch the list of taxonomy term “vb”.

Step 3:

Create a folder structure in the custom module as “src\Plugin\rest\resource”.

The folder structure will look like this:

Folder structure to be followed after creating subfolders for rest resource in Drupal 8/9

Step 4

We will implement our resource file. For that, create a php file as “SampleGetRestResource.php” and place the file in the “resource” folder.

<?php

namespace Drupal\sample_rest_resource\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Psr\Log\LoggerInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
/**
 * Provides a resource to get view modes by entity and bundle.
 * @RestResource(
 *   id = "custom_get_rest_resource",
 *   label = @Translation("Custom Get Rest Resource"),
 *   uri_paths = {
 *     "canonical" = "/vb-rest"
 *   }
 * )
 */
class SampleGetRestResource extends ResourceBase {
  /**
   * A current user instance which is logged in the session.
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $loggedUser;
  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $config
   *   A configuration array which contains the information about the plugin instance.
   * @param string $module_id
   *   The module_id for the plugin instance.
   * @param mixed $module_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 currently logged user instance.
   */
  public function __construct(
    array $config,
    $module_id,
    $module_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($config, $module_id, $module_definition, $serializer_formats, $logger);

    $this->loggedUser = $current_user;
  }
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $config, $module_id, $module_definition) {
    return new static(
      $config,
      $module_id,
      $module_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('sample_rest_resource'),
      $container->get('current_user')
    );
  }
  /**
   * Responds to GET request.
   * Returns a list of taxonomy terms.
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   * Throws exception expected.
   */
  public function get() {
    // Implementing our custom REST Resource here.
    // Use currently logged user after passing authentication and validating the access of term list.
    if (!$this->loggedUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }    
    $vid = 'vb';
    $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
    foreach ($terms as $term) {
      $term_result[] = array(
        'id' => $term->tid,
        'name' => $term->name
      );
    }

    $response = new ResourceResponse($term_result);
    $response->addCacheableDependency($term_result);
    return $response;
  }

}

We’re using the “GET” method in the template, in which we define our logic in the form of code to define what output is required. As an example- we require all the existing terms title with their respective IDs for “vb (machine name of Vb Test)” taxonomy for currently logged user.

Step 5

We have created a “Vb Test” taxonomy and added two terms in that.

Taxonomy added in our site which terms we will be listing using our custom resource

Taxonomy terms are added to the vocabulary

Step 6

Now let's first enable Drupal REST API which is provided by core itself.

Our module will be dependent upon the Rest and Rest UI module. The Rest UI module can be installed using this command:

“composer require 'drupal/restui:^1.20'”

After installing the RestUI module, enable both the modules and follow the snapshots attached to configure REST API.

Enable RestUI and Restful Web Service module for implementing our custom rest resource

Step 7

Let’s enable our custom module now.

Enabling our custom module for implementation of custom rest resource

Step 8

After enabling the custom module, enable custom rest resource.

For enabling custom rest resource, follow these steps:-

1. Go to “/admin/config/services/rest”.

2. Search for our custom rest resource using the id that we have created in the resource file. Here it is “Custom Get Rest Resource”

Enable our custom rest resource in configuration

3. Enable the custom rest resource and do the following configuration. Hit “Save Configuration”.

Follow these changes to get your rest resource start working

Rest Resource is enabled and now ready to fetch data

4. Now go to “/vb-rest?_format=json” and the URL will result in a Taxonomy term list containing Term ID and title.

Output of custom rest resource shows the list of taxonomy terms

So we have seen REST can be used as a type of data transfer which is built, based on the architecture of the HTTP protocols. It helps us to easily send and retrieve data between two or more different services using XML or JSON. RESTful web services are loosely coupled and are lightweight web services. These are particularly used for creating APIs for clients spread across the web.

Bạn thấy bài viết này như thế nào?: 
Average: 3.5 (22 votes)
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Bình luận (0)

 

Add Comment

Plain text

  • No HTML tags allowed.
  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Tự động ngắt dòng và đoạn văn.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.

Tìm kiếm bất động sản

 

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Apple, Google và Netflix không yêu cầu nhân viên có bằng Đại học

Apple, Google và Netflix không yêu cầu nhân viên có bằng Đại học

Các bạn học sinh, sinh viên cho rằng việc có được tấm bằng Đại học sau 4 năm học với khoản đầu tư để đi học lên tới hàng ngàn dollar là cách duy nhất để đặt chân vào làm việc tại các công ty hàng đầu như Apple, Google và Netflix

Khác biệt cơ bản giữa Windows 32-bit và 64-bit

So sánh sự khác nhau giữa Windows 32-bit và 64-bit

Chúng ta thường nghe đến cụm từ hệ điều hành Windows "32-bit" và “64-bit”. Đây không phải là một khái niệm mới mà đã được xuất hiện từ cách đây khá lâu. Vậy điểm khác biệt của chúng là gì? Bài viết sau đây sẽ giúp bạn hiểu rõ hơn về khái niệm này.

Làm quen với Machine Learning - Natural Language Processing

Làm quen với Machine Learning - Natural Language Processing

Vào năm 2014, mình có thuyết trình trước lớp một bài giới thiệu về Machine Learning.

Tomdesgin.vn

 

Drupal Services