Upgrade Your Drupal Skills
We trained 1,000+ Drupal Developers over the last decade.
See Advanced Courses NAH, I know EnoughHow 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'));
}
}
}
About Drupal Sun
Drupal Sun is an Evolving Web project. It allows you to:
- Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
- Facet based on tags, author, or feed
- Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
- View the entire article text inline, or in the context of the site where it was created
See the blog post at Evolving Web