How to create RESTful API / Web Service with Slim, PHP & MySQL

How to create RESTful API / Web Service with Slim, PHP & MySQL

For this article we will be using the slim PHP micro framework to implement the RESTful API. Slim was chosen because it is very light weight, clean, supports all the HTTP methods, and also provides support for middleware layers. Along with slim you will need a web server (apache or nginx), PHP, and MySQL installed before proceeding. Once you’ve gotten all the necessary files you can begin.

This tutorial gives you complete examples of creating full Restful API using multiple HTTP methods like GET,POSTPUT and DELETE. You would get the output in JSON and create a user data for all options, download code available.

HTTP methods:

GET: Used to retrieve and search data.

POST: Used to insert data.

PUT: Used to update data.

DELETE: Used to delete data.

Add below .htaccess file in your api folder http://localhost/api

RewriteEngine On
 
RewriteBase /api # if hosting api files on root use only /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

Database design and table:
database name => rest
table name => restAPI
column names => id, name, email, ip, date
db.sql
Database file run in your MySQL to create database and add data in table.

CREATE TABLE `rest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(240) NOT NULL,
  `email` varchar(240) NOT NULL,
  `password` varchar(240) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

Database configuration

Edit database name, user and password as per your configuration

function getConnection() {
    try {
        $db_username = "DATABASE_NAME";
        $db_password = "********";
        $conn = new PDO('mysql:host=localhost;dbname=root', $db_username, $db_password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 
    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    return $conn;
}

Used PDO connection you can use as per your ease and I have added this function in same methods file you can also manage them as per your projects.

Implement API

We have created 6 API methods

  1. getUsers
  2. getUser
  3. findByName
  4. addUser
  5. updateUser
  6. deleteUser

Define HTTP routes:

$app->get('/users', 'getUsers'); // Using Get HTTP Method and process getUsers function
$app->get('/users/:id',    'getUser'); // Using Get HTTP Method and process getUser function
$app->get('/users/search/:query', 'findByName'); // Using Get HTTP Method and process findByName function
$app->post('/users', 'addUser'); // Using Post HTTP Method and process addUser function
$app->put('/users/:id', 'updateUser'); // Using Put HTTP Method and process updateUser function
$app->delete('/users/:id',    'deleteUser'); // Using Delete HTTP Method and process deleteUser function
$app->run();

These all routes call individual function as defined above and in the last $app->run(); used to run Slim application.

let’s see functions:

1. getUsers: $app->get(‘/users’, ‘getUsers’);

function getUsers() {
    $sql_query = "select `name`,`email`,`date`,`ip` FROM restAPI ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt   = $dbCon->query($sql_query);
        $users  = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"users": ' . json_encode($users) . '}';
    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }    
}

This function simply return all users information as you can see in this query, to call this API use this URL http://localhost/api/users this is it for your first API using get route.

2. getUser: $app->get(‘/users/:id’,    ‘getUser’); In this route we are sending id.

function getUser($id) {
    $sql = "SELECT `name`,`email`,`date`,`ip` FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $user = $stmt->fetchObject();  
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function check record of given id and return if found any thing,  to call this API use this URL http://localhost/api/users/1.

3. findByName: $app->get(‘/users/search/:query’, ‘findByName’); Route is used to search record with extra parameter and a search query with simple get method.

function findByName($query) {
    $sql = "SELECT * FROM restAPI WHERE UPPER(name) LIKE :query ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);
        $query = "%".$query."%";
        $stmt->bindParam("query", $query);
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"user": ' . json_encode($users) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function search in database for your given query, to call this API use this URL http://localhost/api/users/search/f.

4. addUser: $app->post(‘/users’, ‘addUser’); API used to add new record and accept post.

function addUser() {
    global $app;
    $req = $app->request(); // Getting parameter with names
    $paramName = $req->params('name'); // Getting parameter with names
    $paramEmail = $req->params('email'); // Getting parameter with names
 
    $sql = "INSERT INTO restAPI (`name`,`email`,`ip`) VALUES (:name, :email, :ip)";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("ip", $_SERVER['REMOTE_ADDR']);
        $stmt->execute();
        $user->id = $dbCon->lastInsertId();
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API accept post request and insert submitted data in your database as we received parameters in starting of that function. To call this API I have used cURL, you can use jQuery or any other technique.

<?php
if($_POST){
    echo post_to_url("http://localhost/users", $_POST);
} else{
 ?>
ADD RECORD.
<form action="" method="post">
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="POST" />
<input type="submit" value="A D D" />
</form>
<?php 
}
?>

This form will be submitted to your action file and there is a curl and that curl will post data as I have used a hidden input of _METHOD with POST value this is because some times your cURL don’t Post data to API (faced this so used this for post as well) and Slim give us this functionality to method override and as our modern browsers do not have native support to PUT and delete so we have to use method overriding like below.

<input type="hidden" name="_METHOD" value="POST" /> <!-- POST data -->
<input type="hidden" name="_METHOD" value="PUT" /> <!-- PUT data -->
<input type="hidden" name="_METHOD" value="DELETE" /> <!-- DELETE data -->

cURL function to post data:

function post_curl($_url, $_data) {
   $mfields = '';
   foreach($_data as $key => $val) { 
      $mfields .= $key . '=' . $val . '&'; 
   }
   rtrim($mfields, '&');
   $pst = curl_init();
 
   curl_setopt($pst, CURLOPT_URL, $_url);
   curl_setopt($pst, CURLOPT_POST, count($_data));
   curl_setopt($pst, CURLOPT_POSTFIELDS, $mfields);
   curl_setopt($pst, CURLOPT_RETURNTRANSFER, 1);
 
   $res = curl_exec($pst);
 
   curl_close($pst);
   return $res;
}

5. updateUser: $app->put(‘/users/:id’, ‘updateUser’); This route accept put HTTP method.

function updateUser($id) {
    global $app;
    $req = $app->request();
    $paramName = $req->params('name');
    $paramEmail = $req->params('email');
 
    $sql = "UPDATE restAPI SET name=:name, email=:email WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("id", $id);
        $status->status = $stmt->execute();
 
        $dbCon = null;
        echo json_encode($status); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function update your data by id, to call this API we need to again use cURL and HTML form.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST); // add id after last slash which you want to edit.
} else{
UPDATE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to update" /><br>
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="PUT" />
<input type="submit" value="U P D A T E" />
</form>
<?php 
}
?>

6. deleteUser: $app->delete(‘/users/:id’,    ‘deleteUser’); Route used to delete specific ID.

function deleteUser($id) {
    $sql = "DELETE FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $status->status = $stmt->execute();
        $dbCon = null;
        echo json_encode($status);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function accept HTTP delete request and to send HTTP delete method we have to used method overriding using our hidden field named _METHOD and value will be DELETE form and cURL code given below.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST);
} else{
 ?>
DELETE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to delete" /><br>
<input type="hidden" name="_METHOD" value="DELETE" />
<input type="submit" value="D E L E T E" />
</form>
 <?php 
}
?>

That’s all for our one of the biggest tutorial for RESTful API, I hope you like this tutorial and please don’t forget to give us your feedback and any issue you have faced in this tutorial please do comment we try our level best to solve your problems.

Author Surjit Sidhu

Surjit SidhuSurjit is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling.