Learn How to Create a REST API Using Slim Framework – TUTORIAL

As soon as you hear the word API, one of the first things that might come to your mind would be Node.js or Django, or Java. But today let’s dive into the PHP world and learn about a micro framework called Slim. But hey, isn’t Laravel the most popular framework for PHP? What’s the point of learning something new again? You might ask. Notice that I said Slim Framework was a micro framework which means it only has the essential utilities and is very lightweight for creating APIs. There certainly are a bunch of apps/websites out there that require the code to be very fast, minimal & micro.

What is Slim Framework?

slim framework logo

As we discussed, slim is a micro framework that helps us to quickly write REST APIs. Before moving to the tutorial, let’s have a deeper look into what exactly Slim Framework is and have a look at its Advantages and Disadvantages compared to other popular frameworks 

Advantages

  1. Since slim is minimal, it’s a good starting point for developers wanting to get into the world of PHP Development
  2. Supports all major packages that frameworks like Laravel support
  3. The Slim framework is Open Sourced
  4. Supports REST based structure 
  5. Great documentation and support for beginners

Disadvantages

  1. There are more differences between different versions (for eg, Slim 2 and Slim 3 have so many differences that it might require you to re-learn the whole framework)
  2. It might be too minimal depending on your needs

Overall you get the idea that the Slim framework is a good starting point to get into PHP and Rest API development. And might not be suitable for your app if you require advanced features and do not care about having heavy frameworks in your app

How to learn Slim Framework?

The best way to learn something, not just Slim is to “Learn by Doing”. In this tutorial, we’ll learn to build and test the API. The API we’ll be building will serve the Details of Vaccinated people, in a locality/state/region. To give you a quick overview the API will support the following queries

  • Getting the List of Vaccinated People
  • Getting the List of Un – Vaccinated People
  • Getting The Percentage of Vaccinated People
  • Checking the vaccination status of a person

Part 1: Installing Essential Tools for Slim Framework

If you visit the official website of Slim https://slimframework.com, you’ll find that there is no “link” to download/install slim.

That’s because slim is not available to us directly and we have to install it using Composer.

If you’ve never heard of Composer, it’s a dependency manager for PHP applications. A dependency manager is a tool that allows us to install/remove frameworks from PHP projects. This is the equivalent of Node Package Manager (NPM) for Node.js

Installing PHP

php logo

Before getting started and installing Composer Slim, Let’s first install PHP

  • Firstly visit the official download website of PHP https://www.php.net/downloads.php 
  • Based on your Operating System download the required file and follow the on-screen instructions
  • Try to download the Latest Version of PHP available (which is 8.1.8 as of writing this article) 

Now PHP should be installed on your computer

To test your PHP installation, open your CMD or Powershell and run the following command

php --version

If your installation was successful you should get the following output 

Installing Composer

composer logo

To install dependencies such as frameworks in any PHP application, we first have to install a tool called Composer which will easily allow us to install Slim, to install composer 

You will then find a section for Manual Installation

Download, the latest Stable release, which would be the first option

  • This should download a composer.phar file to your Downloads folder
  • Copy this file to your Home or Downloads folder or somewhere it is easily accessible 

Installing Slim

Now that we have PHP and Composer installed, let’s move on to installing Slim in the PHP project

To create a Sample Slim project and install Slim, run the following command in your Home or Downloads folder (the folder where you downloaded Composer

PHP composer.phar create-project slim/slim-skeleton:dev-master covid-vaccination 

This should execute the following process and your project will be created!  Here slim-skeleton is a starter template provided to us by the slim development team

creating new slim project

Now you should notice a new folder called covid-vaccination, this is where the project will reside 

Installing Visual Studio Code (Optional) 

vscode home screen

Since we’ll be writing tons of code for the API, it would be wise to use an advanced IDE/Code Editor. If you don’t know what an IDE (Integrated Development Environment)  is, it’s essentially a tool that helps us to quickly write codes by providing awesome features such as Syntax highlighting, Integrated Terminal, Error Detection, and a lot more! There are many popular IDEs available on the market, but for our purposes, we’ll be using something called Visual Studio Code, as it’s the most popular and easy-to-use IDE currently in the market.

Part 2: Understanding the File Structure for Slim Framework

slim framework file structure

If you open the project folder now, you’ll find that there are many files and folders. If this is your first PHP project, it might be hard to even find the files in which you are supposed to write code in. Do not worry as we’ll dedicate an entire section to understanding the directory structure of almost any PHP project. Do pay close attention, as this would certainly help you in your future projects as well 

The main “index.php” file

public folder slim framework

Inside the public/ folder, you’ll find the index.php file. You can consider this to be the “main” entry point of the program or even the “main” file of the entire project as whenever a user visits the API, this would be the file that is being run. 

This is the file where we’ll write most of our code

The “src” folder

src folder slim framework

The contents of this folder should be pretty obvious by its name. The “src” folder will contain Source Code for the server. You might then question, why we even need the src folder when we can write the source code in the index.php file. The truth is you don’t. For a small application, it’s totally fine to fit the whole code in the index.php file itself. But for larger projects and API it doesn’t make sense to put the whole code in one single file itself. Therefore we split the code into multiple modules and these modules are stored inside the src folder

The “app” folder

app folder postman

This folder is specific to the Slim Skeleton project only. It contains the essential info for the app, such as its Settings, Dependencies, etc. For our application, we generally wouldn’t need to deal with it

The “tests” folder

tests folder slim framework

The Slim starter template, by default, adds support for performing Tests in the app. Since covering Unit Testing is not in the scope of this article. We can ignore this folder as of now. 

The “vendor” folder

slim framework vendor folder structure

This is a PHP-managed folder that is not intended for us to modify/edit. This is where all of the dependencies of the project (for eg. Slim) are stored. Generally, when uploading the project to GitHub/BitBucket. It’s a good idea that we make sure this folder is not uploaded, as it is generally large and is not something that we manage on our own

Part 3: Basic Setup for Slim Framework

index.php file slim framework

As discussed, we’ll be mostly working on the public/index.php file, so let’s start by opening that in the editor first.

You might then see some code like this 

Do not worry about the code, as we’ll be clearing all of that, and starting from the ground up. This should give you a good understanding of how things work.

So let’s clear the file, and start by writing the following code

<?php

use Slim\Factory\AppFactory;

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

$app = AppFactory::create();

$app->run();


?>

Let’s try to walk through the code step-by-step

  1. The first thing to notice would be that we write all of the PHP code inside the <?PHP ?> tag
  2. Then to create the Slim App, Slim provides us with a class called AppFactory. To use that in the index.php file, we have to add the line use Slim\Factory\AppFactory
  3. Then to autoload all of the the classes in Slim framework, we also need to require (or include) the autoload.php file inside the vendor folder (recall that the vendor folder has all the installed dependencies)
  4. Then we create the Slim App by using the Create function inside AppFactory and store the created app inside the $app variable
  5. To run the $app we simply add $app->run(); to the file

To run the PHP app, we start the server by executing the following command

php -S localhost:8080 -t public public/index.php 

If you look closely, you can understand what the command is trying to say,

  • -S: Start the server on the website localhost:8080
  • -t type of the server is public
  • And the main file of the server is public/index.php

After running the command you will notice that the PHP server has started, but when you try to go to localhost:8080. You will notice the following error

404 error slim framework

This is because the app doesn’t know how to handle Requests yet, to do that we have to use something called $app->get()

The function $app->get() takes in two parameters, the first one is a string or route, If you don’t understand routes, they’re just website URLs without the domain part (for eg. the Home Route would be /

And the second parameter is a Callback Function or a function that is Called Back whenever the user visits that particular URL or Route

Let’s start by adding a “Welcome Message” to the user, whenever he visits the Home of the API

To do that, we simply have to add the following code

$app->get("/", function($req, $resp)  {

   $resp->getBody()->write("Welcome to the API");
   return $resp;
});

As you might notice, the CallBack Function also takes in two parameters, $req, and $resp. Both of them are just what their name sounds – Request and Response objects.

  • The Request object contains data for the Request which user has made
  • The Response object provides us with helper functions that help us to send the Response back to the user

In the code above, what we are doing is, using the write function that the response object provides, and we simply write the string “Welcome to the API” in the response

Now if you visit localhost:8080, you should see your Welcome Message

slim framework api welcome message

Part 4: Creating API using Slim Framework

As we discussed earlier, we’ll be creating 4 functions for the API

  • Getting the List of Vaccinated People
  • Getting the List of Un – Vaccinated People
  • Getting The Percentage of Vaccinated People
  • Checking the vaccination status of a person

Let’s start by tackling each of them one by one,

Creating the “Data” for the API

To serve the above queries, we would need the Data of the Users, since covering Databases is outside the scope of this article, we’ll try to simulate a database by storing our data in a variable as follows

$people = array(
  array("name" => "Derek", "vaccinated" => "yes"),
  array("name" => "Emma", "vaccinated" => "no"),
  array("name" => "John", "vaccinated" => "yes"),
  array("name" => "Noah", "vaccinated" => "no"),
  array("name" => "Claire", "vaccinated" => "no"),
  array("name" => "Sofia", "vaccinated" => "no")
);

List of Vaccinated & Unvaccinated People

To Get the List of Vaccinated People, We will create a route called /getVaccinatedList by adding the following code

$app->get("/getVaccinatedList", function($req, $resp) use($people) {
$vaccinated = array_filter($people, function($person) {
return $person["vaccinated"] == "yes";
});
$resp->getBody()->write(json_encode($vaccinated));
return $resp;
});

If you don’t know about the $app->get() function, recall that it has 2 parameters, the first one is the route name and the second one is the callback function which is executed as soon as the user visits the route 

Let’s now have a look at the code above,

  • In PHP to access variables outside a function (in our case we’re trying to access $people which is outside of the function) we have to bind it to the function, we can do that using the keyword use and adding the variable we need inside the function

This is related to something called closures in PHP, if you’re interested you can learn more about them here

  • Looking at the inside of the function, we’re using PHP’s built-in function called array_filter, which helps us filter out only the elements in $person that have their vaccination status set to yes
  • After filtering the array, the final array is stored inside the $vaccinated variable
  • Now if you directly pass the array to your write() function, it’ll give you an error because in response’s write function you can only pass Strings or Text Content.
  • To deal with that, we first have to convert the $vaccinated array to a String and that can be done using the json_encode() function which will convert the array into a string.
  • Then we can simply pass the String content to the write function

Similarly to handle the request to Get Un Vaccinated People, we create a route using the /getUnVaccinatedList which would have a very similar code as the previous route

$app->get("/getUnVaccinatedList", function($req, $resp, $arg) use($people) {
$unvaccinated = array_filter($people, function($person) {
return $person["vaccinated"] == "no";
});

$resp->getBody()->write(json_encode($unvaccinated));
return $resp;
});

If you notice, the only thing that has changed from the previous route is that instead of checking for vaccinated == “yes”, we are now looking for unvaccinated people, that is vaccinated == “no” 

Checking Vaccination Status

Before moving ahead I would like you to guess the route for this feature.

After thinking for a while you might have realized that it’s not possible to make this function without getting some additional information from the user, that information would be the name of the person whose vaccination status is required

Thankfully there is a way to pass such information using something called Query Parameters, They’re just a way of sending additional information to any URL or Website

Let’s have a look at how we’ll pass the information to the Vaccination status feature, we’ll do that by 

localhost:8080/check?name=Emma

If for any reason you need to pass even more information, you can do so by following the given pattern

https://<website-url>/featureName?dataPropertyName1=value&property2=value2….

Now let’s have a look at the code and how we’ll implement it

$app->get("/check", function($req, $resp) use($people) {
 $qp = $req->getQueryParams();
$personName = $qp["name"];
foreach($people as $person) {
if($person["name"] == $personName) {
$resp->getBody()->write("The vaccination status is : " . $person['vaccinated']);
return $resp;
}
}

$resp->getBody()->write("Not found");
return $resp;
});
  • Firstly we get access to Query Parameters by using the getQueryParams() method that the $req object provides us
  • Then from the $qp (query parameters), we get the $personName 
  • Then we loop through the $people array and check if any person has the name which we received in the Query Parameters
  • If not, we simply write Not Found Message in the response object
  • If we do find a match, we simply their vaccination status which is stored in $person[‘vaccinated’]

Getting Percentage Of Vaccinated People

After making the above routes, this one should be pretty easy for you to figure out.

I would highly recommend you give this a try on your own and before jumping to the solution make sure to read the Hint and give it another go!

Hint

Percentage Of Vaccinated People = 100 *  (No. of vaccinated)/(No. of Vaccinated + No. of Un Vaccinated)

Hopefully, you gave it an honest try before looking at the following solution

Solution

$app->get("/percentage", function($req, $resp) use($people) {
$vacc = 0;
$unvacc = 0;
foreach($people as $person) {
  if($person['vaccinated'] == 'yes') $vacc++;
  else $unvacc++;
}

$perc = ($vacc)/($vacc + $unvacc) * 100;

$resp->getBody()->write(json_encode($perc));
return $resp;
});

However, it’s fine if you weren’t able to solve it completely on your own. Let’s go through the solution now 

  • Firstly we create 2 variables $vacc and $unvacc which will store the count of the vaccinated and unvaccinated people 
  • Then we loop through the $people array and if we find a person who is vaccinated we update the $vacc variable and vice versa
  • After doing that, we apply a simple percentage formula (mentioned in the hint) and store the resultant percentage in a new variable called $perc 
  • Then we simply use the write function to write the perc variable to the response 

Part 5: Testing the Slim Framework API

More the code we write, there will be a chance of errors in it. And the last thing we want is to deliver a product that doesn’t work according to the user’s needs. Hence testing the API is an important step. As important as coding it in the first place

There are many tools to test an API, but we’ll be using the most easy-to-use and one of the most popular ones called POSTMAN

Installing POSTMAN

Do not worry as Installing postman is not a complicated process at all, it’s almost similar to how you would install any other normal application. To install POSTMAN: 

postman website
  • Under the Download, the desktop app section, select the appropriate OS and your download should begin
  • Follow the on-screen instructions and you should have POSTMAN installed on your computer!

Setting up POSTMAN

After opening POSTMAN you should see the following screen asking you to create an account 

postman create account page

For this tutorial we do not need to create an account, however, you might do so if you are interested in the benefits that a POSTMAN account provides

On the Home Screen, you’ll see an option to Create a New Request, That is what we are interested in so click on that and you should see the following  

postman api page

To check whether the API is up and running, simply type localhost:8080 or whatever URL you chose while creating your PHP server

If everything goes correctly you should see the Welcome Message popup on your screen

postman api response

Testing /getVaccinatedList and /getUnVaccinatedList

Let’s now begin the testing by checking how these two functions work together, and to do that simply type the appropriate URL and click on the Get button

If your API is working properly and the tests succeed you should get the following output 

/getVaccinatedList

postman api response

/getUnvaccinatedList

postman api response

Testing /check

This part is where you realize the power of POSTMAN, you might have noticed a separate table called Query Params 

postman add header section

This is where you’ll put your Query Params (name in our case). Instead of typing the ?key1=value1 syntax this is a much faster and more efficient way to test the API

Simply edit the URL and add the name key, you should then get the appropriate result if everything was ok

postman api response
postman api response

Testing /percentage

This part would be easiest of all as you simply have to replace the URL with localhost:8080/percentage and if the query was successful you should get the following output 

postman api response

The output we got is the correct answer which is 33.33% percent of people are vaccinated in the region

Conclusion

Congrats on coming this far and completing the tutorial on Slim Framework. A good Next Step would be to learn about MySQL Database or any other Database of your choice and rebuild the same API. But instead of storing the data in a variable try to access it by storing it in your database. Doing this project would surely increase your comfort and confidence in working with the Slim framework and PHP. If you had fun building this project and learned something new today, do share it with your friends!