Lesson 14 โข Expert
APIs & JSON ๐
Build REST APIs, encode and decode JSON, consume external services with cURL, and structure professional API responses in PHP.
What You'll Learn in This Lesson
- โข Encode PHP arrays to JSON and decode JSON back to arrays
- โข Build a REST API that handles GET, POST, PUT, DELETE requests
- โข Consume external APIs using cURL with authentication
- โข Use proper HTTP status codes and response formats
- โข Handle JSON errors and build reusable API clients
JSON: The Language of APIs
JSON (JavaScript Object Notation) is the most common data format for APIs. PHP has built-in functions json_encode() and json_decode() to convert between PHP arrays and JSON strings. Always pass true as the second argument to json_decode() to get an associative array instead of an object.
Try It: JSON Encoding & Decoding
Convert PHP arrays to JSON and back โ learn the flags and error handling
// PHP APIs & JSON: Encoding and Decoding
console.log("=== JSON in PHP ===");
console.log();
console.log("1๏ธโฃ ENCODING โ PHP Array โ JSON String");
console.log("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ");
console.log();
// Simulate PHP's json_encode
let user = { name: "Alice", age: 28, skills: ["PHP", "MySQL", "JavaScript"] };
let jsonString = JSON.stringify(user, null, 2);
console.log("PHP: $json = json_encode($user);");
console.log("Output:");
console.log(jsonString);
console.log();
console.l
...Building a REST API
REST (Representational State Transfer) is an architectural pattern for building APIs. Each URL represents a resource, and HTTP methods define what action to take. A well-structured API uses proper status codes, consistent response formats, and input validation.
Try It: REST API Endpoints
Build GET, POST, PUT, DELETE endpoints with proper status codes
// PHP REST API: Building Endpoints
console.log("=== Building a REST API in PHP ===");
console.log();
console.log("๐ File: api/users.php");
console.log("โโโโโโโโโโโโโโโโโโโโโโโ");
console.log();
// Simulate HTTP methods
let methods = ["GET", "POST", "PUT", "DELETE"];
for (let method of methods) {
console.log("๐ " + method + " /api/users");
if (method === "GET") {
console.log(" Code: header('Content-Type: application/json');");
console.log(" $users = $pdo->query('SEL
...Consuming APIs with cURL
cURL is PHP's built-in library for making HTTP requests to external services. It supports all HTTP methods, custom headers, authentication tokens, and file uploads. For production apps, consider using Guzzle HTTP client for a cleaner API.
Try It: cURL API Client
Make GET and POST requests, add auth headers, build a reusable client
// PHP cURL: Consuming External APIs
console.log("=== Consuming APIs with cURL ===");
console.log();
console.log("1๏ธโฃ BASIC GET REQUEST");
console.log("โโโโโโโโโโโโโโโโโโโโโ");
console.log();
console.log(" $ch = curl_init('https://api.example.com/users');");
console.log(" curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);");
console.log(" $response = curl_exec($ch);");
console.log(" $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);");
console.log(" curl_close($ch);");
console.log(" $data =
...โ ๏ธ Common Mistakes
header('Content-Type: application/json') before echoing JSON. Without it, clients may misinterpret the response.$_POST only works with form data. For JSON request bodies, use json_decode(file_get_contents('php://input'), true).curl_exec() and handle timeouts gracefully./api/v1/users) from day one. This lets you make breaking changes in v2 without affecting existing clients.๐ Quick Reference โ APIs & JSON
| Function / Concept | Purpose |
|---|---|
| json_encode($data) | PHP array โ JSON string |
| json_decode($str, true) | JSON string โ PHP array |
| $_SERVER['REQUEST_METHOD'] | Get HTTP method (GET, POST, etc.) |
| file_get_contents('php://input') | Read raw JSON request body |
| http_response_code(201) | Set HTTP status code |
| curl_init() / curl_exec() | Make HTTP requests to external APIs |
๐ Lesson Complete!
You can now build and consume REST APIs in PHP! Next, explore advanced OOP design patterns for production-quality code.
Sign up for free to track which lessons you've completed and get learning reminders.