Creating a Simple REST API With Slim Framework

by Shahroze Nawaz  June 8, 2016

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.

rest api with slim framework

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.

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

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.

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

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:

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

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.

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:

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.

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.

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.

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.

Start Creating Web Apps on Managed Cloud Servers Now!

Easy Web App Deployment for Agencies, Developers and E-Commerce Industry

About Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at shahroze.nawaz@cloudways.com

Stay Connected:

You Might Also Like...

  • Ken

    You can checkout RedbeanPHP as a ORM companion to slim framework.

    I was able to build a RESTful API to integrate 2 major health care systems in just a few hours.

    • Shahroze Nawaz

      Great! Ken I have checked Redbean with Slim and find it simple with clean syntax.I would love to explore it more.

  • Sean Mumford

    $query = “UPDATE library SET book_name = ?, book_isbn = ?, book_category = ? WHERE book_id = $get_id”;

    This code is vulnerable to SQL injection. Why not use a parameter it the same way as your other database fields?

  • Matt

    $query = “DELETE from library WHERE book_id = $get_id”;

    Don’t write tutorials with code like that.

    • Shahroze Nawaz

      Thanks @maiorano84:disqus for your feedback as I have stated it’s a beginner’s tutorial. It’s nice to see you have pointed this out. I am working on it. Hopefully, it will be done soon.