DEV Community

Cover image for Creating RESTful API Using Slim Micro-Framework
Cloudways
Cloudways

Posted on

Creating RESTful API Using Slim Micro-Framework

This article was originally published at Cloudways: Creating A Simple REST API With Slim 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 and if you didn't launch your server signup to get it.

After creating the server launch SSH terminal.

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

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


composer require slim/slim"^3.0"

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.

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

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 (available from the Chrome App Store). This plugin greatly helps in API management and usage.

In postman, make a GET call with API URL.

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.

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.

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

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.

Top comments (4)

Collapse
 
vikkio88 profile image
Vincenzo

this is great! Regarding to this I am working on a framework based on Slim and Eloquent, which would make everything even easier and less messy (sql in "controller" was a bit :o) slime

Collapse
 
_shahroznawaz profile image
Shahroz Nawaz

Eloquent is also <3

Collapse
 
midhilaj profile image
Midhilaj

Show me the code! Please?
require_once('db.php'); db.php file

Collapse
 
zichis profile image
Ezichi Ebere Ezichi

What about security?