Học cách Custom REST API using a Controller in Drupal 9 cùng Postman

Học cách Custom REST API using a Controller in Drupal 9 cùng Postman

If you are new to Drupal 9 and wondering how to create a simple REST API, this is the right place to learn about it. You can create a REST API in multiple ways, but the one I am going to show you in this post is the simplest method.

First, we need to create a module. So Let’s start. Create a folder name as “custom_rest_api_controller” and create an info file in it, as shown below:


name: Custom REST API using a Controller
description: An example module on how to create a Custom REST API using a Controller
core_version_requirement: ^8 || ^9
type: module
package: Custom

Now we have a module ready, let’s write a Controller now. We need to have a routing.yml file for this.


  path: /my_rest_api/get_data
    _controller: Drupal\custom_rest_api_controller\Controller\MyRestController::getData
  methods: ['GET']
    _user_is_logged_in: 'TRUE'
    _auth: ['basic_auth']
  path: /my_rest_api/post_data
    _controller: Drupal\custom_rest_api_controller\Controller\MyRestController::postData
  methods: ['POST']
    _user_is_logged_in: 'TRUE'
    _auth: ['basic_auth']

If you see the above file, I have created two routes and I had set POST and GET methods as well. So basically, the POST method is to store data and the GET method is to fetch the Stored data. Also, you can notice properties such as “options” and “_auth“, these are useful to enable Authentication for our routes.

Now we have our Routing.yml file ready, let’s create a Controller Class and this should go under the path “src/Controller/MyRestController.php“. So we need to create two folders “src” and “Controller” and then create a file under that.


namespace Drupal\custom_rest_api_controller\Controller;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
class MyRestController extends ControllerBase {
    public function getData() {
        //get the configuration
        $config = \Drupal::config('custom_rest_api_controller.settings');
        //get the stored name or return default
        $name = $config->get('name') ? : 'no name stored yet';
        //return the response
        $res['name'] = $name;
        return new JsonResponse($res);
    public function postData(Request $req) {
        //decode the json data
        $data = Json::decode($req->getContent());
        //check if the name property is present or not
        if ( !isset($data['name']) ){
            //return the error response
            $res['error_code'] = 404;
            $res['error_msg'] = 'name property is missing, cannot store the configuration';
        } else {
            //if the name property is present in the json data, store in a drupal configuration
            $config = \Drupal::service('config.factory')->getEditable('custom_rest_api_controller.settings');
            $config->set('name', $data['name'])->save();
            //return the success response
            $res['result'] = 'Hello '.$data['name'].'! You name stored successfully!';
        return new JsonResponse($res);

There are two methods in our Controller, getData() to get the stored data and postData() to store the data in a Drupal config variable. Just go through the above lines of code and the comments in it to understand the logic.

Now we have everything ready, let’s enable this module, also since we are using “_auth: [‘basic_auth’]” as authentication for our REST API, we need to enable the “HTTP Basic Authentication” module as well. See the screenshot below:

  1. custom_rest_api_enable
  2. http_basic_auth


Everything is set, Let’s test the APIs now. We can POSTMAN Chrome extension to test our REST APIs.

I have this Drupal 9 instance in my “Localhost” so the URL is something like this for me


Don’t forget to add the “_format” query param after the URL otherwise we may see unexpected behavior. Since we are using “Basic Authentication“, let’s add them to the Postman under the “Authorization” tab. The username and password are nothing but the Drupal username and password. Make sure you have selected the “POST” method in the tool since our API “method” is POST.


Now move to the “Body” tab and put this JSON object and hit the “Send” button.

  name: "agurchand"

The below screenshot shows what should be there in the “Body” tab, and also it shows what will be the response once you send the POST request by clicking the “Send” button.

Now the “name” value is stored in our custom configuration drupal variable “custom_rest_api_controller.settings“.

Let’s fetch the data by using the GET method and the “get_data“ API. This below is our “get_data” URL,


Don’t forget to add the username and password under the “Authentication” tab and select the method as “GET“. Here is the screen showing the response of our get_data API

Hope this helped you to understand how to create a REST API using a Controller in Drupal 9.

You can download this custom module from my repository. Just install as a regular custom module and test the module to understand it thoroughly.

Bạn thấy bài viết này như thế nào?: 
Average: 4.5 (4 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

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.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Enter the characters shown in the image.

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





Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

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

Hướng dẫn tạo Drupal 8 Theme sử dụng Bootstrap framework

Hướng dẫn tạo Drupal 8 Theme sử dụng Bootstrap framework

Bootstrap is one of the most popular digital (HTML, CSS and JS) frameworks used today. Because it makes front-end web development faster for any device and for projects of all sizes

Hướng dẫn cách cấp quyền trong Fanpage của facebook

Hướng dẫn cách cấp quyền trong Fanpage của facebook

Facebook đã phân quyền theo cấp cho admin Fan Page !

Giới thiệu 50 best practices cho Optimize PHP code

Giới thiệu 50 best practices cho Optimize PHP code

Like any scripting language, PHP can be used in a variety of applications. The down-side for most programmers is that when they learn how to write PHP

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


Diet con trung