This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Creating a Simple REST API With Slim Framework

Updated on June 14, 2021

5 Min Read

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.

Related: Creating Twig Templates in Slim Microframework

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.

PHP Hosting: Best PHP 7 & PHP 5.6 Web Hosting

(Note: You may use promo code: PHP15 to get FREE Cloudways hosting credit of $15 on signup.)

php server cloudways

After creating the server  launch SSH terminal.

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

terminal command

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

composer require slim/slim"^3.0"

terminal installation

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.

First PHP Website Migration Is Free At Cloudways

Cloudways Engineers can migrate your website Flawlessly

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.

Access Detail

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

SQL Command

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.

You might also like: Using Eloquent ORM With Slim

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.

Get Call

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.

Add Records

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.

Add data

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

Run Call

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.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at [email protected]

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!