Follow this step-by-step guide to create a simple API in Drupal without using token authentication and by injecting custom services into your controller.
First, define a custom service in your module's custom_api.services.yml
file:
services:
custom_api.example_service:
class: Drupal\custom_api\ExampleService
Create the ExampleService
class in the src
directory of your module:
<?php
namespace Drupal\custom_api;
class ExampleService {
public function getData() {
return [
'message' => 'Hello, this is a custom service response.',
'status' => 'success',
];
}
}
Modify CustomApiController.php
to inject the custom service and use it in your API response:
<?php
namespace Drupal\custom_api\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\custom_api\ExampleService;
class CustomApiController extends ControllerBase {
protected $exampleService;
public function __construct(ExampleService $exampleService) {
$this->exampleService = $exampleService;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('custom_api.example_service')
);
}
public function content(Request $request) {
$data = $this->exampleService->getData();
return new JsonResponse($data);
}
}
Ensure your route in custom_api.routing.yml
is properly defined:
custom_api.content:
path: '/api/custom'
defaults:
_controller: '\Drupal\custom_api\Controller\CustomApiController::content'
_title: 'Custom API'
requirements:
_permission: 'access content'
options:
_format: 'json'
Enable your custom module and clear the cache:
drush en custom_api -y
drush cr
Use a simple GET request to access your API endpoint:
curl -X GET http://your-drupal-site/api/custom
This setup demonstrates how to create a basic API in Drupal without bearer token authentication, focusing on the use of custom services and controllers. You can manage access control using Drupal’s built-in permissions.
Published By: Krishanu Jadiya
Updated at: 2024-08-06 00:17:19