Tag: Lesson 17: PHP and APIs

  • Lesson 17: PHP and APIs

    APIs (Application Programming Interfaces) allow systems to communicate with each other. RESTful APIs are widely used in web applications to exchange data. In this lesson, you will learn how to consume RESTful APIs and build a simple REST API using PHP.


    Lesson Outline

    1. Introduction to RESTful APIs
    2. Consuming RESTful APIs
    3. Building a Simple REST API with PHP

    17.1 Introduction to RESTful APIs

    What is a RESTful API?

    • REST (Representational State Transfer) is an architectural style for designing APIs.
    • Key Features:
      • Stateless: Each request is independent and contains all necessary information.
      • HTTP Methods: Standard HTTP methods are used for CRUD operations:
        • GET: Retrieve data.
        • POST: Create data.
        • PUT: Update data.
        • DELETE: Delete data.
      • Resource-based: Data is represented as resources (e.g., /users, /products).

    17.2 Consuming RESTful APIs

    Fetching Data with file_get_contents

    Example: Fetching Data from a Public API

    php
    <?php
    $url = "https://jsonplaceholder.typicode.com/posts";
    $response = file_get_contents($url);
    $data = json_decode($response, true); // Decode JSON response into an array
    foreach ($data as $post) {
    echo “Title: “ . $post[‘title’] . “<br>”;
    echo “Body: “ . $post[‘body’] . “<hr>”;
    }
    ?>


    Using cURL to Consume APIs

    What is cURL?

    • cURL is a library in PHP for making HTTP requests.

    GET Request with cURL

    php
    <?php
    $url = "https://jsonplaceholder.typicode.com/posts";
    $ch = curl_init($url); // Initialize cURL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
    $response = curl_exec($ch); // Execute the request
    curl_close($ch); // Close cURL

    $data = json_decode($response, true); // Decode JSON response

    foreach ($data as $post) {
    echo “Title: “ . $post[‘title’] . “<br>”;
    echo “Body: “ . $post[‘body’] . “<hr>”;
    }
    ?>


    POST Request with cURL

    php
    <?php
    $url = "https://jsonplaceholder.typicode.com/posts";
    $data = [
    'title' => 'New Post',
    'body' => 'This is the content of the post.',
    'userId' => 1
    ];
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
    ‘Content-Type: application/json’,
    ‘Content-Length: ‘ . strlen(json_encode($data))
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    echo “Response: “ . $response;
    ?>


    17.3 Building a Simple REST API with PHP

    Setting Up the Environment

    1. Create a new database api_demo and a table users:
      sql

      CREATE DATABASE api_demo;

      USE api_demo;

      CREATE TABLE users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(100),
      email VARCHAR(100),
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );

    2. Insert sample data:
      sql
      INSERT INTO users (name, email) VALUES
      ('Alice', 'alice@example.com'),
      ('Bob', 'bob@example.com');
    3. Create a file db.php for database connection:
      php
      <?php
      $host = "localhost";
      $username = "root";
      $password = "";
      $database = "api_demo";
      try {
      $conn = new PDO(“mysql:host=$host;dbname=$database, $username, $password);
      $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      } catch (PDOException $e) {
      die(“Connection failed: “ . $e->getMessage());
      }
      ?>


    Creating the REST API

    Step 1: API Endpoint Structure

    • /api/users – GET (Retrieve all users)
    • /api/users/:id – GET (Retrieve a specific user)
    • /api/users – POST (Create a new user)
    • /api/users/:id – PUT (Update a user)
    • /api/users/:id – DELETE (Delete a user)

    Step 2: Base API File (api.php)

    php
    <?php
    require 'db.php';
    header(“Content-Type: application/json”);

    $requestMethod = $_SERVER[“REQUEST_METHOD”];
    $requestUri = explode(“/”, trim($_SERVER[“REQUEST_URI”], “/”));

    // Extract resource and ID
    $resource = $requestUri[1] ?? null;
    $id = $requestUri[2] ?? null;

    if ($resource !== ‘users’) {
    http_response_code(404);
    echo json_encode([‘message’ => ‘Resource not found’]);
    exit;
    }
    ?>


    Step 3: Handle GET Requests

    php
    if ($requestMethod === 'GET') {
    if ($id) {
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    $stmt->execute();
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user) {
    echo json_encode($user);
    } else {
    http_response_code(404);
    echo json_encode([‘message’ => ‘User not found’]);
    }
    } else {
    $stmt = $conn->query(“SELECT * FROM users”);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($users);
    }
    }


    Step 4: Handle POST Requests

    php
    if ($requestMethod === 'POST') {
    $data = json_decode(file_get_contents("php://input"), true);
    $stmt = $conn->prepare(“INSERT INTO users (name, email) VALUES (:name, :email)”);
    $stmt->bindParam(‘:name’, $data[‘name’]);
    $stmt->bindParam(‘:email’, $data[’email’]);

    if ($stmt->execute()) {
    http_response_code(201);
    echo json_encode([‘message’ => ‘User created’]);
    } else {
    http_response_code(500);
    echo json_encode([‘message’ => ‘Error creating user’]);
    }
    }


    Step 5: Handle PUT Requests

    php
    if ($requestMethod === 'PUT' && $id) {
    $data = json_decode(file_get_contents("php://input"), true);
    $stmt = $conn->prepare(“UPDATE users SET name = :name, email = :email WHERE id = :id”);
    $stmt->bindParam(‘:id’, $id);
    $stmt->bindParam(‘:name’, $data[‘name’]);
    $stmt->bindParam(‘:email’, $data[’email’]);

    if ($stmt->execute()) {
    echo json_encode([‘message’ => ‘User updated’]);
    } else {
    http_response_code(500);
    echo json_encode([‘message’ => ‘Error updating user’]);
    }
    }


    Step 6: Handle DELETE Requests

    php
    if ($requestMethod === 'DELETE' && $id) {
    $stmt = $conn->prepare("DELETE FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id);
    if ($stmt->execute()) {
    echo json_encode([‘message’ => ‘User deleted’]);
    } else {
    http_response_code(500);
    echo json_encode([‘message’ => ‘Error deleting user’]);
    }
    }


    Testing the API

    1. Use tools like Postman or cURL to test API endpoints.
    2. Example cURL commands:
      • GET all users:
        bash
        curl -X GET http://localhost/api/users
      • POST a new user:
        bash
        curl -X POST -H "Content-Type: application/json" -d '{"name":"Charlie","email":"charlie@example.com"}' http://localhost/api/users

    Activities and Exercises

    1. Consuming APIs:
      • Fetch and display posts from the JSONPlaceholder API using cURL.
    2. Building APIs:
      • Extend the users API to include user authentication (e.g., login).
    3. Validation:
      • Add validation for user input (e.g., email format, required fields) in the POST and PUT endpoints.

    Assignment

    1. Create a database library with tables:
      • books: id, title, author.
      • users: id, name, email.
      • borrowed_books: id, user_id, book_id, borrowed_at.
    2. Build an API with the following endpoints:
      • /api/books (GET): Retrieve all books.
      • /api/users/:id/borrowed (GET): Retrieve books borrowed by a user.
      • /api/borrow (POST): Borrow a book.