Tập tành chọt Drupal 8/9 and Guzzle HTTP client library

4th Jul 2022
Table of contents

Making a simple HTTP Get request in Drupal 8 or 9 is super easy thanks to the Guzzle library. This library has been added to Drupal core a long time ago, and it replaced the much less powerful drupal_http_request() function. Let's see how to get some data from the Star Wars API:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

$client = new Client();
$people = [];

try {
  $response = $client->get('https://swapi.dev/api/people');
  $result = json_decode($response->getBody(), TRUE);
  foreach($result['results'] as $item) {
    $people[] = $item['name']; 
catch (RequestException $e) {
  // log exception

Guzzle can also be accessed through the http_client service and the helper method:

$client = \Drupal::httpClient();
Sending a POST request is also simple and easy.

public function sendOrder(OrderInterface $order) {
  try {
    $response = $this->httpClient->post($url, [
      'form_params' => $data,
    $response_data = json_decode($response->getBody()->getContents(), TRUE);

    // do something with data
  catch (RequestException $e) {
    // log exception

If you want to log the exception don't use $e->getMessage() because the error message will be truncated. Instead, use this:


You can also use Guzzle to send files. To send an image file you can do something like this:

try {
  $client = new Client(['headers' => ['X-Auth-Secret-Token' => 'my-secret-token']]);
  $options = [
    'multipart' => [
        'Content-type' => 'multipart/form-data',
        'name' => 'image',
        'contents' => fopen($image->getFileUri(), 'r'),
        'filename' => basename($image->getFileUri()),
  $response = $client->post($api_base_url . 'api/v1/images', $options);
catch (\Exception $e) {
  // log exception

In this case, the $image variable is an instance of Drupal\file\Entity\File class.

Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Enter the characters shown in the image.
Câu nói tâm đắc: “Điều tuyệt với nhất trong cuộc sống là làm được những việc mà người khác tin là không thể!”

Related Articles

Recently I found myself needing to manage cookie data in Drupal 9 for the first time. As oft, my first step in the process was to search through Drupal core and the Drupal API for examples of “the right way” to handle cookies. After I didn’t find any reasonable existing solution within Drupal, it was time to solve this on my own.

Regardless of your position on either side of the web, there is always risk of being a victim of a cyber attack. This has put businesses in a tizz to make personal data of the visitors secure.

we had 5 domain on our website and we need to redirect a user to US domain if user is browsing from US

Migration from one version of Drupal to the other version of Drupal has always been important as it helps to move with time and stay updated with the latest technology.

in this article, I'll show you how to create custom controller with JSON response in Drupal 9