Drupal x React: Rest API and Authentication

Drupal x React: Rest API and Authentication

In the previous article I discussed about how you can preprocess the data from nodes and share it with react without an api you can read the whole article over here -

Now when we choose an separate framework to handle the frontend logic we might sometime run into a condition that we need to have the node data on an cross origin platform that too with authentication.

Situations for which we may need such implementation -

  • You have an mobile app running parallel to your drupal based site and now you want to access the drupal data on the app.
  • To integrate Drupal with other applications and services. For instance, you could use an API to connect your Drupal site to a CRM system or an e-commerce platform.

Okay anyways we want to access node on an api end point,

How to do that ?

Drupal Core - REST Module

First we will install a module named rest (part of core) and restui which essentially provides an user interface for managing your rest api all in one place.

Drupal offers an powerfull rest api integration for your needs, all you have to do is just extend the ResourceBase class and add an annotation like this -

<?php

namespace Drupal\custom_api\Plugin\rest\resource;

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


/**
 * Provides a custom REST resource.
 *
 * @RestResource(
 *   id = "custom_rest_api",
 *   label = @Translation("Custom REST Resource"),
 *   uri_paths = {
 *     "canonical" = "/api/node"
 *   }
 * )
 */
class NodeRestResource extends ResourceBase
{
        

To read more about it Go here -

Now once you have done this you will be able to see your rest api in the restui module's interface

Article content
Rest UI interface

And now what about the data ?

For our use case we will pass an an query parameter which holds the title of the node that we have created in CMS (keep it unique).

Now we will implement an get() function which responds to the GET request to this endpoint and we will fetch the query parameter title.

 /**
   * Responds to GET requests.
   *
   * @return \Drupal\rest\ResourceResponse
   */
  public function get()
  {

    $title = \Drupal::request()->query->get('title');        

Then we will execute an entity query, in which we are specifying the type of entity and also an condition which says what should be the title of it.

 $filteredData = \Drupal::entityQuery('node')
      ->accessCheck(TRUE)
      ->condition('title', $title)
      ->execute();        

After fetching the entity from entity type manager you will receive an associative array with 'node_id' => [node_entity] so since we have to keep the node title unique the result will be just 1 so no worries get the first value and its our node. Now since we have overridden the bundle class of this node bundle we still have access to the getData() function that we created in last article and we will just returned the result.

$node_data = [];
    $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($filteredData);

    $node_data = $nodes[array_key_first($nodes)]->getData();

    new ResourceResponse($node_data));
}        
Article content
The api response to our custom node api

As you can see we got the json data in response when I passed homepage as a query parameter.

Authentication

Now we want to authenticate the api otherwise anyone will be able to access our api's and thats not good.

Drupal have a lot of modules which offers an authentication service to your api and if your are a tech guy you can just make one yourself.

But for demo we will use an module called Drupal REST & JSON API Authentication install it. It offers all type of authentication you name it -

(This module is not completely free but it does offer some free stuff like api authentication.)

After that generate an api key and enable authentication -

Article content
Interface for api auth module

Now we will have a option to add authentication on our custom api from our rest ui module -

Article content
UI for managing api from rest ui

Now when we will try to access the same api from post man after clearing its cookies we will get an error -

Article content

Which means we can now use the api auth on the as a authentication method on our api I am assuming you know how to do that, so this concludes this Article.

Thanks for spending time oreading it.n this.

To view or add a comment, sign in

More articles by Abhinav Singh

Others also viewed

Explore content categories