Your support helps keep this blog running! Secure payments via Paypal and Stripe.
Building a REST API is essential for modern web and mobile applications, and the Slim Framework offers a lightweight yet powerful solution for PHP developers. In this guide, you’ll learn how to create a RESTful API using Slim—from installation and routing to handling requests and returning JSON responses—so you can build fast, secure, and scalable backends without the complexity of a full-stack framework.
What is an 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.
From a business standpoint, API can open up new opportunities for new business partnerships with related service providers such as Travel businesses, spas, Tour, Hotel, and restaurant.
APIs can be categorized into 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 development purposes for developers. The public API is published outside the company, such as the tour packages information. The partner API is used by the specific parties who have made an agreement. For example, you agree to sell Thailand package tours at a special price for the European tour company. So you can provide this special API for this European tour company only.
As I am a web developer, I mostly work with Web APIs or also 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 is 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.
Before We Start
- Web server: I use WampServer. But you can use any web server you like. So we can run PHP on the web server.
- 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 Composer to install Slim.
- 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.
Today’s Sections
- Install Slim framework
- Set up the file structure to work with Slim (this is my preference. You can set up any file structure you like)
- Create the database and create a customer table
- Create the database connection with the PDO object
- Create
GET/POST/PUT/DELETErequests for the customer APIs
Install Slim Framework
- At the webroot, which is the
wwwIn the Wamp server, I create a new folder called “slimapi“. So the path looks likewww\slimapi - Open 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 has been installed 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, andcomposer.lock. Those folders and files are installed by the composer.
Setting Up the File Structure
- 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 whether 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 added “../” in front of the vendor path because my file structure is set 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 Slim and other related dependencies from Slim. Next, we create a new Slim instance.
After that, the $app->get() is called to make 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 in the browser. Finally, we run the $app->run() command to let the slim start to work.
# The first route is created and ready to run
Now you can run the API URL below in your browser. Let’s run it.
http://localhost/slimapi/public/index.php/hello/AppleRinquestYou should see “Hello, AppleRinquest” as the result in the browser. Congrats!
# Get rid of the index.php
It seems the URL is long. I’m gonna get rid of the index.php. To do that, you just create an .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 setting up 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 sets the blocking the system files written by other programs 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 web server. I have not set the virtual host in this tutorial.
Create the Database and Create a Customer Table
- At the PHPMyAdmin, create a new database called “slimapi“
- Create a new table called “customers” with 3 fields (id, name, and address). The ID will be set as
INT(11), primary key, and an Auto Increment. Name and address are set asVarchar(150). - Add some data for testing. I added 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.phpfile in there. - In the
db.phpfile, I added the code below. Don’t forget to change the database config to match 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.phpunder the public folder, I include thedb.phpafter theautoload.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 in the browser.
http://localhost/slimapi/public/hello/AppleRinquestYou should see the “Hello, AppleRinquest” message on your browser. That means no error from the db.php.
Create a GET request for all customers’ data
- Under the src folder, I create a new routes folder, and under the routes folder, I create
customers.php - In the
customers.php, I added 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.phpunder the public folder, I include thecustomers.phpbefore$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 in the browser for testing the route.
http://localhost/slimapi/public/api/customersYou should see the “Sawandee my customers” message on the browser.
- Since we have already created the database connection and customer table. We will replace the
getBody()->write()with the query instead. To do that, you will add the query to thecustomers.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’s test it on the browser using this API URL.
http://localhost/slimapi/public/api/customersYou should see your customer data in JSON format, like [{"id":"1","name":"John Doe","address":"Las Vegas, USA"},{"id":"2","name":"Sandy Wong","address":"HongKong"}]
Using the REST API Testing Chrome extension
- Before I forget, we should test our APIs in the 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. - In the response section, you should see 200 OK, which means success, and in the body section, you should see the customer data in JSON format.

At this point, we can get all customers’ data with /api/cusotmers route. Next, we want to get the single customer data only.
Create a GET Request for a Single Customer’s Data with a Parameter
- In 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/1You should see the customer data of ID #1 in the body section.
Create a POST Request for Adding New Customer Data
- Normally, when users add new data, they will add it via an adding form. Then, the form is submitted, and the form action will redirect to the API.
- To create the
POST requestfor adding new customer data, you will add the code below to the last line in thecustomers.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, in the REST API Testing extension, change the GET method to the POST method. Then paste this API URL and add the query parameter as the screenshot below. Finally, hits the Send button.
http://localhost/slimapi/public/api/customer/add
If it is successful, in 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 change the method to GET and paste this API URL. Then hit the Send button. You should see the new customer data you just added.
http://localhost/slimapi/public/api/customersCreate a PUT Request for Updating a Single Customer’s Data
- Finally, we will update the customer data for the specific ID.
- In 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/1Add the new query parameter for name and address. Make sure the header content type is application/JSON. Then hit 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 hit the Send button.
http://localhost/slimapi/public/api/customer/1You should see the updated customer data you just did.
Create a DELETE Request for Deleting a Single Customer’s Data
In the customers.php, add the code below to 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, change the method to DELETE and paste this API URL. Then hit the Send button. You should see this message {"notice" : {"msg" : "New Customer Deleted.."}.
http://localhost/slimapi/public/api/customer/delete/1Check 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 has been deleted.
http://localhost/slimapi/public/api/customersThe Complete Source Code
The complete source code can be downloaded below. You can run the composer with the composer file to install the Slim framework.
Please complete the form. Upon successful submission, the file download will begin automatically. Please allow a few seconds for the submission to complete.
That’s it for today. This is my first tutorial on my blog. I hope you enjoy it. See you in the next tutorial.
Your support helps keep this blog running! Secure payments via Paypal and Stripe.
