Rahul Bari April 16, 2019

RESTful API with Slim Framework

Slim is a full-featured, open-source PHP micro-framework that enables you to write ‘simple yet powerful’ web applications and APIs in a quick manner. It comes with a sophisticated URL dispatcher and middleware architecture that makes it perfect for static websites or API prototyping. It supports all (GET, POST, PUT, DELETE) the HTTP methods.

This article explains Slim Framework in detail, illustrating how you can use it to rapidly build and deploy a REST API with support for authentication and multiple request/response formats.

How to install

If you are using Composer, the PHP dependency manager, simply issue the following command:

$ composer create-project slim/slim-skeleton [my-app-name]

Replace [my-app-name] with the desired directory name for your new application. The above command will create a project using Slim-Skeleton application

Now You can run it with PHP’s built-in web server or you can point your browser with full URL.

$ cd [my-app-name]

After going through the above steps, if you point your browser to http://192.168.0.70/slim_api/public/, you would have following output in the browser –

Database Design

CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL,
`task` varchar(200) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
`created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `tasks` ADD PRIMARY KEY (`id`);
ALTER TABLE `tasks` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Insert some sample data into the tasks table:

INSERT INTO `tasks` (`id`, `task`, `status`, `created_at`) VALUES
(1, 'API Call 1', 1, '2019-03-15 23:50:40'),
(2, 'API Call 2', 1, '2019-03-15 23:50:40'),
(3, 'API Call 3', 1, '2019-03-15 23:50:40'),
(4, 'API Call 4', 1, '2019-03-15 23:50:40'),
(5, 'API Call 5', 1, '2019-03-15 23:50:50');

Database configuration

Open your src/settings.php file and configure your database setting by adding/editing database config array as shown below:

"db" => [
"host" => "your-host-name",
"dbname" => "your-db-name",
"user" => "your-username",
"pass" => "your-password"
],

Now open your src/dependencies.php file and configure database library. There are many database libraries available for PHP, but this example uses PDO – this is available in PHP as standard so it’s probably useful in every project, or you can use your own libraries by adapting to the following example:

In the below code we are injecting database object into container using dependency injection, in this case, called db:

$container['db'] = function ($c) {
$settings = $c->get('settings')['db'];
$pdo = new PDO("mysql:host=" . $settings['host'] . ";dbname=" . $settings['dbname'], $settings['user'], $settings['pass']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
};

We are going to implement the following API calls –

GET /tasks (Retrieve all tasks)
GET /task/1 (Retrieve task with task_id)
POST /task (Add a new task)
PUT /task/1 (Update task with task_id)
DELETE /task/1 (Delete task with task_id)

Implementing the API calls with Slim Framework:

Now that we have our Slim app up and running with the database connection, we need to manage tasks in the database.

Getting the Tasks list – We are going to create a new route so that when a user hits /tasks, it will return a list of all tasks in JSON format. Open your src/routes.php and add

$app->get('/tasks', function ($request, $response, $args) {
$sth = $this->db->prepare("SELECT * FROM tasks");
$sth->execute();
$tasks = $sth->fetchAll();
return $this->response->withJson($tasks);
});

This function simply returns all tasks’ information as you can see in this query, to call this API use this URL http://192.168.0.70/slim_api/public/tasks

Add new task – We are going to create a new route so that when a user sends a post request to /task with required data, the app would add a new record to the database.

$app->post('/taskinsert', function ($request, $response) {
$input = $request->getParsedBody();
$sth1 = $this->db->prepare("SELECT * FROM tasks WHERE task=:task");
$sth1->bindParam("task", $input['task']);
$sth1->execute();
$row = $sth1->fetch(PDO::FETCH_ASSOC);
if ($row) {
$arr = array('code' => 409, 'data' => 'row already exists');
return $this->response->withJson($arr);
} else {
$sql = "INSERT INTO tasks (task) VALUES (:task)";
$sth = $this->db->prepare($sql);
$sth->bindParam("task", $input['task']);
$sth->execute();
$input['id'] = $this->db->lastInsertId();
//fetching inserted data and showing in response
$sth = $this->db->prepare("SELECT * FROM tasks WHERE id=:id");
$sth->bindParam("id", $input['id']);
$sth->execute();
$task = $sth->fetchObject();
//response
$arr = array('code' => 200, 'data' => $task);
return $this->response->withJson($arr);
}
});

This API accepts post request and inserts submitted data into your database. To call this API use this URL http://192.168.0.70/slim_api/public/taskinsert

Delete Task – We are going to create a new route so that when a user sends a delete request to /task/{id}, the app will delete a record from the database.

$app->delete('/deletetask/[{id}]', function ($request, $response, $args) {
$sth1 = $this->db->prepare("SELECT * FROM tasks WHERE id=:id");
$sth1->bindParam("id", $args['id']);
$sth1->execute();
$row = $sth1->fetch(PDO::FETCH_ASSOC);
if ($row) {
$sth = $this->db->prepare("DELETE FROM tasks WHERE id=:id");
$sth->bindParam("id", $args['id']);
$sth->execute();
if ($sth->execute() == 1) {
$arr = array('code' => 200, 'message' => 'Data deleted');
return $this->response->withJson($arr);
}
} else {
$arr = array('code' => 404, 'message' => 'ID not found or invalid');
return $this->response->withJson($arr);
}
});

This API accepts delete request and deletes data from your database. To call this API use this URL http://192.168.0.70/slim_api/public/deletetask/task_id

Update Task – Here we are going to design a database to create a new route so that when a user sends a put request to /task/{id} with required data, the app will update a record based on match parameter in the database.

$app->put('/updatetask/[{id}]', function ($request, $response, $args) {
$sth1 = $this->db->prepare("SELECT * FROM tasks WHERE id=:id");
$sth1->bindParam("id", $args['id']);
$sth1->execute();
$row = $sth1->fetch(PDO::FETCH_ASSOC);
if ($row) {
$input = $request->getParsedBody();
$sql = "UPDATE tasks SET task=:task WHERE id=:id";
$sth = $this->db->prepare($sql);
$sth->bindParam("id", $args['id']);
$sth->bindParam("task", $input['task']);
$sth->execute();
$input['id'] = $args['id'];
return $this->response->withJson($input);
} else {
$arr = array('code' => 404, 'message' => 'ID not found or invalid');
return $this->response->withJson($arr);
}
});

This API accepts put request and updates submitted data in your database. To call this API use this URL http://192.168.0.70/slim_api/public/updatetask/task_id

Getting single task – We are going to create a new route so that when a user hits /task/{id}, it will return a task in JSON format.

$app->get('/task/[{id}]', function ($request, $response, $args) {
$sth = $this->db->prepare("SELECT * FROM tasks WHERE id=:id");
$sth->bindParam("id", $args['id']);
$sth->execute();
$task = $sth->fetchObject();
if (!$task == false) {
return $this->response->withJson(array(
'code' => 200,
'data' => $task
), 200);
}
if ($task == false) {
$arr = array('code' => 404, 'message' => 'ID not found or invalid');
return $this->response->withJson($arr);
}
});

This function checks the record of given id and returns, in case it finds something. To call this API, use this URL http://192.168.0.70/slim_api/public/task/task_id

 

In case I missed something, do let me know in the comments and I’ll add it!”

Cheers!!

Need assistance from professionals to build effective RESTful APIs? reach out to us and take your API development to the next level today!

Lets’s Talk

About your ideas and concept