Skip to Content
Course content

139: Practice Exercise: Building a RESTful API with Slim Framework

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

A few years ago, I worked with a developer named Marcus who was building a backend for a niche mobile app. He didn't want the overhead of a full-stack framework, so he decided to "keep it simple" by using vanilla PHP. He ended up with a directory full of files like get_user.php, update_user.php, and delete_post.php. Whenever he wanted to change a URL structure or add a middleware check for authentication, he had to manually edit dozens of files. It was a maintenance nightmare. He eventually came to me exhausted, asking why his "simple" approach felt so complex. That's when I introduced him to Slim.

Slim is what we call a micro-framework. It doesn't try to give you an ORM, a template engine, or a complex folder structure. Instead, it does one thing exceptionally well: it maps an HTTP request to a specific piece of code. In the world of RESTful APIs, this is exactly what you need. You get a clean way to define your endpoints, handle different HTTP methods (GET, POST, PUT, DELETE), and manage the request and response cycle without getting bogged down in the plumbing of PHP's global variables.

Defining Clean API Endpoints

In a RESTful architecture, the URL should represent the resource, and the HTTP method should represent the action. When you're using Slim, you stop thinking about "files" and start thinking about "routes." Instead of routing a user to /api/books/delete.php?id=12, you define a route for DELETE /books/{id}. This makes your API intuitive for whoever is consuming it.

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// A simple GET endpoint to fetch a list of books
$app->get('/books', function (Request $request, Response $response) {
    $books = [
        ['id' => 1, 'title' => 'The Pragmatic Programmer', 'author' => 'Hunt & Thomas'],
        ['id' => 2, 'title' => 'Clean Code', 'author' => 'Robert C. Martin'],
    ];
    
    $payload = json_encode($books);
    $response->getBody()->write($payload);
    return $response->withHeader('Content-Type', 'application/json');
});

$app->run();

I love how explicit this is. You can see at a glance that /books handles GET requests. If you tried to send a POST request to that same URL, Slim would automatically handle the 405 Method Not Allowed response for you, saving you from writing that logic yourself.

Managing the Request-Response Cycle

One of the biggest hurdles for developers moving from vanilla PHP to Slim is the shift toward PSR-7. In the old way, you'd just echo a string and call exit(). In Slim, you work with Request and Response objects. This might feel like extra work at first, but it's actually a superpower. Because the response is an object, you can pass it through various middleware—like an authentication layer—that can modify the headers or the body before it ever reaches the user.

When building a REST API, you'll frequently deal with JSON payloads. Instead of accessing $_POST, you'll use the request object to parse the body. This ensures that your API can handle application/json content types, which is the standard for modern front-ends. You wrap your data in json_encode(), write it to the response body, and crucially, set the Content-Type header so the client knows how to parse the result.




📋 Practical Task

Exercise: Building a Gadget Inventory API

Your task is to build a small RESTful API using the Slim Framework to manage a collection of electronic gadgets. You don't need a database for this; a simple hard-coded array will suffice to simulate your data store.

Requirements:

  • GET /gadgets: Return a JSON list of all gadgets. Each gadget should have an id, name, and category.
  • GET /gadgets/{id}: Return a single gadget based on the ID provided in the URL. If the ID doesn't exist in your array, return a 404 Not Found response.
  • POST /gadgets: Accept a JSON payload containing a name and category, and return the created gadget along with a 201 Created status code.

Constraint: Ensure all responses are sent with the Content-Type: application/json header. Use PSR-7 Request and Response objects throughout your routes.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.