Custom Rest API - Part I

Rest API: (Representational State Transfer)

In this series of the blog we will discuss custom rest APIs and how can we define it in Drupal 8. I have divided this series into 2 parts. In our first part we will discuss core rest APIs and "How can we extend Rest module to define our custom API in Drupal 8" and In our 2nd part we will discuss, "How can we define Rest Api using controller".

Now before going further our question is what is REST?
REST
means "Representational state transfer". It's a way to which most of the web services works. Through our REST services, we give chance to external services to communicate or work with our internal application. REST API uses different-2 HTTP methods to fetch, update, add or delete data in our application like POST, GET, Patch (Update/modify), PUT (Update/replace), and Delete. The best thing in Drupal-8/9 is we have the REST API module in Drupal core. You just need to enable the REST and its supporting module to make it workable in your application.

Extend Drupal Core Rest API: To extend the Drupal Rest API we need to define our custom plugin. We will tell that Drupal we are extending Core Rest API with our custom code. If everything is defined according to Drupal way then you can able to call this API in your external app.

So let's get started:

Step-1 Define your module

The first thing you need to define the "info.yml" file in your custom module folder like goto rootfolder->modules->custom->your_module_folder and in your_module_folder define your "your_module_folder.info.yml" file in it. Now open this newly created .info.yml file and put this code in it.

Actually, this code informs Drupal about the newly created custom module. Once the user enables the module it will save this info in the config table


name:  Custom REST API Example
description: Define's a custom REST Resource.
package: Custom
type: module
core: 8.x  

Step-2 Creating the Resource Plugins

Now in this step we need to define our REST api file in our plugins foldee like goto rootfolder->modules->custom->your_module_folder ->src->Plugin->rest->resource->CustomRest.php


<?php

namespace Drupal\custom_module_machine_name\Plugin\rest\resource;

use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;

/**
 * Provides a CustomRest Resource
 *
 * @RestResource(
 *   id = "custom_rest",
 *   label = @Translation("Custom Rest Resource"),
 *   uri_paths = {
 *     "canonical" = "/rest/customrest"
 *   }
 * )
 */
class CustomRest extends ResourceBase {

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {
    //Prepare response data
    $response = [
       'data' => 'Hi all, this is my first rest api',
       'method' => 'POST'
    ];

    return new ResourceResponse([
    'response' => $response
     ]);
  }
/**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function post($data) {
    //Create node and prepare response data
    $response = Node::create(
      array(
        'type' => $data->content_type->value,
        'title' => $data->title->value,
        'body' => [
          'summary' => '',
          'value' => $data->body->value,
          'format' => 'full_html',
        ],
      )
    );
    $node->save();

    return new ResourceResponse([
      'response' => $response,
      'message' => t('New node created successfully.'),
    ]);
  }
}

In the above code, we have defined @RestResource annotation. This annotation will use to define meta-data about the custom rest API and also define the rest API endpoints or paths, where it will be available. This annotation will tell Drupal that we have defined our custom rest resource plugins with machine name "custom_rest" and label "Custom rest resource", which will serve the response data on "/rest/customrest" this path 

After annotation definition, we will extend the Drupal resource base class with our custom class. This child class or custom class will use to define our custom methods which will use to send the response data. In our case, we have defined the get() and post() methods for reading and writing operations. In the get() method we are simply sending a text message in response and in Post() method we are creating a new node depending on the data passed in the body for our post-call and return a node data in response.

Test REST Resource Plugins endpoint

Now open the postman and test our custom api endpoint.