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

    Try it Yourself ยป
    JavaScript
    // 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

    Try it Yourself ยป
    JavaScript
    // 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

    Try it Yourself ยป
    JavaScript
    // 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

    โš ๏ธ
    Forgetting Content-Type header โ€” always set header('Content-Type: application/json') before echoing JSON. Without it, clients may misinterpret the response.
    โš ๏ธ
    Using $_POST for JSON input โ€” $_POST only works with form data. For JSON request bodies, use json_decode(file_get_contents('php://input'), true).
    โš ๏ธ
    Not checking curl_errno() โ€” cURL can fail silently. Always check for errors after curl_exec() and handle timeouts gracefully.
    ๐Ÿ’ก
    Pro Tip: Version your API URLs (/api/v1/users) from day one. This lets you make breaking changes in v2 without affecting existing clients.

    ๐Ÿ“‹ Quick Reference โ€” APIs & JSON

    Function / ConceptPurpose
    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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service