Lab 12: JSON & APIs

Objective

Encode and decode JSON, make HTTP requests with PHP streams and cURL, build a simple REST client, and parse API responses with error handling.

Background

JSON is the lingua franca of modern APIs. PHP's json_encode/json_decode functions are fast and flexible. Making HTTP requests in PHP uses either file_get_contents with a stream context (built-in), cURL (more control), or libraries like Guzzle. Understanding raw HTTP in PHP prepares you to use any framework's HTTP client.

Time

35 minutes

Prerequisites

  • Lab 09 (Error Handling), Lab 10 (File I/O)

Tools

  • PHP 8.3 CLI

  • Docker image: zchencow/innozverse-php:latest


Lab Instructions

Step 1: json_encode & json_decode

💡 JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE are the most useful flags. Without JSON_UNESCAPED_UNICODE, Chinese/emoji characters become \uXXXX escape sequences. Without JSON_UNESCAPED_SLASHES, / becomes \/. Both flags produce cleaner, human-readable JSON.

📸 Verified Output:


Step 2: JSON Schema Validation

📸 Verified Output:


Step 3: HTTP Request with file_get_contents

💡 $http_response_header is a PHP magic variable — after file_get_contents() with an HTTP URL, it's automatically populated with the response headers as an array of strings. ignore_errors: true prevents PHP warnings on 4xx/5xx responses so you can handle them yourself.

📸 Verified Output:


Step 4: HTTP POST with JSON Body

📸 Verified Output:


Step 5: Build a Simple REST Client

💡 Wrapping HTTP logic in a RestClient class gives you a clean API: $client->get('/users/1'). This is exactly what Guzzle does internally — it wraps cURL with a fluent interface. The key difference: Guzzle adds retry, middleware, async, and PSR-7 compliance.

📸 Verified Output:


Step 6: Parse & Transform API Responses

📸 Verified Output:


Step 7: Error Handling for HTTP

📸 Verified Output:


Step 8: Complete — Mock REST API Server

💡 Mock APIs let you test your REST client code without hitting real servers — no network dependency, deterministic responses, no rate limits. This pattern is how PHPUnit tests HTTP-dependent code. Laravel's Http::fake() and Guzzle's MockHandler work on the same principle.

📸 Verified Output:


Verification

Summary

JSON and HTTP are PHP's bread and butter. You've encoded/decoded JSON, made GET/POST requests with stream contexts, built a reusable REST client, handled API errors with custom exceptions, and implemented a mock API. These skills cover 90% of real-world PHP API integration work.

Further Reading

Last updated