David Lohmeyer's Blog

How to make custom Guzzle requests in Drupal 8 modules

If you're sending a request to a custom URL in Drupal 8, you might be tempted to implement a solution using cURL or another library. However, Drupal core comes with Guzzle, a "PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services." As with most things in Drupal, it's not obvious how to use something immediately, so here's a demo to show you how to take care of sending a request to an arbitrary URL inside a custom Drupal module. You might use this example class to display a status code on some page. Here's the actual class, and a Github repo to show module structure:

<?php

namespace Drupal\custom_guzzle_request\Http;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/** 
 * Get a response code from any URL using Guzzle in Drupal 8!
 * 
 * Usage: 
 * In the head of your document:
 * 
 * use Drupal\custom_guzzle_request\Http\CustomGuzzleHttp;
 * 
 * In the area you want to return the result, using any URL for $url:
 *
 * $check = new CustomGuzzleHttp();
 * $response = $check->performRequest($url);
 *  
 **/

class CustomGuzzleHttp {
  use StringTranslationTrait;
  
  public function performRequest($siteUrl) {
    $client = new \GuzzleHttp\Client();
    try {
      $res = $client->get($siteUrl, ['http_errors' => false]);
      return($res->getStatusCode());
    } catch (RequestException $e) {
      return($this->t('Error'));
    }

  }
}

 

Related Posts