Reading list Switch to dark mode

    How to use Guzzle in Magento 2

    Updated 12 July 2023

    In this blog, we will discuss how we use the Guzzle in Magento 2. Let’s get started

    What is Guzzle in Magento 2

    Guzzle is a PHP HTTP client that makes it easy to create some integrations with some web services. Its implementation code is more simpler, cleaner, and readable, in comparison with cURL.

    GuzzleHttp uses cURL by default, but it can use any HTTP client that you want other than cURL like PHP’s stream wrapper or sockets, in case curl isn’t installed on your Web Server.

    To know more about Guzzle’s request click here

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    To use Guzzle we require some of the classes mentioned below these classes will help us to use Guzzle HTTP request in Magento 2.

    use GuzzleHttp\Client;
    use GuzzleHttp\ClientFactory;
    use GuzzleHttp\Exception\GuzzleException;
    use GuzzleHttp\Psr7\Response;
    use GuzzleHttp\Psr7\ResponseFactory;
    use Magento\Framework\Webapi\Rest\Request;

    Now we required a file in which we need a response from a api like we are using the controller in which we created the function doRequest() in which we have have requested to get the api response mentioned below.

        /**
         * Do API request with provided params
         *
         * @param string $uriEndpoint
         * @param array $params
         * @param string $requestMethod
         *
         * @return Response
         */
        private function doRequest(
            string $uriEndpoint,
            array $params = [],
            string $requestMethod = Request::HTTP_METHOD_GET
        ): Response {
            /** @var Client $client */
            $client = $this->clientFactory->create(['config' => [
                'base_uri' => self::API_REQUEST_URI
            ]]);
    
            try {
                $response = $client->request(
                    $requestMethod,
                    $uriEndpoint,
                    $params
                );
            } catch (GuzzleException $exception) {
                /** @var Response $response */
                $response = $this->responseFactory->create([
                    'status' => $exception->getCode(),
                    'reason' => $exception->getMessage()
                ]);
            }
    
            return $response;
        }

    Now in controller, we will call this function with appropriate parameters like mentioned below.

    $repositoryName = 'magento/magento2';
    $response = $this->doRequest(static::API_REQUEST_ENDPOINT . $repositoryName);
    $status = $response->getStatusCode(); // 200 status code
    $responseBody = $response->getBody();
    $responseContent = $responseBody->getContents();

    By the above-mentioned code, we will get the response from the api.

    Now our controller will look like.

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_GuzzleHttpApi
     * @author    Webkul <[email protected]>
     * @copyright Webkul Software Private Limited (https://webkul.com)
     * @license   https://store.webkul.com/license.html ASL Licence
     * @link      https://store.webkul.com/license.html
     */
    
    namespace Webkul\GuzzleHttpApi\Controller\Services;
    
    use GuzzleHttp\Client;
    use GuzzleHttp\ClientFactory;
    use GuzzleHttp\Exception\GuzzleException;
    use GuzzleHttp\Psr7\Response;
    use GuzzleHttp\Psr7\ResponseFactory;
    use Magento\Framework\Webapi\Rest\Request;
    
    /**
     * Class Guzzel Api
     */
    class GuzzelApi
    {
        /**
         * API request URL
         */
        const API_REQUEST_URI = 'https://api.github.com/';
    
        /**
         * API request endpoint
         */
        const API_REQUEST_ENDPOINT = 'repos/';
    
        /**
         * @var ResponseFactory
         */
        private $responseFactory;
    
        /**
         * @var ClientFactory
         */
        private $clientFactory;
    
        /**
         * Constructor
         *
         * @param ClientFactory $clientFactory
         * @param ResponseFactory $responseFactory
         */
        public function __construct(
            ClientFactory $clientFactory,
            ResponseFactory $responseFactory
        ) {
            $this->clientFactory = $clientFactory;
            $this->responseFactory = $responseFactory;
        }
    
        /**
         * Execute Function for class Addtocompare
         */
        public function execute()
        {
            $repositoryName = 'magento/magento2';
            $response = $this->doRequest(static::API_REQUEST_ENDPOINT . $repositoryName);
            $status = $response->getStatusCode(); // 200 status code
            $responseBody = $response->getBody();
            $responseContent = $responseBody->getContents();
            
            return json_decode($responseContent);
        }
    
        /**
         * Do API request with provided params
         *
         * @param string $uriEndpoint
         * @param array $params
         * @param string $requestMethod
         *
         * @return Response
         */
        private function doRequest(
            string $uriEndpoint,
            array $params = [],
            string $requestMethod = Request::HTTP_METHOD_GET
        ): Response {
            /** @var Client $client */
            $client = $this->clientFactory->create(['config' => [
                'base_uri' => self::API_REQUEST_URI
            ]]);
    
            try {
                $response = $client->request(
                    $requestMethod,
                    $uriEndpoint,
                    $params
                );
            } catch (GuzzleException $exception) {
                /** @var Response $response */
                $response = $this->responseFactory->create([
                    'status' => $exception->getCode(),
                    'reason' => $exception->getMessage()
                ]);
            }
    
            return $response;
        }
    }

    We will get response mentioned below.

    Response for Magento 2 Guzzle Request

    Please refer to the blog for reference: click here
    That’s all for this blog.
    Happy coding 🙂

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home