A futuristic, tech-inspired image with the PHP logo at the center, surrounded by interconnected nodes and symbols representing REST APIs and connectivity. The background depicts a blurred classroom or workspace environment, giving a sense of teaching and learning.

Hi there! In today’s post, I wanted to share my lecture notes on developing REST APIs using PHP, which I presented to some high school students (don’t worry, I’ve updated everything to PHP 8). These notes were written to give an outline of how a REST API works, as well as how we can use PHP to implement RESTful interactions. I hope you’ll have a clearer understanding of the concepts and feel inspired to create your own APIs!

In today’s fast-paced web development environment, RESTful APIs are essential for creating powerful and flexible applications. This tutorial guides you through the process of building a RESTful API with PHP without using a database, by storing data in arrays and later persisting that data in a JSON file for easy retrieval. We’ll cover the basic structure of a REST API, methods to handle CRUD operations, and how to save and retrieve data effectively. By the end of this guide, you’ll have a simple yet functional REST API, perfect for small projects or prototyping, and a strong foundation to expand further with more advanced features. Have a great reading!


Table of Contents

  1. Introduction to RESTful APIs
  2. Setting Up the Project
  3. Creating the Array-Based Data Store
  4. Implementing CRUD Operations
  5. Saving Data to a JSON File
  6. Retrieving Data from a JSON File
  7. Testing the API

1. Introduction to RESTful APIs

A RESTful API (Representational State Transfer) is a set of rules that allows systems to communicate over HTTP, typically in JSON format. RESTful APIs enable different applications or services to interact seamlessly, whether over the internet or within a local network.

The most common HTTP methods used in RESTful APIs include:

  • GET: Retrieve data
  • POST: Create new data
  • PUT: Update existing data
  • DELETE: Remove data

This guide will focus on developing an API that handles the following:

  • Creating an entry (POST)
  • Retrieving all entries (GET)
  • Updating an entry (PUT)
  • Deleting an entry (DELETE)

What You’ll Need

  • PHP installed (8.x is recommended)
  • A text editor (e.g., vscodium, zed, Sublime, etc.) (preference: zed)
  • Basic knowledge of PHP, file operations and arrays

2. Setting Up the Project

Let’s create a simple file structure for our API:

/myapi
    ├── api.php
    ├── data.json
  • api.php: This file will contain the logic for handling incoming requests.
  • data.json: This file will store our array of objects as JSON.

3. Creating the Array-Based Data Store

We’ll begin by defining a PHP array to represent our data. For this example, let’s assume we’re managing a list of books.

<?php

$books = [
    [
        'id' => 1,
        'title' => '1984',
        'author' => 'George Orwell',
        'year' => 1949
    ],
    [
        'id' => 2,
        'title' => 'Brave New World',
        'author' => 'Aldous Huxley',
        'year' => 1932
    ]
];

Here, we’ve created an array of books where each book is represented as an associative array with properties like id, title, author, and year.


4. Implementing CRUD Operations

Now, let’s add RESTful routes to our api.php file. Each route will handle a specific HTTP method (GET, POST, PUT, DELETE).

Handling GET Requests (Retrieving Data)

This function will return all books stored in the array.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    header('Content-Type: application/json');
    echo json_encode($books);
}

This block checks if the request method is GET. If it is, it converts the $books array to JSON and returns it to the client.

Handling POST Requests (Adding Data)

To add a new book, we’ll listen for POST requests and extract the data sent by the client.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $newBook = [
        'id' => end($books)['id'] + 1,
        'title' => $input['title'],
        'author' => $input['author'],
        'year' => $input['year']
    ];

    $books[] = $newBook;

    header('Content-Type: application/json');
    echo json_encode($newBook);
}

This code listens for POST requests, decodes the incoming JSON data, creates a new book entry with a unique ID, and adds it to the $books array.

Handling PUT Requests (Updating Data)

To update an existing book, we will use the PUT method. The client must send the updated data along with the id of the book to be modified.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $input = json_decode(file_get_contents('php://input'), true);
    $bookId = $input['id'];

    foreach ($books as &$book) {
        if ($book['id'] == $bookId) {
            $book['title'] = $input['title'];
            $book['author'] = $input['author'];
            $book['year'] = $input['year'];
            break;
        }
    }

    header('Content-Type: application/json');
    echo json_encode($input);
}

Here, we loop through the $books array, find the book by its id, and update its properties.

Handling DELETE Requests (Removing Data)

The DELETE method removes an entry based on its id.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    $input = json_decode(file_get_contents('php://input'), true);
    $bookId = $input['id'];

    foreach ($books as $key => $book) {
        if ($book['id'] == $bookId) {
            unset($books[$key]);
            break;
        }
    }

    header('Content-Type: application/json');
    echo json_encode(['message' => 'Book deleted']);
}

This code listens for DELETE requests, finds the book by its id, and removes it from the array utilising the unset function.


5. Saving Data to a JSON File

To persist our data, we’ll save the array of books to a data.json file. Each time the array is modified (after a POST, PUT, or DELETE), we’ll write the updated array to the file.

Saving the Array to JSON

At the end of each CRUD operation (POST, PUT, DELETE), we’ll add the following code to save the updated $books array to the data.json file:

file_put_contents('data.json', json_encode($books));

This function writes the current state of the $books array to data.json.

Example (Adding it to the POST Request)

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $newBook = [
        'id' => end($books)['id'] + 1,
        'title' => $input['title'],
        'author' => $input['author'],
        'year' => $input['year']
    ];

    $books[] = $newBook;

    file_put_contents('data.json', json_encode($books));

    header('Content-Type: application/json');
    echo json_encode($newBook);
}

Now, after a new book is added, the array is saved to the JSON file.


6. Retrieving Data from the JSON File

On startup, we can check if data.json exists and load data from it to initialise our $books array.

<?php

if (file_exists('data.json')) {
    $books = json_decode(file_get_contents('data.json'), true);
} else {
    $books = [];
}

This code checks if data.json exists. If it does, it populates the $books array with the contents of the file. Otherwise, it initialises $books as an empty array.


7. Testing the API

To test the API, you can use a tool like Postman or cURL.

  • GET Request: Fetch all books
    • URL: http://localhost/myapi/api.php
    • Method: GET
  • POST Request: Add a new book
    • URL: http://localhost/myapi/api.php
    • Method: POST
    • Body (JSON):
      • { "title": "The Hobbit", "author": "J.R.R. Tolkien", "year": 1937 }
  • PUT Request: Update a book
    • URL: http://localhost/myapi/api.php
    • Method: PUT
    • Body (JSON):
      • { "id": 1, "title": "1984 (Updated)", "author": "George Orwell", "year": 1949 }
  • DELETE Request: Remove a book
    • URL: http://localhost/myapi/api.php
    • Method: DELETE
    • Body (JSON):
      • { "id": 2 }

Conclusion

By following this tutorial, you’ve learnt how to create a simple RESTful API in PHP that uses an array of objects for data storage. We’ve also demonstrated how to save the array in a JSON file and retrieve it, effectively simulating a lightweight database. This approach is ideal for small projects or prototyping, providing flexibility without the need for a full-fledged database system.

As your API grows, you can expand on this foundation by introducing real database solutions, JWT based authentication, data validation, and error handling to enhance its robustness and use rate limiters to ensure 100% uptime as well.

I’ll see you at our next lecture.


Subscribe to my newsletter


ABOUT ME

Hey there! I’m Metin, also known as devsimsek—a young, self-taught developer from Turkey. I’ve been coding since 2009, which means I’ve had plenty of time to make mistakes (and learn from them…mostly).

I love tinkering with web development and DevOps, and I’ve dipped my toes in numerous programming languages—some of them even willingly! When I’m not debugging my latest projects, you can find me dreaming up new ideas or wondering why my code just won’t work (it’s clearly a conspiracy).

Join me on this wild ride of coding, creativity, and maybe a few bad jokes along the way!