Skip to content

Instantly share code, notes, and snippets.

@Shahrozmunir
Last active December 18, 2024 11:53
Show Gist options
  • Save Shahrozmunir/84a96606560260d25c524413b2f54af4 to your computer and use it in GitHub Desktop.
Save Shahrozmunir/84a96606560260d25c524413b2f54af4 to your computer and use it in GitHub Desktop.
Drupal Custom API Module Controller

What the Code Does

Purpose

This code is part of a custom Drupal module that fetches data from an external REST API and displays it on a page.

Features

  • It uses Drupal's http_client service (based on Guzzle) to make API requests.
  • Handles errors gracefully using a try-catch block.
  • Implements dependency injection for better testing and modularity.
  • Outputs data in a renderable array compatible with Drupal’s theme system.

Why I Coded It This Way

Performance and Scalability

By using dependency injection, the code adheres to Drupal’s best practices, which makes it reusable and testable. It also avoids hard-coding dependencies.

Error Handling

The try-catch block ensures the application does not crash on API failures and logs errors for debugging.

Standards Compliance

Following Drupal’s coding standards and guidelines ensures maintainability and compatibility with future updates.

Extensibility

The controller is designed to be extensible, allowing additional logic (e.g., caching or transforming API data) to be easily incorporated.

<?php
namespace Drupal\custom_api_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use GuzzleHttp\ClientInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Controller for fetching and displaying API data.
*/
class ApiDataController extends ControllerBase {
/**
* The HTTP client to fetch external API data.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* Constructs a new ApiDataController object.
*
* @param \GuzzleHttp\ClientInterface $http_client
* The HTTP client service.
*/
public function __construct(ClientInterface $http_client) {
$this->httpClient = $http_client;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('http_client')
);
}
/**
* Fetches data from an external API and returns it as a renderable array.
*
* @return array
* A renderable array.
*/
public function fetchApiData() {
$url = 'https://api.example.com/data';
try {
$response = $this->httpClient->request('GET', $url, [
'headers' => [
'Accept' => 'application/json',
],
]);
$data = json_decode($response->getBody(), TRUE);
if (!empty($data)) {
$output = [];
foreach ($data as $item) {
$output[] = [
'#markup' => $this->t('Item: @item', ['@item' => $item['name']]),
];
}
return $output;
}
else {
return [
'#markup' => $this->t('No data found.'),
];
}
}
catch (\Exception $e) {
watchdog_exception('custom_api_module', $e);
return [
'#markup' => $this->t('An error occurred while fetching the API data.'),
];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment