Handling API Responses and Errors
Check HTTP status codes, handle errors, and parse API payloads.
Handling API Responses and Errors is a free PHP Academy lesson on CoddyKit — lesson 3 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.
Check HTTP Status Code
Always check the HTTP status code before processing the response body.
<?php
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($statusCode !== 200) {
throw new RuntimeException("API error: HTTP $statusCode");
}Parse JSON Response
Decode the JSON body and handle parse errors.
<?php
$body = curl_exec($ch);
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
// $data is now a PHP arrayError Response Bodies
APIs often return error details in the body even for 4xx/5xx responses. Always parse and log the body on errors.
<?php
if ($statusCode >= 400) {
$err = json_decode($body, true);
$msg = $err["message"] ?? "Unknown API error";
throw new RuntimeException("API $statusCode: $msg");
}cURL Transport Errors
Network errors (DNS failure, timeout) are separate from HTTP errors. Check curl_errno() first, then HTTP status.
<?php
if (curl_errno($ch)) {
throw new RuntimeException("Transport error: ".curl_error($ch));
}Wrapping in a Helper Function
Encapsulate cURL setup, execution, and error handling in a reusable function.
<?php
function httpGet(string $url, string $token): array {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer $token"],
CURLOPT_TIMEOUT => 15,
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$errno = curl_errno($ch);
curl_close($ch);
if ($errno) throw new RuntimeException(curl_strerror($errno));
if ($status >= 400) throw new RuntimeException("HTTP $status");
return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}Retry Logic
For transient errors (503 Service Unavailable, timeouts), implement exponential backoff with a retry limit.
<?php
$maxRetries = 3;
for ($attempt = 0; $attempt < $maxRetries; $attempt++) {
try {
$data = httpGet($url, $token);
break;
} catch (RuntimeException $e) {
if ($attempt === $maxRetries - 1) throw $e;
sleep(2 ** $attempt);
}
}Rate Limiting Headers
Many APIs include rate-limit headers: X-RateLimit-Remaining and X-RateLimit-Reset. Read them to avoid hitting limits.
<?php
curl_setopt($ch, CURLOPT_HEADER, true);
// Parse headers from the response stringResponse Caching
Cache API responses to avoid redundant network calls. Store responses in Redis or APCu with a TTL matching the data freshness requirement.
Logging API Calls
Log request URL, method, status code, and latency to aid debugging and monitor API health in production.
Timeouts as Errors
A cURL timeout (CURLE_OPERATION_TIMEDOUT) is a transport error, not an HTTP error. Handle it explicitly.
SSL Certificate Errors
Certificate validation failures (CURLE_SSL_CACERT) mean the server certificate is untrusted. Update your CA bundle, never disable verification.
Summary
Always check cURL errno first, then HTTP status. Parse error bodies. Wrap logic in reusable functions. Implement retry for transient failures.
Quick Check
Which should you check first: cURL errno or HTTP status?
Frequently asked questions
Is the “Handling API Responses and Errors” lesson free?
Yes — the full text of “Handling API Responses and Errors” 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 “Handling API Responses and Errors”?
Check HTTP status codes, handle errors, and parse API payloads. 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 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Handling API Responses and Errors” 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
- JSON Encoding and Decoding
- Making HTTP Requests with cURL
- Handling API Responses and Errors
- Building a Simple API Client