0Pricing
PHP Academy · Lesson

Building a Simple API Client

Wrap cURL calls in a reusable PHP API client class.

Why Wrap cURL?

A dedicated API client class centralises authentication, base URL, error handling, and logging — avoiding repetitive boilerplate across the codebase.

Client Class Skeleton

A minimal API client with a base URL and auth token.

<?php
class ApiClient {
    public function __construct(
        private string $baseUrl,
        private string $token
    ) {}

    private function request(string $method, string $path, array $data = []): array {
        $ch = curl_init($this->baseUrl.$path);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_HTTPHEADER     => [
                "Authorization: Bearer ".$this->token,
                "Content-Type: application/json",
                "Accept: application/json",
            ],
        ]);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        $body   = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($status >= 400) throw new RuntimeException("API error $status: $body");
        return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
    }
}

All lessons in this course

  1. JSON Encoding and Decoding
  2. Making HTTP Requests with cURL
  3. Handling API Responses and Errors
  4. Building a Simple API Client
← Back to PHP Academy