0PricingLogin
PHP Academy · Lesson

Handling API Responses and Errors

Check HTTP status codes, handle errors, and parse API payloads.

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 array

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