Creating RESTful API Using Slim Micro-Framework 
Tags: slim, phpmicroframework, php, restapi
Published: 2017-03-23 11:51:51

---
title: Creating RESTful API Using Slim Micro-Framework 
published: true
description: This tutorial is an introduction to Slim and how you can use it to create a RESTful API.
cover_image: https://www.cloudways.com/blog/wp-content/uploads/rest-api-slim-framework.jpg
tags: slim, php micro framework, php, rest api
---

*This article was originally published at Cloudways: [Creating A Simple REST API With Slim Framework](https://www.cloudways.com/blog/simple-rest-api-with-slim-micro-framework/)*

The internet is chock full of third-party and custom APIs that offer a wide range of functionalities. PHP offers several frameworks for web app development rapidly. However, time is always the enemy of web developers and the app needs to be pushed at an impossible deadline. In such times, frameworks are the best option for rapid application development.

In this tutorial, I will introduce you to Slim framework for PHP. Slim is fast becoming the most-opted framework for API development and small web apps. Although you can create REST API in several other frameworks like CakePHP, Symfony Laravel, Codeigniter, they have a steep learning curve and are often too cumbersome to use in rapid development scenarios.

##Understanding Slim Framework

Slim is super lightweight framework, ideal for rapid web app development. One of the important usages is in REST API development. Slim supports all HTTP method (GET,POST,PUT,DELETE). Slim contains very handy URL structure with routers, middlewares, bodyparser along with page templates, flash messages, encrypted cookies and lots more.

At this point, it is important to understand the structure of the REST API.

##Understanding REST API

REST is the abbreviation of Representational State Transfer. This is a bridge or medium between data resource and application interface, whether it's on mobile devices or desktops. REST provides a block of HTTP methods which are used to alter the data. The following are common HTTP methods:

GET	is used for reading and retrieving data.
POST	is used for inserting data.
PUT	is used for updating data.
DELETE	is used for deleting data.

Basically, REST phenomena works on actions and resources. Whenever any action URL is invoked, it performs an individual method (or a set of methods) on that URL. I will further discuss this below with examples.

First we will need to install Slim framework for the REST API project.

I assume that you already have your [Cloudways server launched with PHPstack](https://platform.cloudways.com/signup) and if you didn't launch your server signup to get it.

![](http://www.cloudways.com/blog/wp-content/uploads/phpstactnew-resize.gif)

After creating the server  launch SSH terminal.

![](https://www.cloudways.com/blog/wp-content/uploads/launch-ssh-terminal-768x301.png)

##Step 1: Install Slim Framework From Composer

Open SSH terminal from the Cloudways panel and and sign in with your username and password. Now go to the folder where you want to install SLIM with cd command

![](https://www.cloudways.com/blog/wp-content/uploads/terminal-command-768x293.png)

Input the following command in the terminal to install Slim via composer.

```composer require slim/slim"^3.0"```

![](https://www.cloudways.com/blog/wp-content/uploads/terminal-installation.png)

After installing Slim, the following piece of code will require it in the index.php file to require autoload file and instantiate Slim.

```
<?php

require 'vendor/autoload.php';
$app = new Slim\App();
```

Composer comes pre-installed on Cloudways servers. If you are working on the localhost, you need to install it. If you haven't installed it yet, just go to the following link and follow the instructions.

##Step 2: Making a .htaccess File for Clean URL Structure

To make your life easier, you should create a .htaccess file that defines clean URL structure. At the root directory, make a .htaccess file and add the below code in it. This will provide a clean URL structure for the PHP file. (this just means that you don't want to include PHP filename in the URL calls).

```
RewriteEngine On

RewriteCond %{Request_Filename} !-F

RewriteCond %{Request_Filename} !-d

RewriteRule ^ index.php [QSA,L]
```

If your index file is located in different folder (for instance, the “public” folder),  then you can insert the full path of the index file in the last line:

```RewriteRule ^ public/index.php [QSA,L]```

##Step 3: Create a Database in MySQL

With each PHP Stack on Cloudways, you get an empty database.

![](https://www.cloudways.com/blog/wp-content/uploads/image01-25-768x265.png)

Click on Launch Database Manager. To create the requisite tables, run the following query in SQL Command box:

![](https://www.cloudways.com/blog/wp-content/uploads/image00-27-768x283.png)

```
CREATE TABLE IF NOT EXISTS `library` (

Â `book_id` int(11) NOT NULL,

Â `book_name` varchar(100) NOT NULL,

Â `book_isbn` varchar(100) NOT NULL,

Â `book_category` varchar(100) NOT NULL

) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;

INSERT INTO `library` (`book_id`, `book_name`, `book_isbn`, `book_category`) VALUES

(1, 'PHP', 'bk001', 'Server Side'),

(3, 'javascript', 'bk002', 'Client Side'),

(4, 'Python', 'bk003', 'Data Analysis');
```

Now it is time for the first API call. Let's make it systematically.

##Step 4: Retrieving All Books

Enter the following code in the index.php file to get all the books from the database. A GET call is used for retrieval.

```
$app->get('/books', function() {

Â require_once('db.php');

Â $query = "select * from library order by book_id";

Â $result = $connection->query($query);

Â // var_dump($result);

Â while ($row = $result->fetch_assoc()){

$data[] = $row;

Â }

Â echo json_encode($data);

});
```

To streamline working with the API calls, I recommend using [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) (available from the Chrome App Store). This plugin greatly helps in API management and usage.

In postman, make a GET call with API URL.

![](https://www.cloudways.com/blog/wp-content/uploads/image04-17-768x432.png)

##Step 5: Creating a Book's Record

Make a new API call in the index.php  through the following code:

```
$app->post('/books', function($request){

Â require_once('db.php');

Â $query = "INSERT INTO library (book_name,book_isbn,book_category) VALUES (?,?,?)";

Â $stmt = $connection->prepare($query);

Â $stmt->bind_param("sss",$book_name,$book_isbn,$book_category);

Â $book_name = $request->getParsedBody()['book_name'];

Â $book_isbn = $request->getParsedBody()['book_isbn'];

Â $book_category = $request->getParsedBody()['book_category'];

Â Â $stmt->execute();

});
```

Open Postman and click Body. Select x.www-form-urlencoded. Now add records to insert via POST call.

![](https://www.cloudways.com/blog/wp-content/uploads/image05-14-768x432.png)

##Step 6: Updating a Book's Record

Make a new API call like below to update a record in the database.

```
$app->put('/books/{book_id}', function($request){

Â require_once('db.php');

Â $get_id = $request->getAttribute('book_id');

Â $query = "UPDATE library SET book_name = ?, book_isbn = ?, book_category = ? WHERE book_id = $get_id";

Â $stmt = $connection->prepare($query);

Â $stmt->bind_param("sss",$book_name,$book_isbn,$book_category);

Â $book_name = $request->getParsedBody()['book_name'];

Â $book_isbn = $request->getParsedBody()['book_isbn'];

Â $book_category = $request->getParsedBody()['book_category'];

Â $stmt->execute();

});
```

In Postman, add data to update a specific book record.

![](https://www.cloudways.com/blog/wp-content/uploads/image03-20-768x432.png)

##Step 7: Deleting a Book's Record

To delete a record with a specific ID, a DELETE call is required.

```
$app->delete('/books/{book_id}', function($request){

Â require_once('db.php');

Â $get_id = $request->getAttribute('book_id');

Â $query = "DELETE from library WHERE book_id = $get_id";

Â $result = $connection->query($query);

});
```

On Postman, run the call like this

![](https://www.cloudways.com/blog/wp-content/uploads/image02-21.png)

This is all for the basic REST API in the Slim Framework. However, this API will not work until you add this command at the end of the code.

`$app->run();`

##Conclusion

Creating and using the REST API with Slim framework is very easy. The biggest advantage of the framework is its ease of use and lightweight. The icing on the cake is that it is very easy to learn and a good developer could pick up the framework in a matter of hour. To summarize, Slim receives HTTP requests, review them and invokes the appropriate callback routine for HTTP requests and return the appropriate response(s).

If you need clarification about this article or have any other query about the Slim Framework, do let me know through the comment section.