PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
47: Building a Small REST API in Vanilla PHP
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, aname, and acompletedboolean. - Implement a
GETrequest that:- Returns the full list if no ID is provided.
- Returns a single habit if an
idquery parameter is provided. - Returns a
404 Not Founderror if the ID doesn't exist.
- Implement a
POSTrequest that:- Reads a JSON body containing a
name. - Returns a
400 Bad Requestif thenameis missing. - Returns a success message and the "created" habit object if successful.
- Reads a JSON body containing a
- Ensure the
Content-Type: application/jsonheader is set for all responses.
There are no comments for now.