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 (28 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 (1)

Ảnh của Tommy Tran
Tommy Tran- Apr 28, 2023 08:26 AM Reply

Đặc biệt, VNG Cloud đã nhận được rất nhiều câu hỏi từ các bạn tại webinar và nhân cơ hội này, chúng tôi xin được giải đáp 10 câu hỏi được quan tâm nhất tại sự kiện

1. Xác thực google có thể bị hack do có lỗ hổng dễ dàng không? 

Thực chất, chúng ta chỉ có thể tăng cường bảo mật tương đối, chứ không thể tuyệt đối. Việc enable xác thực đa yếu tố (MFA) chỉ là thêm 1 lớp khóa cho account. Google MFA khó bị hack, nhưng không đồng nghĩa với việc không thể bị hack. 

2. Sự khác biệt giữa Bastion host khác VPN?

Bastion host kiểm soát truy cập vào các host trước, giống như một jump host. Bạn phải truy cập tới Bastion host trước, sau đó ở Bastion host bạn sẽ được phân quyền để truy cập vào quản trị trên các tài nguyên đã deploy trên Cloud.

Với VPN chỉ khởi tạo một kết nối từ bạn tới các tài nguyên trên Cloud, từ đó bạn có thể truy cập tới tài nguyên cloud mà không cần thông qua một trạm kiểm soát truy cập trung gian nào.

3. Gói security service là offer mặc định hay là lựa chọn của VNG Cloud cho khách hàng? Nó tuy là lợi thế nhưng có dẫn tới giá của VNG Cloud cao hơn so với các nhà cung cấp Cloud khác không? 

Tính năng NSG (Network Security Group) và IAM được VNG mặc định hỗ trợ cho khách hàng. Đối với Cloud WAF, Backup Data Storage là một lựa chọn mà VNG Cloud cung cấp. Tùy vào quy mô triển khai sẽ có các mức giá cạnh tranh khác nhau, anh vui lòng liên hệ VNG Cloud để được tư vấn chí tiết hơn.

4. VNG Cloud hiện có những dịch vụ bảo mật nào? 

Hiện tại VNG Cloud cung cấp các lớp bảo mật như sau

Tại tầng application: 

  • - Bshield (protect application) 
  • - Polaris WAF (Protect web)

Tại tầng network: 

  • - Security group (protect VM) 
  • - Network Vendor firewall (F5, Fortigate, Checkpoint, Palo Alto).

5. VNG Cloud có thể chia sẻ thêm về mô hình bảo mật multi-account không? 

Identity & Access Management (IAM) cho phép người dùng được quyền đặt chính sách rằng ai trong tổ chức được quyền truy cập vào những tài nguyên gì, và được làm gì trên những tài nguyên Cloud đó. Ví dụ: Bạn có thể phân quyền cho nhóm user Administrator để có thể View/Delete/Edit Server/Cấu hình server trên Cloud, trong khi các nhóm khác chỉ có thể View.

6. VNG Cloud có triển khai bảo mật cho tất cả các khách hàng sử dụng cloud hay không? Nếu có thì có phân lớp bảo mật không? 

VNG Cloud cung cấp các tính năng và khả năng bảo mật, khách hàng/user quyết định sử dụng tính năng nào và tự triển khai tùy vào đặc điểm hệ thống mình muốn triển khai. 

7. Kết quả của báo cáo Pentest của VSEC có thể dùng để chứng minh khi làm các chứng chỉ quốc tế như ISO27001 hoặc PCIDSS không?

VSEC hiện tại đang được xác nhận bởi tổ chức CREST về quy trình cung cấp dịch vụ pentest. Các báo cáo của VSEC hoàn toàn có thể dùng làm chứng minh khi đáp ứng các compliance quốc tế như ISO27001, PCIDSS. Thực tế hiện tại VSEC đã cung cấp dịch vụ pentest tới rất nhiều Ngân hàng tại Việt Nam.

8. Pentest có cần thực hiện thường xuyên không? Tần suất ra sao?

Đối với các ứng dụng quan trọng có liên quan đến thanh toán, dữ liệu kinh doanh, dữ liệu khách hàng, được khuyến nghị thực hiện pentest trước khi go-live. Trong trường hợp giới hạn về chi phí, hạ tầng CNTT nên thực hiện pentest tối thiểu 1 lần/năm. Phía các tổ chức chính phủ cũng như các ngành nghề tài chính đang quy định bắt buộc đánh giá tối thiểu 1 lần/năm.

9. So sánh ưu nhược điểm của Pentest as a service và tổ chức 1 chương trình bug bounty?

Bug bounty là chương trình được đưa ra bởi một tổ chức để kêu gọi các hacker tìm kiếm lỗ hổng của một sản phẩm và được trả thưởng qua tiền. Bug-bounty sẽ phụ thuộc vào kĩ năng của các hacker tham gia vào chương trình, và về cơ bản là không có các ràng buộc trách nhiệm về việc bảo mật lỗ hổng. Bug-bounty có thể sẽ tốn ít chi phí hơn tuy nhiên sẽ có nhiều rủi ro hơn về việc bảo mật thông tin lỗ hổng tìm được và việc sót các lỗ hổng tìm được do giới hạn kĩ năng của hacker tham gia (do giá trị bug-bounty không hấp dẫn các kĩ sư giỏi). Pentest hay pentest-as-a-service là dịch vụ được cung cấp bởi một đơn vị chuyên nghiệp, có ràng buộc trách nhiệm, bảo mật thông tin, cam kết về chất lượng cung cấp, cũng như hỗ trợ khách hàng để khắc phục lỗ hổng. 

10. Việc triển khai pentest as a service 1 cách tự động có làm thay đổi tính chất của việc pentest hay không? 

Việc triển khai tự động không làm thay đổi tính chất của pentest, Pentest-as-a-service chỉ là tự động hóa các công việc lặp lại để giúp các kĩ sư rút ngắn thời gian thực hiện, cũng như tập trung vào việc khai thác các lỗ hổng quan trọng theo nghiệp vụ. Pentest-as-a-service cũng giúp tận dụng tri thức của các kỹ sư nhiều năm kinh nghiệm thông qua AI/ML khuyến nghị cho các kỹ sư bảo mật mới.

 

Add Comment

Filtered HTML

  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Các thẻ HTML được chấp nhận: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Tự động ngắt dòng và đoạn văn.

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.

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

 
Một số khái niệm cơ bản cần biết về Search Engine Optimization - SEO (phần 2)

Một số khái niệm cơ bản cần biết về Search Engine Optimization - SEO (phần 2)

Search Engine Optimization, hay thường gọi là tối ưu hóa bộ máy tìm kiếm có lẽ không mấy xa lạ với nhiều người sử dụng chúng ta. Nhưng việc hiểu rõ về bản chất cũng như tận dụng được ưu điểm của SEO ...

Sự khác biệt Entity Property API ở Drupal 8 và Drupal 7

Sự khác biệt Entity Property API ở Drupal 8 và Drupal 7

While the conversion to full CRUD for entities and classed objects for Drupal 8 made good progress

Sony xác nhận Xperia Arc S và Mini Pro không được cập nhật Jelly Bean

Tin buồn cho người sử dụng 2 thiết bị này, Sony sẽ không công bố bản cập nhật Jelly Bean chính thức nào cho Xperia Arc S và Mini Pro.

Công ty diệt chuột T&C

 

Diet con trung