Why Create a Custom Node API?
A custom API allows external systems such as mobile applications, Angular/React frontends, or third-party services to fetch Drupal content securely and efficiently.
- Expose selected content fields
- Control access and permissions
- Return structured JSON responses
- Integrate Drupal with other platforms
Module Name
lightnet_api
Create your custom module inside:
modules/custom/lightnet_apiStep 1: Create Module Info File
File: lightnet_api.info.yml
name: LightNet API
type: module
description: Custom API to fetch node data
core_version_requirement: ^10
package: Custom
dependencies:
- nodeStep 2: Create Routing File
File: lightnet_api.routing.yml
lightnet_api.node_details:
path: '/api/node/{nid}'
defaults:
_controller: '\Drupal\lightnet_api\Controller\NodeApiController::nodeDetails'
_title: 'Node API'
requirements:
_permission: 'access content'
methods: [GET]Step 3: Create Controller
File: src/Controller/NodeApiController.php
<?php
namespace Drupal\lightnet_api\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\node\Entity\Node;
/**
* Returns node data in JSON format.
*/
class NodeApiController extends ControllerBase {
/**
* Get node details.
*/
public function nodeDetails($nid) {
$node = Node::load($nid);
if (!$node) {
return new JsonResponse(['message' => 'Node not found'], 404);
}
$data = [
'nid' => $node->id(),
'title' => $node->getTitle(),
'type' => $node->bundle(),
'status' => $node->isPublished(),
'created' => $node->getCreatedTime(),
'body' => $node->hasField('body') ? $node->get('body')->value : '',
];
return new JsonResponse($data);
}
}Step 4: Enable the Module
drush en lightnet_api -y
drush crStep 5: Test the API
https://your-site.com/api/node/1Contact Details
LightNet Technology Private Limited
Indrayani Nagar, Dehu Gav
Pune, Maharashtra, India
Phone: +91 9503061806
Website: https://lightnet.co.in