Creating REST API using Slim Framework — Getting started with server-side scripting

Basu
5 min readJun 19, 2020

This is a part of the article:

Building an Android app — From scratch to pro!

REST determines how the API looks like. It stands for “Representational State Transfer”. It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL.

Each URL is called a request while the data sent back to you is called a response.

You might have seen some URL like xyz.com/login.php and some like abc.com/login. The first one is a login.php file while the second one is a function in a PHP file. There could be tens of function in a single PHP file. You don’t need several PHP files. You can have all the codes of each one of the files inside a function in a single Php file.

Framework for REST API:

Slim Framework: Slim is a PHP micro-framework that helps you quickly write simple yet powerful web applications and APIs. Example:

<?php
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, " . $name;
});
$app->run();
//Here $app->get('/hello/:name', function ($name)
hello is a function (similar to a web page) and name is variable or value we are passing and $name is the variable we are storing the value in.

You can learn more about Slim documentation here.

Now, if you have a Php editor open that else download an IDE. I’m using PhpStorm which you can get here, free for some time if you are a student :).

Open it, create a new project, name it and create the following file and folder structure. Remember, this is not necessary. You can create your own strategy to arrange file.

In the home folder of your project, create these folders and files. You need to download the ”Slim” folder which is the actual library and put it in your project.

Clone or download this library from Github. To clone the library, follow this step. Once cloned, open the main folder and copy the Slim folder into your project.

Before that, if you don’t know MySQL, here’s a good tutorial on Php MySql.

Now comes the actual coding of your server. Let’s create each file one by one:

Open Constants.php:

<?php
//Constants to connect with the database
define('DB_USERNAME', 'YOUR_DATABASE_USERNAME');
define('DB_PASSWORD', 'YOUR_DATABASE_PASSWORD');
define('DB_HOST', 'YOUR_DATABASE_URL');
define('DB_NAME', 'YOUR_DATABASE_NAME');
define('FIREBASE_API_KEY', 'ZHSA7dXXXXXXXXX_YOUR_API_KEY');//This is your Firebase key. This is your unique key and keep it secret shhh!Go to this page. Choose your project (if you don't have any project, create one).
You can find the API KEY in:
(gear-next-to-project-name) > Project Settings > Cloud Messaging
Server Key is the API key.

Open DbConnect.php:

<?php

//Class DbConnect
class DbConnect
{
//Variable to store database link
private $con;

//Class constructor
function __construct()
{

}

//This method will connect to the database
function connect()
{
//Including the constants.php file to get the database constants
include_once dirname(__FILE__) . '/Constants.php';

//connecting to mysql database
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

//Checking if any error occured while connecting
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

//finally returning the connection link
return $this->con;
}

}
//Here Connect() function opens up a connection with your MySql database. Here's a tutorial to setup Sql on your server. You can search your own server's documentation for setting it up.

Open DbOperations.php:

<?php

class DbOperation
{
//Database connection link
private $con;

//Class constructor
function __construct()
{
//Getting the DbConnect.php file
require_once dirname(__FILE__) . '/DbConnect.php';

//Creating a DbConnect object to connect to the database
$db = new DbConnect();

//Initializing our connection link of this class
//by calling the method connect of DbConnect class
$this->con = $db->connect();
}
public function getAllTokens(){
$stmt = $this->con->prepare("SELECT fcm_id FROM user");
$stmt->execute();
$result = $stmt->get_result();
$tokens = array();
while($token = $result->fetch_assoc()){
array_push($tokens, $token['fcm_id']);
}
return $tokens;

}
public function createUser($name, $email, $phone, $gender, $fcm_id, $device_id){
date_default_timezone_set("Asia/Kolkata");
$timestamp = date("d/m/Y-H:i:s");
$stmt = $this->con->prepare("INSERT INTO user (name, email, phone, gender, fcm_id, device, timestamp) values(?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $name, $email, $phone, $gender, $fcm_id, $device_id, $timestamp);
$result = $stmt->execute();
$stmt->close();
if ($result) {
return 0;
} else {
return 1;
}
}
//This method will generate a unique api key
private function generateApiKey(){
return md5(uniqid(rand(), true));
}
}
This is our main operation functions. These functions interact with out database. The createUser() function insert a user's data in our server and the $fcm_id is the Firebase ID of the user. And, the getAllTokens() function is used to retrive the Firebase token/ ID of the users.

The Firebase.php and Push.php are used for sending a notification to a mobile device. You can follow this tutorial to set up Firebase Cloud Messaging to send a notification.

Now open your v1 or v2 folder. I hope you have already downloaded the Slim folder and copied it here.

Open .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]

Open index.php:

<?php
require 'Slim/Slim.php';
require_once '../include/DbOperation.php';
require_once '../include/Push.php';
require_once '../include/Firebase.php';
\Slim\Slim::registerAutoloader();$app = new \Slim\Slim();//Start of your functions$app->get('/getalltoken', function () { $db = new DbOperation();
$list = $db->getAllTokens();
echoResponse(201, $list);
});$app->post('/login/:name/:email/:phone/:gender/:fcm_id/:device', function ($name, $email, $phone, $gender, $fcm_id, $device_id) {
$db = new DbOperation();
$res = $db->createUser($name, $email, $phone, $gender, $fcm_id, $device_id);
if($res == 1){
$response["error"] = true;
$response["message"] = "Our server is facing some issue right now.. Please try again later.";
echoResponse(200, $response);
} else {
$response["error"] = false;
$response["message"] = "Registration Successful!";
echoResponse(201, $response);
}
});//End of your functionsfunction echoResponse($status_code, $response)
{
//Getting app instance
$app = \Slim\Slim::getInstance();

//Setting Http response code
$app->status($status_code);

//setting response content type to json
$app->contentType('application/json');

//displaying the response in json format
echo json_encode($response);
}$app->run();//The lines before "start of your function" is necessary. It loads Slim and other files. echoResponse() is used to send response back to the device. Here, $app->get('/getalltoken', function () is a function just like xyz.com/getalltoken. This function:
$app->post('/login/:name/:email/:phone/:gender/:fcm_id/:device', function ($name, $email, $phone, $gender, $fcm_id, $device_id)
is our login function. It takes our user's detail and store it in a variable for each data and then do the neccessary task.

This is it. Based on this pattern, you can start writing functions and add REST API functionality to your server (can be used by both app and website). You can also use multiple features to secure your server, like adding an API key and other things.

Thank you!

Suggested reading:

  1. https://www.cloudways.com/blog/simple-rest-api-with-slim-micro-framework/
  2. https://www.simplifiedcoding.net/php-restful-api-framework-slim-tutorial-1/

--

--