CodeBlanks Logo Icon CodeBlanks

Project: REST API

PHP course · Advanced · Lesson 55/92

Overview of the 5-lesson REST API project: a task API with JSON, PDO and routing.

Project: REST API

In this five-lesson project you'll build a REST API. Each lesson adds one piece, and by the final lesson you'll complete a working task API.

You'll use PDO queries, class design and superglobals from previous groups. Throughout the project you'll design a Router class that directs each request to the right handler by method and path. Then you'll add the addRoute, dispatch methods and a response class named JsonResponse.

Project roadmap

The project has five lessons. In the second you'll register routes with addRoute and read the incoming request from $_SERVER['REQUEST_METHOD'] and $_SERVER['PATH_INFO']. In the third you'll find the matching route with dispatch and call its handler.

In the fourth you'll send status code, header and structured body together using the JsonResponse class. In the final lesson you'll write the handleGet, handlePost, handlePut and handleDelete handlers and combine every part.

Exercise Define the Router class

Write the first piece of this project. Define a class named Router. Add a public array $routes = []; property. Then create an instance with $router = new Router(); and print the route count with echo count($router->routes);.

Show example solution
Declare the class with class Router { ... }. Add public array $routes = [];. Then create an instance with $router = new Router(); and print with echo count($router->routes);.
Example solution:
<?php
// Router skeleton for the REST API project

class Router {
    public array $routes = [];
}

$router = new Router();
echo count($router->routes);

Test yourself

  1. What does the Router class do in this project?

    • It directs each request to the right handler by method and path
    • It connects to the database directly and creates tables
    • It generates an HTML form and sends it to the browser
    • It manages sessions and cookies
    Show answer

    It directs each request to the right handler by method and path — Correct. The Router looks at method and path and calls the matching handler, so all requests are dispatched from one place.

  2. Complete the class name

    class ____ {
        public array $routes = [];
    }
    Show answer
    class Router {
        public array $routes = [];
    }
  3. Match the project concepts

    Router
    Routes requests
    addRoute
    Adds a route
    dispatch
    Calls the matched route
    JsonResponse
    Structured response

All lessons in Advanced