guzzledrupal-9

Retrieve data via an external API on Drupal 9


I'm using drupal 9 and I want get some data from external API, I searched for solutions. One solution is using guzzlehttp library, and all the sites say make guzzlehttp request with some codes, but none of them said where the code should be added! please help me, I don't know what to do? If there are better solutions, please guide me. Thanks...


Solution

  • You can create a custom module or use an existing one to add your code, if you want to fetch data in controller then add this code in you controller function or else you can add in your .module file for testing. Here is an example to retrieve data from an external API in Drupal 9, 10

    function FUNCTION_NAME() {
      $url = 'https://api.example.com/data';
      $response = \Drupal::httpClient()->get($url);
      $data = json_decode($response->getBody(), TRUE);
      return $data;
    }