🇨🇿Czech Republic @XSramik

Account created on 9 August 2010, over 14 years ago
#

Recent comments

🇨🇿Czech Republic XSramik

Hello Cilefen, thank you for looking into it so quickly. Despite the log message, the problem was within another module which implements CSV serialization in (likely) outdated way. I just replaced that module and everything works well.

I am closing this as the 'rest.module' works as should.

🇨🇿Czech Republic XSramik

It turns out that the best way to implement this is to use $http_client_factory. Here's a working example in case anyone finds it useful.

<?php
namespace Drupal\module\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\Http\ClientFactory;

class DevForm extends FormBase {
  protected $httpClient;
  protected $cookieJar;
  protected $aquaponi;

  public function __construct(ClientFactory $http_client_factory) {
    $this->cookieJar = new \GuzzleHttp\Cookie\CookieJar;
    $this->company= (object)(Settings::get('default','company')['company']);
    $this->httpClient = $http_client_factory->fromOptions([
      'base_uri' => $this->company->base_uri,
      'cookies'  => $this->cookieJar,
    ]);

    // Login to the COMPANY API (get the token)
    if(empty($this->cookieJar->getCookieByName($this->aquaponi->cookie)))
    {
      $request = $this->httpClient->request('POST', 'login', [
        'json' => [
          'username' => $this->company->username,
          'password' => $this->company->password
        ]
      ]);
    }
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('http_client_factory')
    );
  }

...

The authorization token and 'base_uri' are then used by default with the following call:

$this->httpClient->request('GET', 'data');

Source: https://drupalize.me/blog/speak-http-drupalhttpclient

Production build 0.71.5 2024