Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Melodia's avatar

How do I format json data from api call?

My snippet looks like this:

$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://example.example.co.za/api/consumers/get?id=32223&[email protected]",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_POSTFIELDS => "",
    CURLOPT_HTTPHEADER => array(
    "Accept: */*",
    "Authorization: Bearer thetoken",
    "Cache-Control: no-cache",
    "Connection: keep-alive",
    "Content-Type: application/x-www-form-urlencoded",
    "accept-encoding: gzip, deflate",
    "cache-control: no-cache",
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

return $response;

The response shows me an object like this:

{
    success: true,
    count: 1,
    data: [{
       id: 3429217,
       brand_id: 2323,
       first_name: "My name",
    }]
}

First: Instead of return the entire JSON, how can I return only the data inside the data key? Second: What would be the best way to do this API call?

0 likes
2 replies
mabdullahsari's avatar
  1. You need to return $response['data'] instead of the whole assoc array.

  2. I would recommend the use of GuzzleHttp instead of plain curl: http://docs.guzzlephp.org/en/stable/ If the HTTP endpoint is often going to be hit, I'd consider abstracting it away into a separate ApiClient which you initialize only once and then call methods from it to fetch data.

If you are into tests, you can resolve the client via the IoC container to swap it with a fake implementation during your tests because network requests are generally too slow for non-integration tests.

An example (might not work):

class ApiClient
{
    private $http;

    public function __construct(?string $token, $baseURL = null)
    {
        if ($token = null) {
            throw new \Exception();
        }

        $options = ['headers' => ['Authorization' => 'Bearer ' . $token]];

        if (isset($baseURL)) {
            $options['base_uri'] = $baseURL;
        }

        $this->http = new \GuzzleHttp\Client($options);
    }

    public function fetchConsumers(array $query): array
    {
        try {
            $res = $this
                ->http
                ->get($this->getUrl('consumers/get'), compact('query'));
        } catch (Exception $ex) {
            \Log::error($ex);
            return [];
        }

        return $this->asArray($res);
    }

    private function getUrl(string $endpoint): string
    {
        return $this->http->getConfig('base_uri') . '/' . $endpoint;
    }

    private function asArray(ResponseInterface $res)
    {
        return json_decode($res->getBody()->getContents(), true);
    }
}

Register the client as a singleton in AppServiceProvider, e.g.

$this->app->singleton(ClientContract::class, static function () {
    return new ApiClient(config('external_api.token'), config('external_api.base_uri'));
});

Just to give you an idea of how the problem can be tackled, do not take it as an absolute thing.

1 like

Please or to participate in this conversation.