Skip to Content
Course content

47: Building a Small REST API in Vanilla PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've always found that the best way to understand REST APIs is to stop thinking about them as "special" and start thinking about them as just another way to output data. Instead of returning HTML for a browser to render, we're returning a structured string—usually JSON—for another program to parse. Let's build a tiny "Movie Watchlist" API from scratch using nothing but vanilla PHP.

Just getting some data on the screen

I'll start with the simplest possible version. I have a list of movies, and I want a client (like a frontend app or Postman) to be able to ask for them. If I just echo an array, PHP will complain or give me something useless. I need json_encode.

<?php
$movies = [
    ["id" => 1, "title" => "Inception", "watched" => true],
    ["id" => 2, "title" => "The Matrix", "watched" => false],
    ["id" => 3, "title" => "Interstellar", "watched" => true],
];

echo json_encode($movies);
?>

If I run this, it works, but there's a problem. If I check the network headers, the server is telling the client this is text/html. That's a lie. It's JSON. If a strict client tries to read this, it might choke. I need to tell the browser exactly what I'm sending.

<?php
header('Content-Type: application/json');

$movies = [
    ["id" => 1, "title" => "Inception", "watched" => true],
    ["id" => 2, "title" => "The Matrix", "watched" => false],
    ["id" => 3, "title" => "Interstellar", "watched" => true],
];

echo json_encode($movies);
?>

Wait, we need to know what the client actually wants

Right now, this script just dumps the whole list regardless of how it's called. But a real API needs to handle different actions. If I send a GET request, I want the list. If I send a POST request, I probably want to add a movie. I can use the $_SERVER superglobal to figure out what's happening.

<?php
header('Content-Type: application/json');

$method = $_SERVER['REQUEST_METHOD'];
$movies = [
    ["id" => 1, "title" => "Inception", "watched" => true],
    ["id" => 2, "title" => "The Matrix", "watched" => false],
];

if ($method === 'GET') {
    echo json_encode($movies);
} elseif ($method === 'POST') {
    // I'll handle adding a movie here in a moment
    echo json_encode(["message" => "You tried to add a movie!"]);
} else {
    http_response_code(405); // Method Not Allowed
    echo json_encode(["error" => "Method not supported"]);
}
?>

The JSON input trap

Now I want to actually process the data sent in a POST request. My first instinct is to use $_POST, but here's the catch: $_POST only works if the data is sent as application/x-www-form-urlencoded (like a standard HTML form). Most modern API clients send data as a raw JSON string in the request body.

I tried print_r($_POST) and got an empty array. Frustrating, but common. To get the raw body, I have to read from the PHP input stream.

<?php
// ... existing headers and movie array ...

if ($method === 'POST') {
    // Read the raw input stream
    $json = file_get_contents('php://input');
    
    // Turn that JSON string into a PHP associative array
    $data = json_decode($json, true);

    if (!isset($data['title'])) {
        http_response_code(400); // Bad Request
        echo json_encode(["error" => "Movie title is required"]);
        exit;
    }

    $newMovie = [
        "id" => count($movies) + 1,
        "title" => $data['title'],
        "watched" => $data['watched'] ?? false
    ];

    // In a real app, this goes to a DB. For now, I'll just simulate success.
    echo json_encode(["message" => "Movie added!", "movie" => $newMovie]);
}
?>

Targeting a specific movie

One last thing: I don't always want the whole list. I want to be able to say "give me movie #2". Since I'm using a single file for this API, the easiest way to do this without a complex routing library is via a query parameter, like api.php?id=2.

I'll tweak my GET block to check for that ID. I'll also use array_filter to find the specific movie, which is cleaner than a foreach loop for this purpose.

<?php
// ... inside the GET block ...
if ($method === 'GET') {
    if (isset($_GET['id'])) {
        $id = (int)$_GET['id'];
        $result = array_filter($movies, fn($m) => $m['id'] === $id);
        
        if (empty($result)) {
            http_response_code(404);
            echo json_encode(["error" => "Movie not found"]);
        } else {
            // array_filter preserves keys, so I'll use array_values to reset it to 0
            echo json_encode(array_values($result)[0]);
        }
    } else {
        echo json_encode($movies);
    }
}
?>

It's not a full-blown framework, but it's functional. We've handled content types, HTTP methods, raw JSON input, and basic resource filtering. This is the core of how every major API works under the hood.




📋 Practical Task

Building a Simple Habit Tracker API

Your task is to build a vanilla PHP REST API that manages a list of daily habits. Instead of movies, you will manage habits (e.g., "Drink Water", "Read 10 Pages").

  • Create a file named habits.php.
  • Start with a hardcoded array of 3 habits, each with an id, a name, and a completed boolean.
  • Implement a GET request that:
    • Returns the full list if no ID is provided.
    • Returns a single habit if an id query parameter is provided.
    • Returns a 404 Not Found error if the ID doesn't exist.
  • Implement a POST request that:
    • Reads a JSON body containing a name.
    • Returns a 400 Bad Request if the name is missing.
    • Returns a success message and the "created" habit object if successful.
  • Ensure the Content-Type: application/json header is set for all responses.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.