Posted on

Magento 2.4 REST API POST Body params

I have the following POST request but something with the body params must be wrong when I try to pass there more than one argument. I do not get any response.

<?php
declare(strict_types=1);

namespace VendorModuleCron;

use GuzzleHttpClient;
use GuzzleHttpClientFactory;
use GuzzleHttpExceptionGuzzleException;
use GuzzleHttpPsr7Response;
use GuzzleHttpPsr7ResponseFactory;
use MagentoFrameworkWebapiRestRequest;
use PsrLogLoggerInterface;

class ApiService
{
/**
* API request URL
*/
const API_REQUEST_URI = ‘http://httpbin.org’;

/**
* API request endpoint
*/
const API_REQUEST_ENDPOINT = ‘/post’;

/**
* @var
*/
protected $_logger;

/**
* @var ResponseFactory
*/
private $responseFactory;

/**
* @var ClientFactory
*/
private $clientFactory;

/**
* @param ClientFactory $clientFactory
* @param ResponseFactory $responseFactory
* @param LoggerInterface $logger
*/
public function __construct(
ClientFactory $clientFactory,
ResponseFactory $responseFactory,
LoggerInterface $logger
) {
$this->clientFactory = $clientFactory;
$this->responseFactory = $responseFactory;
$this->_logger = $logger;
}

/**
* @param $lead_personfirstname
* @param $lead_personlastname
*/
public function execute(
$lead_personfirstname,
$lead_personlastname
) {
$response = $this->doRequest(static::API_REQUEST_ENDPOINT, [
‘body’ => [
‘lead_personfirstname’=> $lead_personfirstname,
‘lead_personlastname’=> $lead_personlastname,
]
]);

$status = $response->getStatusCode(); // 200 status code
$responseBody = $response->getBody();
$responseContent = $responseBody->getContents();
$this->_logger->info($status .$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_POST
): 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;
}
}

If I just pass it with one argument it is working fine:
$response = $this->doRequest(static::API_REQUEST_ENDPOINT, [‘body’ => $lead_personlastname]);
Can anyone please tell me what I am doing wrong above?
Thanks!

Leave a Reply

Your email address will not be published.