DEV Community

Gavin Sykes
Gavin Sykes

Posted on

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:



$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:

$app = AppFactory::create();

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

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 endpoint. Had we done, say, $app->get('all' ... then it would be

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.

Top comments (0)