How to Create a Simple REST API With Slim Framework

This tutorial help to create REST API using Restful API Framework SLIM for any web application or mobile application.You can use these REST End points to any android, IOS, Angularjs etc application.Rest API help to communication between the client app and the server application.I am using MySQL for database and fetch records from mysql using php.

I will create REST API that can be HTTP GET, POST, PUT and DELETE type request.I will use GET request for fetch records, POST for add new records,PUT for update record into database,Delete for delete record from database.

PHP Restful API Framework SLIM

Slim is a PHP micro framework that helps you quickly write simple and powerful web applications and APIs.SLIM framework is easy to use and very light weight with supports all kind of requests.I assuming you have knowledge of basic PHP, mysql and rest service.

Read: Different type of web services.

How to configure Slim framework on XAMPP/WAMP

You need to download Slim framework and unzip this,Now we will rename Slim-Skeleton-master folder to dummy and paste into XAMPP/htdocs or wamp/www folder.

Now project folder structure will look like below,

XAMPP/htdocs/dummy

I am assuming you have composer install, if not please install composer on your system.Please open XAMPP/htdocs/dummy folder into cmd line and run below command,

composer update

Create Virtual Host into XAMPP

Step 1: Open D:\XAMPP\apache\conf\extra\httpd-vhosts.conf file and added below codes into end of file.

Select Code
1
2
3
4
5
6
7
8
<VirtualHost *:80>
    DocumentRoot "D:\XAMPP\htdocs\dummy\public"
    ServerName dummy
  <Directory "D:\XAMPP\htdocs\dummy\public">
    Order allow,deny
    Allow from all
  </Directory>
</VirtualHost>

Please uncomment NameVirtualHost *:80 line from httpd-vhosts.conf file.

Note: Please Change ‘D:’ drive as per your install XAMPP drive.

Step 2: Now open C:\Windows\System32\drivers\etc\hosts files and added below codes into end of file.

Select Code
1
127.0.0.1      dummy

Now open http://dummy on browser, that will redirect to slim home page which is index.php file into public folder.

How to connect MySQL with Lumen

I am using MYSQL database for this slim tutorials.I will create dummy_db in mysql using phpMyAdmin UI or MySQL server.We will run below SQL query into dummy_db database,

Select Code
1
2
3
4
5
6
7
8
9
10
--
-- Table structure for table `employee`
--

CREATE TABLE IF NOT EXISTS `employee` (
`id` int(11) NOT NULL COMMENT 'primary key',
  `employee_name` varchar(255) NOT NULL COMMENT 'employee name',
  `employee_salary` double NOT NULL COMMENT 'employee salary',
  `employee_age` int(11) NOT NULL COMMENT 'employee age'
) ENGINE=InnoDB AUTO_INCREMENT=58 DEFAULT CHARSET=latin1 COMMENT='datatable demo table';

We will create db connection method in index.php file,You can create separate db connection file and include into index.php as well, since i am creating simple laymen user slim tutorials so i will not create complexity in this slim tutorial code.

Open dummy/public/index.php file and added below code in the end of file.

Select Code
1
2
3
4
5
6
7
8
9
function getConnection() {
    $dbhost="127.0.0.1";
    $dbuser="root";
    $dbpass="";
    $dbname="dummy_db";
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}

As you can see MySQL connection information,The parameters are,

dbhost : This will contain hostname of database like, IP address or hostname, if your slim framework application code and mysql server on same machine You can define localhost as a hostname.
dbname : The name of database.You can replace as per your db name.
dbuser : The username of mysql database.
dbpass : The password of mysql database.

now open http://dummy/ URL on browser, if everything fine you will see slim home page otherwise error will show,

HTTP Rest Service

I will create following rest end points in this slim example tutorials,We will create GET,POST,PUT and DELETE type request.

#RouteMethodTypeFull routeDescription
1/employeeGETJSON http://yourhost/api/v1/employees/Get all employee data
2/employee/{id}GETJSON http://yourhost/api/v1/employee/1Get a single employee data
3/createPOSTJSON http://yourhost/api/v1/createCreate new record in database
4/update/{id}PUTJSON http://yourhost/api/v1/update/21Update an employee record
5/delete/{id}DELETEJSON http://yourhost/api/v1/update/2Delete an employee record

Create HTTP routes in Slim Framework

We are planning create above rest call into this tutorial so we will add below rest end points into dummy/src/routes.php file,

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
// Routes

// API group
$app->group('/api', function () use ($app) {
    // Version group
    $app->group('/v1', function () use ($app) {
        $app->get('/employees', 'getEmployes');
        $app->get('/employee/{id}', 'getEmployee');
        $app->post('/create', 'addEmployee');
        $app->put('/update/{id}', 'updateEmployee');
        $app->delete('/delete/{id}', 'deleteEmployee');
    });
});

I have created api and v1 group for versioning process only, that will help to navigate rest end point easily.I use GET, POST, PUT and DELETE type request and pass rest url and controller method which will call on API request.

ex: $app->post('/create', 'addEmployee');

in above Routes the HTTP method is POST type and 'addEmployee' is function that will call on '/create' rest end point.

Get all records from Mysql Database Using Slim Restful API Framework

We will create new method getEmployes() into dummy/public/index.php file and return JSON results.This method will get all employee details from employee table.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
function getEmployes($response) {
    $sql = "select * FROM employee";
    try {
        $stmt = getConnection()->query($sql);
        $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        
        return json_encode($wines);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

now test rest call http://dummy/api/v1/employees using browser , it will show employee list json results data.

How to Fix cross-domain request in Slim

sometimes, we are using cross domain rest call , so client will get error on console about cross domain request blah blah..? We can fix that issue easily in slim framework by corsslim plugin.

First we will include "palanik/corsslim": "dev-slim3" into composer file and run again 'composer update' command.We will write some CORS configuration code code into public\index.php file.

Select Code
1
2
3
4
5
6
$corsOptions = array(
    "origin" => "*",
    "exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
    "allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS')
);
$cors = new \CorsSlim\CorsSlim($corsOptions);

Add New Employee Data Using MySQL and Slim Restful API Framework

We will create new HTTP Post method addEmployee() into dummy/public/index.php file. This methos will create new record into MySQL database.You need to send data into json format.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function addEmployee($request) {
    $emp = json_decode($request->getBody());
    
    $sql = "INSERT INTO employee (employee_name, employee_salary, employee_age) VALUES (:name, :salary, :age)";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("name", $emp->name);
        $stmt->bindParam("salary", $emp->salary);
        $stmt->bindParam("age", $emp->age);
        $stmt->execute();
        $emp->id = $db->lastInsertId();
        $db = null;
        echo json_encode($emp);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

now test rest call http://dummy/api/v1/create using any rest test client like postman etc , it will return created employee JSON data as a results.

Update Employee Data Using MySQL and Slim Restful API Framework

We will create new HTTP PUT method updateEmployee() into dummy/public/index.php file. This methos will update existing employee record into MySQL database.You need to send employee data with ID into json format.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function updateEmployee($request) {
    $emp = json_decode($request->getBody());
    $id = $request->getAttribute('id');
    $sql = "UPDATE employee SET employee_name=:name, employee_salary=:salary, employee_age=:age WHERE id=:id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("name", $emp->name);
        $stmt->bindParam("salary", $emp->salary);
        $stmt->bindParam("age", $emp->age);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
        echo json_encode($emp);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

now test rest call http://dummy/api/v1/update/1 using any rest test client like postman etc , it will return updated employee json data as a results.

Delete record from Mysql Table Using Slim REst Api Framework

We will create Delete type request and new method deleteEmployee() into dummy/public/index.php file.This method will take employee id as parameter and delete records from employee table.

Select Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function deleteEmployee($request) {
    $id = $request->getAttribute('id');
    $sql = "DELETE FROM employee WHERE id=:id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
        echo '{"error":{"text":"successfully! deleted Records"}}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
}

Conclusion

This Slim Api Framework tutorials has basic crud table operation.We have learn add new records and edit existing records into mysql database using rest webservice. We have also added listing of employee table data with delete record from mysql table.You can integrate these rest call to any web application which are communicating to server using APIs.You can extend this Slim example tutorials as per your need and enjoy :).

  • Kishor Kulkarni

    how to connect with sql server

    • i hvnt connected with sql server, i thng u need to set right database driver for sql server

  • Rama Astadipati

    Hi can you provide github link, i m not really understand bout this? thank you

    • Ok,i ll do that and update u