Dec 10, 2021
0
Level 13
Guzzle client. Working with params on remote API that has a param Array of strings json
I am working with an API (Cpanel) that in some endpoints allows the passing of a parameter made up of an array of string json
As it has many endpoints I had already structured everything as a base class in which I mount the call -> get through a Guzzle client.
$response = $client->get($endpoint, [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'whm root:' .config('whmapi.token')
],
'query' => $this->params
]);
The problem is that none of the options I have tried has been correct, except for a somewhat far-fetched one.
array of json
add={"dname":"em5768.pruebas.com","ttl":3600,"record_type":"CNAME","data":["u23123539.wl040.sendgrid.net"]}&add={"dname":"em5769.pruebas.com","ttl":3600,"record_type":"CNAME","data":["u23123540.wl040.sendgrid.net"]}
Way 1
Create a method on class for this action, that get array of array and convert in a unique param
$params = [
"api.version" => 1
"serial" => 2021121005
"zone" => "pruebas.com"
"add" => "{"dname":"em5768.pruebas.com","ttl":3600,"record_type":"CNAME","data":["u23123539.wl040.sendgrid.net"]}&add={"dname":"em5769.pruebas.com","ttl":3600,"record_type":"CNAME","data":["u23123540.wl040.sendgrid.net"]}"
]
This fails because Guzzle decode & in the middle of the param add
Working way that works
public function getRequest(bool $params = true)
{
$client = new Client();
$endpoint = $this->endpoint;
// @todo I needs improve
if (!empty($this->stringify_params)) {
$stringify = '?';
foreach ($this->stringify_params as $key => $param) {
$stringify .= $key . '=' . $param . '&';
}
$stringify = rtrim($stringify, '&');
$endpoint .= $stringify;
$this->params = [];
// I needs this because if `query` is equals to empty array remote API fails
if ($params) {
$response = $client->get($endpoint, [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'whm root:' .config('whmapi.token')
],
]);
}
} else {
if ($params) {
$response = $client->get($endpoint, [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'whm root:' .config('whmapi.token')
],
'query' => $this->params
]);
}
}
return $result;
}
Please or to participate in this conversation.