Build a Modern API with Slim 4 - Add your First Route

gavinsykes

Gavin Sykes

Posted on March 5, 2023

Build a Modern API with Slim 4 - Add your First Route

Now that we have our application up and running, we need to make it actually look our for calls on certain routes, as it stands it won't actually do that as we haven't told it what to look out for.

As mentioned way back in the introduction, we will be creating a bookstore API, so let's first of all create a /books endpoint. This all goes in our src/routes folder:

src/routes/books.php

<?php

$app->group('/books', function($app) {
  $app->get('', function($request, $response, $args) {
    // Code will go here
  });
}
Enter fullscreen mode Exit fullscreen mode

And in our index file we add, between creating the app and adding the 3 middlewares:

...
AppFactory::setContainer($container);
$app = AppFactory::create();

require __DIR__ . '/../src/routes/books.php';

$app->addBodyParsingMiddleware();
...
Enter fullscreen mode Exit fullscreen mode

Wait, so, what have we actually done here? Well firstly we've included our books file in our index, as without that it will never even attempt to run it, then in our books file we've added a group called books, inside which we've added a GET endpoint with an empty endpoint, this has enabled the api.bookstore.com/books endpoint. Had we done, say, $app->get('all' ... then it would be api.bookstore.com/books/all.

However, this isn't what our final books file will look like. Ideally we want this file to just handle the routing and add any associated middlewares (JSON validation for example which won't be on every route). We need to make use of our controllers directory for this.

💖 💪 🙅 🚩
gavinsykes
Gavin Sykes

Posted on March 5, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related