Tập chọt Psr-7 Guzzle, Guzzle7 and HTTPClient

30th Jun 2022
Table of contents

If you're sending a request to a custom URL in Drupal 8/9, 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

No. 1

<?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'));
    }

  }
}

No 2.

use GuzzleHttp\Client;

$url = 'http://www.domain.drupal';

$content_client = new Client([
    'base_uri' => $url,
    'timeout'  => 20.0,
]);
$headers = [
    'Content-type' => 'application/vnd.api+json',
    'Accept' => 'application/vnd.api+json'
];
$payload['data'] = [
        'type' => 'node--article',
        'attributes' => [
                "title" => "My custom title",
                "body" => [
                        "value" => "Custom value",
                        "format" => "plain_text"
                    ]
            ]
    ];
$guzzleResponse = $content_client->post('/jsonapi/node/article/71adf560-044c-49e0-9461-af593bad0746', [
                'json' => json_encode($payload),
                'headers' => $headers
            ]);

if ($guzzleResponse->getStatusCode() == 200) {
                $response = json_decode($guzzleResponse->getBody());
}

Guzzle7 (same works for Guzzle 6 as well)

Using RequestException, RequestException catches any exception that can be thrown while transferring requests.

try{
  $client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
 
  $guzzleResponse = $client->get('/foobar');
  // or can use
  // $guzzleResponse = $client->request('GET', '/foobar')
    if ($guzzleResponse->getStatusCode() == 200) {
         $response = json_decode($guzzleResponse->getBody(),true);
         //perform your action with $response
    }
}
catch(\GuzzleHttp\Exception\RequestException $e){
   // you can catch here 400 response errors and 500 response errors
   // You can either use logs here use Illuminate\Support\Facades\Log;
   $error['error'] = $e->getMessage();
   $error['request'] = $e->getRequest();
   if($e->hasResponse()){
       if ($e->getResponse()->getStatusCode() == '400'){
           $error['response'] = $e->getResponse();
       }
   }
   Log::error('Error occurred in get request.', ['error' => $error]);
}catch(Exception $e){
   //other errors
}
Psr7 Guzzle
use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;

try {
    $client->request('GET', '/foo');
} catch (RequestException $e) {
    $error['error'] = $e->getMessage();
    $error['request'] = Psr7\Message::toString($e->getRequest());
    if ($e->hasResponse()) {
        $error['response'] = Psr7\Message::toString($e->getResponse());
    }
    Log::error('Error occurred in get request.', ['error' => $error]);
}

For HTTPClient

use Illuminate\Support\Facades\Http;
try{
    $response = Http::get('http://api.foo.com');
    if($response->successful()){
        $reply = $response->json();
    }
    if($response->failed()){
        if($response->clientError()){
            //catch all 400 exceptions
            Log::debug('client Error occurred in get request.');
            $response->throw();
        }
        if($response->serverError()){
            //catch all 500 exceptions
            Log::debug('server Error occurred in get request.');
            $response->throw();
        }
        
    }
 }catch(Exception $e){
     //catch the exception here
 }
Bạn thấy bài viết này như thế nào?
0 reactions

Add new comment

Image CAPTCHA
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