Lab 09: REST API Development

Objective

Build a complete RESTful API using only PHP's built-in server capabilities: HTTP method routing, URL parsing with parse_url, JSON request/response handling, middleware pipeline for auth and logging, HTTP status codes, input validation, and proper error responses.

Background

Every PHP framework (Laravel, Symfony, Slim) is ultimately a router + middleware stack on top of PHP's request/response model. PHP receives requests via $_SERVER, reads input via php://input, and sends headers with header(). Understanding the raw HTTP layer makes frameworks transparent. A REST API maps HTTP methods (GET/POST/PUT/DELETE) to CRUD operations on resources.

Time

30 minutes

Prerequisites

  • PHP Practitioner Lab 04 (PDO & Repository)

Tools

  • Docker: zchencow/innozverse-php:latest


Lab Instructions

Step 1: Router, middleware, JSON API — full simulation

💡 Middleware runs before and after your handler. The pipeline run() method builds a chain: each middleware calls $next() to continue the chain. The logging middleware runs before (logs the request), then $next() invokes the next middleware (auth check), then $next() in auth invokes the router. After the handler returns, each middleware can process the response too. This is how Laravel Middleware, Express.js, and Django Middleware all work.

📸 Verified Output:


Summary

HTTP Method
Route
Action
Status

GET

/api/products

List all

200

GET

/api/products/{id}

Get one

200 / 404

POST

/api/products

Create

201 / 422

PUT

/api/products/{id}

Update

200 / 404

DELETE

/api/products/{id}

Remove

200 / 404

Further Reading

Last updated