How to Perform 3rd party API operations in your Magento 2 using GuzzleHttp

Magento 2 is a versatile e-commerce platform that allows you to integrate with third-party services and APIs to enhance the functionality of your online store. One popular tool for making HTTP requests to external APIs in Magento 2 is GuzzleHttp, a PHP HTTP client library. In this guide, we'll walk you through the process of using GuzzleHttp for 3rd party API operations in your Magento 2 store.

Step 1: Install GuzzleHttp

In latest Magento version GuzzleHttp is available by default. But if it's not install on your Magento setup then you need to install GuzzleHttp as a dependency for your Magento 2 project. You can do this using Composer.

saveCopyzoom_out_map
composer require guzzlehttp/guzzle

This command will download and install GuzzleHttp into your Magento 2 project.

Step 2: Create a Custom Module (Optional)

To keep your code organized and maintainable, it's a good practice to create a custom module for your API integration. You can skip this step if you prefer to add your code directly to your theme or other Magento modules.

If you choose to create a custom module, follow these steps:

  1. Create a new directory for your module in the app/code directory of your Magento 2 installation. For example, if your module is named "Devhooks_ApiIntegration," create the directory app/code/Devhooks/ApiIntegration.

  2. Create the necessary module files, including registration.php and module.xml, and define your module in app/code/Devhooks/ApiIntegration/etc/module.xml.

  3. Enable your module by running the following command.

saveCopyzoom_out_map
php bin/magento module:enable Devhooks_ApiIntegration php bin/magento setup:upgrade

Step 3: Write PHP Code for API Integration

Now, let's write the PHP code to use GuzzleHttp for 3rd party API operations. Create a custom class or a controller action to handle the API integration. Here's an example:

saveCopyzoom_out_map
<?php namespace Devhooks\ApiIntegration\Cron; use GuzzleHttp\Client; use GuzzleHttp\ClientFactory; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\ResponseFactory; use Magento\Framework\Serialize\Serializer\Json; use Magento\Framework\Webapi\Rest\Request; class GetApiData { /** * API request URL */ const API_REQUEST_URI = 'https://dummyjson.com/'; /** * API request endpoint */ const API_REQUEST_ENDPOINT = 'products'; /** * @var ResponseFactory */ private $responseFactory; /** * @var ClientFactory */ private $clientFactory; /** * @var Json */ private $json; /** * GitApiService constructor * * @param ClientFactory $clientFactory * @param ResponseFactory $responseFactory * @param Json $json */ public function __construct( ClientFactory $clientFactory, ResponseFactory $responseFactory, Json $json ) { $this->clientFactory = $clientFactory; $this->responseFactory = $responseFactory; $this->json = $json; } /** * Fetch some data from API */ public function execute(): void { $response = $this->doRequest(static::API_REQUEST_ENDPOINT); $status = $response->getStatusCode(); // 200 status code $responseBody = $response->getBody(); $responseContent = $responseBody->getContents(); // here you will have the API response in JSON format if($status == 200){ $products = $this->json->unserialize($responseContent); foreach ($products['products'] as $product){ echo $product['id'] . "\n"; } } else{ echo $status; } } /** * 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; } }

In this example, we've created a GetApiData cron class that uses GuzzleHttp to send a GET request to a third-party API and processes the response data.

Refer this article to know How to Create Custom Cron Job in Magento 2.

Always test your API integration thoroughly and implement proper error handling to deal with API request failures or unexpected responses. You can use try-catch blocks to capture exceptions and handle them gracefully.

That's it! You've successfully integrated GuzzleHttp into your Magento 2 project to perform 3rd party API operations. This allows you to fetch data, send requests, and interact with external services to enhance the functionality of your online store.

We hope this Magento article helped you to know How to Perform 3rd party API operations in your Magento 2 using GuzzleHttp.

Bookmark it for your future reference. Do comment below if you have any other questions or doubts.

P.S. Do share this article with your team.

Review other articles maybe it'll help you too.




Recent Articles
Tags
Newsletter
Chrome Extension
Copyright © 2024 devhooks.in All rights reserved.
Ads OFF toggle_off
wifi_off