Php

How to Create a Simple REST API With Slim Framework

This tutorial will show you how to create a REST API using Restful API Framework SLIM for any web or mobile application. These REST Endpoints can be used in any Android, IOS, Angularjs, or other application.

The Rest API facilitates communication between the client and server applications. MySQL is my database, and PHP is used to retrieve records from it.

I’ll build a REST API to handle HTTP GET, POST, PUT, and DELETE requests. I’ll use a GET request to fetch records, a POST request to add new records, a PUT request to update a record in the database, and a Delete request to delete a record from the database.

PHP Restful API Framework SLIM

Slim is a PHP microframework that allows you to create simple and powerful web applications and APIs quickly. The SLIM framework is simple to use and lightweight, and it supports a wide range of requests. I’m assuming you’re familiar with basic PHP, MySQL, and the rest service.

Read: Different type of web services.

How to configure Slim framework on XAMPP/WAMP

You must first download the Slim framework from Slim framework as well as unzip it Now, rename the Slim-Skeleton-master folder dummy and copy it to the XAMPP/htdocs/ or wamp/www/ folder.

The project folder structure will now look like this:

XAMPP/htdocs/dummy

I’m assuming you have composer installed; if not, please install composer. Please open the XAMPP/htdocs/dummy/ folder in the cmd line and run the command below.

composer update

Create Virtual Host into XAMPP

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

<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 add the below codes to the end of the file.

127.0.0.1      dummy

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

How to connect MySQL with Slim

For these slim tutorials, I’m using an MYSQL database. I’ll make a dummy db in MySQL using the phpMyAdmin UI or the MySQL server. We will execute the SQL query below in the code>dummy db database.

--
-- 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 a DB connection method in the code>index.php/code> file. You can create a separate DB connection file and include it in the index.php as well, but I will not create complexity in this slim tutorial code because I am creating simple laymen user slim tutorials.

Open the dummy/public/index.php file and paste the code below at the end.

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 from the MySQL connection information, the parameters are as follows:

Related Post

dbhost: If your slim framework application code and MySQL server are on the same machine, this will contain the database’s hostname, such as IP address or hostname. Localhost can be used as a hostname.

dbname: The database’s name You can replace it with the name of your database.
dbuser: dbuser is the MySQL database’s username.
dbpass: The database password for MySQL.

now navigate to http://dummy// If everything is in order, you will see the slim home page; otherwise, an error message will appear.

HTTP Rest Service

In this slim example tutorial, I will create the following rest of EndPoints. We will create GET, POST, PUT, and DELETE type requests.

#RouteMethodTypeFull routeDescription
1/employeeGETJSONhttp://yourhost/api/v1/employees/Get all employee data
2/employee/{id}GETJSONhttp://yourhost/api/v1/employee/1Get a single employee data
3/createPOSTJSONhttp://yourhost/api/v1/createCreate new record in database
4/update/{id}PUTJSONhttp://yourhost/api/v1/update/21Update an employee record
5/delete/{id}DELETEJSONhttp://yourhost/api/v1/update/2Delete an employee record

Create HTTP routes in Slim Framework

We intend to include the above-rest calls in this tutorial, so we will include the below-rest endpoints in the dummy/src/routes.php/ file.

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’ve created an API and a v1 group for the versioning process only, which will make it easier to navigate the rest endpoints. I use GET, POST, PUT, and DELETE requests and pass the rest URL as well as the controller method that will call the API request.

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

The HTTP method in the preceding Routes is POST, and the function 'addEmployee' will call on the '/create' rest end point.

Get all records from MySQL Database Using Slim Restful API Framework

We will add a new method getEmployes(), to the dummy/public/index.php file and return JSON results. This method will retrieve all employee information from the employee table.

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, try the following rest call: http://dummy/api/v1/employees/ It will display employee list JSON results data in the browser.

How to Fix cross-domain request in Slim

When we use a cross-domain rest call, the client will receive an error message on the console about a cross-domain request, blah blah…? With the corsslim plugin, We can easily fix that issue in the slim framework.

First, we’ll add "palanik/corsslim": "dev-slim3" to the composer file and then run the composer update command again.

We’ll add some CORS configuration code to the publicindex.php file.

$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 a new HTTP Post method addEmployee() into dummy/public/index.php file. This method will create a new record into the MySQL database. You need to send data into json format.

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, try the rest call http://dummy/api/v1/create/. Using any rest test client, such as postman, it will return the newly created employee JSON data as a result.

Update Employee Data Using MySQL and Slim Restful API Framework

We will add a new HTTP PUT method called updateEmployee() to the dummy/public/index.php/ file. This method will update an existing employee record in MySQL. You must send employee data in json format, including the employee’s ID.

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() .'}}';
    }
}

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 result.

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 the employee id as a parameter and delete records from the employee table.

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 tutorial covers the fundamentals of crud table operation. We learned how to use the rest web service to add new records and edit existing records in a MySQL database. We’ve also included a listing of employee table data with a delete record from the MySQL table. You can integrate these rest calls into any web application that communicates with a server via APIs. You can modify these Slim example tutorials to suit your needs and have fun :).

You can download source code from below link.

View Comments

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories