How to Create a REST API Using Slim Framework

REST APIs have redefined and standardized the process of Web app development. In almost all instances, REST APIs provide an efficient and very streamlined way of integrating services into a Web app.

It is no surprise that many popular Web-based services and apps have REST APIs that allow Web developers to integrate those services into their apps. For companies like YouTube, Facebook, and Twitter, REST and REST APIs are the most secure and streamlined manner of third-party content and service integration.

As a developer, you can provision REST APIs in many different ways. Among them, you could write custom code for the API or use a PHP micro framework, such as Slim, Lumen, Silex, or API-Platform.

There are, of course, other similar frameworks for other languages. For PHP, each of these four frameworks is well suited for REST API creation because of their unique mix of strengths. For instance, API-Platform uses Doctrine and Symfony core features for API creation.

If your Web app is built using a macro framework, such as Laravel, Symfony, or Yii2, you could take advantage of the native API building features. For instance, Laravel allows you to define API URLs in routes/api.php and then set up the URL responses accordingly.

In this article, you'll use the Slim framework for creating a REST API. You'll then use this API for performing CRUD operations on a user-defined table in a database. The complete code for the API is available in a GitHub repo.

Requirements

Before getting started, make sure that you have the following two pieces of software installed on your local machine:

  • XAMPP (available for Linux, OSX, or Windows) or WAMP (for Windows only)
  • Composer (dependency manager for PHP)

Start the process by creating a new folder called restapi in the htdocs folder in XAMPP or the www folder in WAMP. The next step is the installation of Slim framework into this folder.

Installing Slim Framework

Launch the terminal (from the command line in Windows or SSH terminal in Linux) and navigate to the restapi subdirectory. Run the following command to install the Slim framework:

$composer require "slim/slim:^3.0"
How to Create a REST API Using Slim Framework: Installing Slim Framework

Once the installation finishes, create a new file in the restapi subdirectory and name it index.php. Paste the following code into this file:

<?php
require 'vendor/autoload.php';

$app = new Slim\App();

In the above code, you first included the autoload file and then created an object for your Slim application.

Next, create a new .htaccess file in same directory. You'll use this file for a clean URL structure. Open the file and paste the following code into it:

RewriteEngine On
RewriteCond %{Request_Filename} !-F
RewriteCond %{Request_Filename} !-d
RewriteRule ^ index.php [QSA,L]

Once the .htaccess file has been added, the local URL for the API endpoint will look like this:

localhost/restapi/users

You'll now use this installation to create a REST API.

Creating a REST API With Slim

Now you'll first setup the database for demonstrating your REST API.

Open PHPMyADmin and create a new database with the name restapi.

How to Create a REST API Using Slim Framework: Creating a REST API With Slim

Then create a new table in this database using following table schema. Run the following command in SQL query box:

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
 `username` varchar(255) NOT NULL UNIQUE,
 `email` varchar(255) NOT NULL UNIQUE,
 `password` varchar(255) NOT NULL,
 `create_date` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
How to Create a REST API Using Slim Framework: Creating a REST API With Slim: New Table

Next, create a new file in the restapi subdirectory and name it config.php. In this file, you'll define the database credentials. Open the file and paste the following code into it:

<?php
$config = [
  'db' => [
     'servername' =>'localhost',
     'username' => 'YOUR_USER',
     'password' => 'YOUR_SECRET',
     'dbname' => 'restapi',
  ]
];

The database is now ready for use with the REST API.

Open the index.php file that you created earlier, and replace the existing code with the following:

<?php
require 'vendor/autoload.php';
include 'config.php';
$app = new Slim\App(["settings" => $config]);
//Handle Dependencies
$container = $app->getContainer();

$container['db'] = function ($c) {
   
   try{
       $db = $c['settings']['db'];
       $options  = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
       PDO::ATTR_DEFAULT_FETCH_MODE                      => PDO::FETCH_ASSOC,
       );
       $pdo = new PDO("mysql:host=" . $db['servername'] . ";dbname=" . $db['dbname'],
       $db['username'], $db['password'],$options);
       return $pdo;
   }
   catch(\Exception $ex){
       return $ex->getMessage();
   }
   
};

As shown in the previous code, you first included the config file and then passed it to Slim. Next, you called the the Slim container to handle dependencies. After that, you created a dependency for the database connection.

Ahmed Khan is the PHP Community Manager at Cloudways and writes about MySQL and PHP. An experienced professional in PHP related topics, Ahmed loves to spend his free time watching The Flash, Game of Thrones and reading DC Comics. Follow him on Twitter and Facebook to keep up with his work and insights on PHP hosting.
 

Comments

Comments(1)

KVN

Great tutorial, covered every bits and bobs without being to complicated. Cheers!