With over a decade of web development experience, I specialize in Drupal (7, 8, 9, 10), CodeIgniter, Laravel, and WordPress. I offer extensive expertise in both module and theme development, providing customized solutions for complex projects. Whether you need to enhance an existing platform, create new features, or seek expert guidance, I'm here to assist. My dedication to delivering high-quality, efficient, and scalable solutions is unmatched. Feel free to contact me to explore how I can contribute to your project's success. Let's turn your ideas into reality!

“Create a Drupal 9 custom module for API integration, store API key in configuration, and render REST API responses using Twig.”
  1. Module Creation:

    Create a custom module folder in the modules/custom directory. Let's name it custom_api_integration.

    mkdir modules/custom/custom_api_integration
  2. Module Info File:

    Create custom_api_integration.info.yml to define module metadata.

    name: 'Custom API Integration'
    type: module
    description: 'Integrate with external API and render responses.'
    package: Custom
    core_version_requirement: ^8 || ^9
    package: Custom
  3. Module File Structure:

    Organize module files:

    custom_api_integration/
    ├── config/
    │   └── install/
    │       └── custom_api_integration.settings.yml
    ├── src/
    │   ├── Controller/
    │   │   └── CustomApiController.php
    │   ├── Plugin/
    │   │   └── Block/
    │   │       └── CustomApiBlock.php
    │   └── PluginManager/
    │       └── CustomApiManager.php
    ├── templates/
    │   └── custom-api-block.html.twig
    ├── custom_api_integration.module
    └── custom_api_integration.install
    
  4. Configuration Setting:

    Create custom_api_integration.settings.yml for storing API key.

    api_key: ''
  5. Module Implementation:
    • custom_api_integration.module

      <?php
      
      /**
       * Implements hook_help().
       */
      function custom_api_integration_help($route_name, \Drupal\Core\Routing\RouteMatchInterface $route_match) {
        switch ($route_name) {
          case 'help.page.custom_api_integration':
            return '<p>' . t('Custom API Integration module provides API integration functionality.') . '</p>';
        }
      }
    • custom_api_integration.install

      <?php
      
      /**
       * Implements hook_install().
       */
      function custom_api_integration_install() {
        // Set default configuration values.
        \Drupal::configFactory()
          ->getEditable('custom_api_integration.settings')
          ->set('api_key', '')
          ->save();
      }
    • src/Plugin/Block/CustomApiBlock.php

      <?php
      
      namespace Drupal\custom_api_integration\Plugin\Block;
      
      use Drupal\Core\Block\BlockBase;
      
      /**
       * Provides a 'Custom API Block' block.
       *
       * @Block(
       *   id = "custom_api_block",
       *   admin_label = @Translation("Custom API Block"),
       * )
       */
      class CustomApiBlock extends BlockBase {
      
        /**
         * {@inheritdoc}
         */
        public function build() {
          $api_manager = \Drupal::service('custom_api_integration.manager');
          $api_response = $api_manager->getApiResponse();
          return [
            '#markup' => $api_response,
            '#cache' => [
              'max-age' => 0,
            ],
          ];
        }
      }
    • src/Controller/CustomApiController.php

      <?php
      
      namespace Drupal\custom_api_integration\Controller;
      
      use Drupal\Core\Controller\ControllerBase;
      
      /**
       * Class CustomApiController.
       */
      class CustomApiController extends ControllerBase {
      
        /**
         * {@inheritdoc}
         */
        public function content() {
          return [
            '#markup' => $this->t('Welcome to the Custom API Integration module.'),
          ];
        }
      }
    • src/PluginManager/CustomApiManager.php

      <?php
      
      namespace Drupal\custom_api_integration\PluginManager;
      
      use Drupal\Core\Plugin\PluginBase;
      
      /**
       * Provides a base class for Custom API Manager plugins.
       */
      abstract class CustomApiManager extends PluginBase {
      
        /**
         * Get API response.
         *
         * @return string
         *   The API response.
         */
        abstract public function getApiResponse();
      }
  6. Twig Template:

    Create custom-api-block.html.twig in the templates folder.

    <div class="custom-api-block">  {{ content }} </div>
  7. Service Definition:

    Define the service in custom_api_integration.services.yml.

    services:
      custom_api_integration.manager:
        class: Drupal\custom_api_integration\PluginManager\CustomApiManager
        arguments: ['@config.factory']
        abstract: true
        shared: false
  8. Custom API Manager Implementation:

    Create a custom API manager plugin that extends CustomApiManager.

    • src/PluginManager/CustomApiManagerImpl.php

      <?php
      
      namespace Drupal\custom_api_integration\PluginManager;
      
      use Drupal\Core\Config\ConfigFactoryInterface;
      use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
      use Drupal\Core\Plugin\PluginFormInterface;
      use Drupal\Core\Plugin\PluginManagerInterface;
      use Drupal\Core\Plugin\PluginBase;
      use Symfony\Component\DependencyInjection\ContainerInterface;
      
      /**
       * Provides a 'Custom API Manager' plugin.
       *
       * @Plugin(
       *   id = "custom_api_manager_impl",
       *   label = @Translation("Custom API Manager Implementation"),
       * )
       */
      class CustomApiManagerImpl extends CustomApiManager implements ContainerFactoryPluginInterface, PluginFormInterface {
      
        /**
         * Config Factory.
         *
         * @var \Drupal\Core\Config\ConfigFactoryInterface
         */
        protected $configFactory;
      
        /**
         * {@inheritdoc}
         */
        public function __construct(array $configuration, $plugin_id, $plugin_definition, ConfigFactoryInterface $config_factory) {
          parent::__construct($configuration, $plugin_id, $plugin_definition);
          $this->configFactory = $config_factory;
        }
      
        /**
         * {@inheritdoc}
         */
        public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
          return new static(
            $configuration,
            $plugin_id,
            $plugin_definition,
            $container->get('config.factory')
          );
        }
      
        /**
         * {@inheritdoc}
         */
        public function getApiResponse() {
          // Implement API call logic using stored API key.
          $api_key = $this->configFactory->get('custom_api_integration.settings')->get('api_key');
          // Make API request and handle response.
          // ...
      
          return 'API Response Placeholder';
        }
      }
  9. Enable the Module:

    Enable the module using Drush or the Drupal UI.

    drush en custom_api_integration

This is a basic structure to get you started. Adjust and expand based on your specific API integration requirements. Ensure you replace placeholder comments with actual implementation details.

Posted by Sujan Shrestha
Categorized:
PREVIOUS POST
banner