0Pricing
PHP Academy · Lesson

Building a Simple API Client

Wrap cURL calls in a reusable PHP API client class.

Building a Simple API Client is a free PHP Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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);
    }
}

GET and POST Methods

Expose convenience methods that delegate to the private request() method.

<?php
public function get(string $path): array {
    return $this->request("GET", $path);
}

public function post(string $path, array $body): array {
    return $this->request("POST", $path, $body);
}

Using the Client

Instantiate and call typed methods instead of raw cURL.

<?php
$client = new ApiClient("https://api.example.com", $apiToken);
$users  = $client->get("/v1/users");
$user   = $client->post("/v1/users", ["name" => "Alice", "email" => "alice@example.com"]);

Query String Parameters

Build query strings with http_build_query().

<?php
public function get(string $path, array $params = []): array {
    $qs = $params ? "?".http_build_query($params) : "";
    return $this->request("GET", $path.$qs);
}
// Usage:
$users = $client->get("/v1/users", ["page" => 1, "limit" => 20]);

Pagination Helper

Add a helper to collect all pages of a paginated API automatically.

<?php
public function paginate(string $path): array {
    $all  = [];
    $page = 1;
    do {
        $res  = $this->get($path, ["page" => $page++]);
        $all  = array_merge($all, $res["data"]);
    } while ($res["has_more"] ?? false);
    return $all;
}

Caching Responses

Inject a cache layer to avoid redundant requests.

<?php
public function getCached(string $path, int $ttl = 60): array {
    $key = "api:".md5($path);
    if (apcu_exists($key)) return apcu_fetch($key);
    $data = $this->get($path);
    apcu_store($key, $data, $ttl);
    return $data;
}

Logging

Add a PSR-3 logger to record every request and response for debugging.

<?php
public function __construct(
    private string $baseUrl,
    private string $token,
    private ?\Psr\Log\LoggerInterface $logger = null
) {}

Testing the Client

In unit tests, replace cURL with a mock HTTP handler (e.g. Guzzle MockHandler) so tests run without real network calls.

Guzzle as an Alternative

For production use, consider Guzzle (composer require guzzlehttp/guzzle), which provides middleware, async requests, and a polished API.

HTTP_FOUNDATION Option

Symfony HttpClient (symfony/http-client) is another excellent alternative with a clean interface and first-class async support.

Summary

Wrapping cURL in a class reduces duplication, centralises error handling, and makes testing easier. Expose typed methods (get, post) over raw HTTP verbs.

Quick Check

Which PHP function builds URL query strings?

Frequently asked questions

Is the “Building a Simple API Client” lesson free?

Yes — the full text of “Building a Simple API Client” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Building a Simple API Client”?

Wrap cURL calls in a reusable PHP API client class. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Building a Simple API Client” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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