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 arrayAll lessons in this course
- JSON Encoding and Decoding
- Making HTTP Requests with cURL
- Handling API Responses and Errors
- Building a Simple API Client