How to create the REST API with Slim framework
Home » BLOG » Web development » How to create the REST API with Slim framework

How to create the REST API with Slim framework

category:  Web development

What is API?

API, you may hear about it often nowadays. API stands for an application programming interface. It lets your product or service communicate with other platforms. For example, you have your own custom application or custom website and you want to exchange your data with the Facebook app or mobile application or other applications, you can create your own API and allow those platforms to access your data that you want them to access.

For the business standpoint, API can open up new opportunities for new business partnerships with related service providers such as Travel business, Spa, Tour, Hotel and restaurant.

APIs can categorize in three basic types. They are the private API, public API, and partner API. In short, the private API is used as the internal API in the company. Mostly it is used for the development purpose for developers. The public API, it is published outside the company such as the tour packages information. The partner API, it is used by the specific parties who make an agreement with. For example, you agree to sell Thailand package tours with a spacial price for the Europe tour company. So you can provide this special API for this Europe tour company only.

As I am a web developer, I mostly work with Web APIs or often called RESTful (representational state transfer). In this post, I gonna share how to create the REST API with the fast and lightweight framework called Slim. The framework based on PHP and you can add the UnitTest(using PHPUnit) to work with the API as well. I am not gonna talk about the UnitTest in this post. I will focus on creating an API in the Slim framework only.

What do you need before continuing

  • Web server – I use WampServer. But you can use any web server you like. So we can run PHP on the webserver.
  • Text Editor tool – I use VScode which is already integrated with the bash terminal. You can use any text editor tool and terminal you like.
  • Composer – I use the compose to install the slim. It is the same concept as nodejs and npm.
  • The web server with URL rewriting
  • PHP 5.5 or newer
  • Rest API testing – I use Restlet Client – REST API Testing Chrome extension. You can use any tools you like.

Here are the sections that I am gonna show you today.

  • Install Slim framework
  • Setup the files structure to work with Slim (this is my preference. You can set up any files structure you like)
  • Create the database and create one customer’s table
  • Create the database connection with PDO object
  • Create GET/POST/PUT/DELETE request for the customer APIs

Install Slim Framework

  • At the webroot which is www folder in Wamp server, I create the new folder called “slimapi“. So the path looks like www\slimapi
  • Open the VScode(text editor tool) and open the slimapi folder
  • Open the bash terminal(you can use your preferred terminal) and run the composer command. The Slim installation document is here.
composer require slim/slim "^3.12"
  • After the composer installs successfully. You will see a similar message below in the terminal.
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 6 installs, 0 updates, 0 removals
  - Installing psr/container (1.0.0): Loading from cache
  - Installing container-interop/container-interop (1.2.0): Loading from cache
  - Installing nikic/fast-route (v1.3.0): Loading from cache
  - Installing psr/http-message (1.0.1): Loading from cache
  - Installing pimple/pimple (v3.2.3): Loading from cache
  - Installing slim/slim (3.12.1): Loading from cache
Writing lock file
Generating autoload files
  • Now under the slimapi folder, you will see the new vendor folder, composer.json, and composer.lock. Those folders and files are installed by the composer.

Setup the files structure to work with Slim

  • Next, I create the two new folders which are public and src. This is my preferred structure. You can create your own structure as you like.
  • Under the public folder, I create a new index.php which is our entry file in Slim.

# Your first GET request

After installing the Slim, we want to test that Slim is working on our web server or not. To do that, in the index.php, add the code below.
The code can be found at the Slim home page.
Notice that, I add “../” in front of the vendor path because my files structure sets this way.

<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

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

$app = new \Slim\App;
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");

    return $response;
});
$app->run();

For a short explanation, we add two namespaces which are Request and Response. Both will help to manage the HTTP request and response for us. Then we include the autoload.php which is created by the composer. So we can refer to the Slim and other related dependencies from Slim. Next, we create a new Slim instance. After that, the $app->get() is called for making the route for us. The route is a GET request. The ‘/hello/{name}’ is our route and the callback function is the response. In the code above, we will write “Hello” text with the name that you set as the name variable on the browser. Finally, we run $app->run() command to let the slim starts to work.

# The first route is created and ready to run

Now you can run the API Url below on your browser. Let’s run it.

http://localhost/slimapi/public/index.php/hello/AppleRinquest

You should see “Hello, AppleRinquest” as the result on the browser. Congrats!

# Get rid of the index.php

It seems the URL is long. I gonna get rid of the index.php. To do that, you just create a .htaccess file under the public folder and add the rule below into the file. If you don’t want to do as I do, it is fine. A useful link can be found here.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

After setup the .htaccess file, I can use this API Url without index.php as shown here.

http://localhost/slimapi/public/hello/AppleRinquest

# Setup the virtual host

Also, you can set the virtual host for the slimapi folder. To do that, for the Wamp server, you just visit http://locahost and click on “Add a Virtual Host” then add the slimapi path and it is done.

Note that, if you use the anti-virus application that set the blocking the system file written by other program option, you must disable this option before adding a new virtual host with Wamp server. Otherwise, you have to set the host file manually. Finally, restart the webserver. I am not set the virtual host in this tutorial.

Create the database and create one customer’s table

  • At the PHPMyAdmin, create the new database called “slimapi
  • Create a new table called “customers” with 3 fields (id, name, and address). The ID will set as INT(11), primary key and Auto Increment. Name and address are set as Varchar(150).
  • Add some data for testing. I add two records to the customer’s table. You can add any data you want so we can test in our API.
  • Back to our slimapi folder, in the src folder, I create a new config folder and add a new db.php file in there.
  • In the db.php file, I add the code below. Don’t forget to change the database config to meet your database.
<?php
/**
 * Connect MySQL with PDO class
 */
class db {
  
  private $dbhost = 'localhost';
  private $dbuser = 'root';
  private $dbpass = '';
  private $dbname = 'slimapi';

  public function connect() {

    // https://www.php.net/manual/en/pdo.connections.php
    $prepare_conn_str = "mysql:host=$this->dbhost;dbname=$this->dbname";
    $dbConn = new PDO( $prepare_conn_str, $this->dbuser, $this->dbpass );

    // https://www.php.net/manual/en/pdo.setattribute.php
    $dbConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    // return the database connection back
    return $dbConn;
  }
}
  • Then in the index.php under the public folder, I include the db.php after the autoload.php like so.
<?php
// # use Namespaces for HTTP request
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

// # include the Slim framework
require '../vendor/autoload.php';

// # include DB connection file
require '../src/config/db.php';

// # create new Slim instance
$app = new \Slim\App;

// create GET HTTP request
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");

    // send the response back from the request
    return $response;
});


// # let Slim starts to run
// without run(), the api routes won't work
$app->run();

Then test the db.php by calling this API Url on the browser.

http://localhost/slimapi/public/hello/AppleRinquest

You should see “Hello, AppleRinquest” message on your browser. That means no error from the db.php.

Create GET request for all customers data

  • Under the src folder, I create new routes folder and under routes folder, I create customers.php
  • In the customers.php, I add the code below.
<?php
// use Namespaces for HTTP request
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

// create new Slim instance
$app = new \Slim\App;

// create GET HTTP request
$app->get('/api/customers', function( Request $request, Response $response){
  echo 'Sawandee my customers';
});
  • Back in the index.php under the public folder, I include the customers.php before $app->run().
<?php
// # use Namespaces for HTTP request
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

// # include the Slim framework
require '../vendor/autoload.php';

// # include DB connection file
require '../src/config/db.php';

// # create new Slim instance
$app = new \Slim\App;

// create GET HTTP request
$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");

    // send the response back from the request
    return $response;
});


// # include Customers route
require '../src/routes/customers.php';


// # let Slim starts to run
// without run(), the api routes won't work
$app->run();

Now, you can call this API Url on the browser for testing the route.

http://localhost/slimapi/public/api/customers

You should see “Sawandee my customers” message on the browser.

  • Since we already created the database connection and customer table. We will replace the getBody()->write() to the query instead. To do that, you will add the query to the customers.php.
<?php
// use Namespaces for HTTP request
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

// create new Slim instance
$app = new \Slim\App;

// create GET HTTP request
$app->get('/api/customers', function( Request $request, Response $response){
  // echo 'Sawandee my customers';

  $sql = "SELECT * FROM customers";

  try {
    // Get DB Object
    $db = new db();

    // connect to DB
    $db = $db->connect();

    // query
    $stmt = $db->query( $sql );
    $customers = $stmt->fetchAll( PDO::FETCH_OBJ );
    $db = null; // clear db object

    // print out the result as json format
    echo json_encode( $customers );    

    
  } catch( PDOException $e ) {

    // show error message as Json format
    echo '{"error": {"msg": ' . $e->getMessage() . '}';
  }

});

Let test it on the browser using this API Url.

http://localhost/slimapi/public/api/customers

You should see your customer data as json format like [{“id”:”1″,”name”:”John Doe”,”address”:”Las Vegas, USA”},{“id”:”2″,”name”:”Sandy Wong”,”address”:”HongKong”}]

Using REST API Testing Chrome extension

  • Before I forget, we should test our APIs in REST API Testing Chrome extension(you can use PostMan if you like). Go to the Chrome browser and install the extension.
  • Open the extension and choose the GET method and paste this link(http://localhost/slimapi/public/api/customers) and then click on the Send button.
  • At the response section, you should see 200 OK which means success and at the body section, you should see the customer data as JSON format.

At this point, we can get all customers’ data with /api/cusotmers route. Next, we want to get a single customer data only.

Create GET request for a single customer data with parameter

  • At the customers.php, add this code after the last line.
/**
 * Get Single Customer
 */
// create GET HTTP request
$app->get('/api/customer/{id}', function( Request $request, Response $response){
  $id = $request->getAttribute('id');

  $sql = "SELECT * FROM customers WHERE id = $id";

  try {
    // Get DB Object
    $db = new db();

    // connect to DB
    $db = $db->connect();

    // query
    $stmt = $db->query( $sql );
    $customer = $stmt->fetchAll( PDO::FETCH_OBJ );
    $db = null; // clear db object

    // print out the result as json format
    echo json_encode( $customer );    

    
  } catch( PDOException $e ) {

    // show error message as Json format
    echo '{"error": {"msg": ' . $e->getMessage() . '}';
  }

});

Then you can test this API Url on the REST API Testing extension. Remember, this is a GET request. So at the extension, you must choose the GET method.

http://localhost/slimapi/public/api/customer/1

You should see the customer data of id#1 in the body section.

Create POST request for adding new customer data

  • Normally, when the users add the new data, they will add via an adding form. Then the form is submitted, the form action will redirect to API.
  • To create the POST request for adding new customer data, you will add the code below at the last line in the customers.php.
/**
 * Add new customer data
 */
// create POST HTTP request
$app->post('/api/customer/add', function( Request $request, Response $response){

  // get the parameter from the form submit
  $name = $request->getParam('name');
  $address = $request->getParam('address');
  

  $sql = "INSERT INTO customers (name,address) VALUES(:name,:address)";

  try {
    // Get DB Object
    $db = new db();

    // connect to DB
    $db = $db->connect();

    // https://www.php.net/manual/en/pdo.prepare.php
    $stmt = $db->prepare( $sql );

    // bind each paramenter
    // https://www.php.net/manual/en/pdostatement.bindparam.php
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':address', $address);

    // execute sql
    $stmt->execute();
    
    // return the message as json format
    echo '{"notice" : {"msg" : "New Customer Added.."}';

  } catch( PDOException $e ) {

    // return error message as Json format
    echo '{"error": {"msg": ' . $e->getMessage() . '}';
  }

});

To test it, at the REST API Testing extension, changes the GET method to the POST method. Then paste this API Url and then add the query parameter as the screenshot below. Finally, hits the Send button.

http://localhost/slimapi/public/api/customer/add

If it is successfully, at the Response section, you will see the {“notice” : {“msg” : “New Customer Added..”} at the BODY part.

To verify, the new customer data is added, at the extension, simply changes the method to GET and paste this API Url. Then hits the Send button. You should see the new customer data you just added.

http://localhost/slimapi/public/api/customers

Create PUT request for updating a single customer data

  • Finally, we will update the customer data for the specific id.
  • At the customers.php, add the code below at the last line.
/**
 * Update a Single Customer data
 */
// create PUT HTTP request
$app->put('/api/customer/update/{id}', function( Request $request, Response $response){
  // get attribute from URL
  $id = $request->getAttribute('id');
  
  // get the parameter from the form submit
  $name = $request->getParam('name');
  $address = $request->getParam('address');
  

  $sql = "UPDATE customers SET 
          name = :name,
          address = :address 
          WHERE id = $id";

  try {
    // Get DB Object
    $db = new db();

    // connect to DB
    $db = $db->connect();

    // https://www.php.net/manual/en/pdo.prepare.php
    $stmt = $db->prepare( $sql );

    // bind each paramenter
    // https://www.php.net/manual/en/pdostatement.bindparam.php
    $stmt->bindParam(':name', $name);
    $stmt->bindParam(':address', $address);

    // execute sql
    $stmt->execute();
    
    // return the message as json format
    echo '{"notice" : {"msg" : "New Customer Updated.."}';

  } catch( PDOException $e ) {

    // return error message as Json format
    echo '{"error": {"msg": ' . $e->getMessage() . '}';
  }

});

At the REST API Testing extension, change the method to PUT and paste the API Url below.

http://localhost/slimapi/public/api/customer/update/1

Add the new query parameter for name and address. Make sure the header content type is application/JSON. Then hits the Send button. You should see the {“notice” : {“msg” : “New Customer Updated..”}.

Check the updated data by changing the method to GET and paste this API Url then hits the Send button.

http://localhost/slimapi/public/api/customer/1

You should see the updated customer data you just did.

Create DELETE request for deleting a single customer data

At the customers.php, add the code below at the last line.

/**
 * Delete a Single Customer data
 */
// create DELETE HTTP request
$app->delete('/api/customer/delete/{id}', function( Request $request, Response $response){
  // get attribute from URL
  $id = $request->getAttribute('id');   

  $sql = "DELETE FROM customers WHERE id = $id";

  try {
    // Get DB Object
    $db = new db();

    // connect to DB
    $db = $db->connect();

    $stmt = $db->prepare($sql);  

    // execute sql
    $stmt->execute();
    $db = null;
    
    // return the message as json format
    echo '{"notice" : {"msg" : "New Customer Deleted.."}';

  } catch( PDOException $e ) {

    // return error message as Json format
    echo '{"error": {"msg": ' . $e->getMessage() . '}';
  }

});

Then at the REST API Testing extension, changes the method to DELETE and paste this API Url. Then hits the Send button. You should see this message {“notice” : {“msg” : “New Customer Deleted..”}.

http://localhost/slimapi/public/api/customer/delete/1

Check the deleted data by changing the method to GET and paste this API Url then hit the Send button. You should not see the customer data #1 since it is deleted.

http://localhost/slimapi/public/api/customers

The complete source code

The complete source code can be download below. You can run the composer with the composer file to install the Slim framework.

SlimAPI (7413 downloads )

That’s it for today. This is my first tutorial on my blog. I hope you enjoy it. See you in the next tutorial.