Menu

Create Simple REST API with Slim Framework

Create Simple REST API with Slim Framework

Slim is a lightweight open source PHP micro framework. This framework is the best to write simple yet powerful web applications and APIs. The Slim framework supports all HTTP method like (GET,POST,PUT,DELETE) and have very handy URL structure with routers, middlewares, bodyparser along with page templates and lots more. Due to this, Slim framework become the best choice of PHP developers to develop simple REST API. Previously we have published tutorial to create simple REST API using PHP and get huge response. Many of them also request tutorial to develop simple REST API with Slim Framework. So in this tutorial you will learn how to Create Simple REST API with Slim Framework.



In this tutorial we will create simple REST API with GET, POST, PUT and DELETE HTTP Request. We will fetch records from database with GET request, insert new record with POST request, update record with PUT request and delete record with DELETE request. The REST APIs help to communicate between the client app and the server application, so you can use this REST API with all kind of web application like Desktop, mobile etc.

So we will cover this tutorial with step by step to create simple REST API with Slim Framework.

Steps1: Install and Configure Slim Framework on XAMPP Server
First we will install Slim Framework on XAMPP server. We will download Slim Framework Skeleton Application and unzip it. We will have Slim-Skeleton-master folder and we will keep this into XAMPP/htdocs. Then we will rename folder to slimrestapi. Now the project folder will be xampp/htdocs/slimrestapi.

Then we need to run composure update to install Slim Framework. So install composure on your computer if its not installed. Then go to the xampp/htdocs/slimrestapi folder into command line and run below composure update command.

composer update

The Slim Framework installed on your server and can be accessed through URL localhost/slimrestapi/public/. So now we need to create Virtual Host into XAMPP server to access it with correct URL. So we will open XAMPP/apache/conf/extra/httpd-vhosts.conf file and needs to add below codes at the end of file.

<VirtualHost *:80>
DocumentRoot E:/XAMPP/htdocs/slimrestapi/public
<Directory "E:/XAMPP/htdocs/slimrestapi/public">
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>


We also need to uncomment below line from httpd-vhosts.conf file.
NameVirtualHost *:80

Now finally open C:\Windows\System32\drivers\etc\hosts file and add below codes at the end of file to change localhost to slimrestapi.

127.0.0.1 slimrestapi

Now the Slim Framework installed and configured successfully. Restart XAMPP server and access your Slim Framework project through URL http://slimrestapi/ into the browser.


Steps2: Create MySQL Database Table
As in this tutorial, we will get data from MySQL database table and also insert, update and delete with HTTP request, so we will create MySQL database table developers using below query.

CREATE TABLE `developers` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`skills` varchar(255) NOT NULL,
`address` varchar(255) NOT NULL,
`gender` varchar(255) NOT NULL,
`designation` varchar(255) NOT NULL,
`age` int(11) NOT NULL,
`image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;


we will also insert few records into table to perform actions.

INSERT INTO `developers` (`id`, `name`, `skills`, `address`, `gender`, `designation`, `age`, `image`) VALUES
(1, 'Smith', 'Java', 'Newyork', 'Male', 'Software Engineer', 34, 'image_1.jpg'),
(2, 'David', 'PHP', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(3, 'Rhodes', 'jQuery', 'New Jersy', 'Male', 'Web Developer', 30, 'image_2.jpg'),
(4, 'Sara', 'JavaScript', 'Delhi', 'Female', 'Web Developer', 25, 'image_2.jpg'),
(5, 'Shyrlin', 'NodeJS', 'Tokiyo', 'Female', 'Programmer', 35, 'image_2.jpg');


Steps3: Connect to MySQL Database with Slim Framework
In our slim project, we will open src/settings.php file and configure MySQL database setting by adding below database config array into settings.

"db" => [
"host" => "localhost",
"dbname" => "phpzag_demos",
"user" => "root",
"pass" => "123456"
],



Now we will open src/dependencies.php file and configure PHP database library PDO to make connection to MySQL database.

$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;
};



Steps4: Details of HTTP API Calls
In this tutorial we will implement following API Calls.




























GET/developersRetrieve all developers
GET/developer/1
Retrieve developer with id == 1
POST/developer/insertAdd a new developer
PUT/developer/update/1Update developer with id == 1
DELETE/developer/delete/1Delete developer with id == 1


Steps5: Implement GET API calls with Slim Framework
Now we will make changes in src/routes.php to implement GET HTTP Call to get all developers data.

$app->get('/developers', function ($request, $response, $args) {
$this->logger->info("index '/' route");
$sth = $this->db->prepare("SELECT id, name, skills, address, gender, designation, age FROM developers ORDER BY id");
$sth->execute();
$developer = $sth->fetchAll();
return $this->response->withJson($developer);
});


The above HTTP GET request will return all developers records when make API Call using this URL http://slimrestapi/developers.


We will also make changes in src/routes.php to implement GET HTTP Call to get particular developer data using developer id.

$app->get('/developer/{id}', function ($request, $response, $args) {
$sth = $this->db->prepare("SELECT id, name, skills, address, gender, designation, age FROM developers WHERE id=:id");
$sth->bindParam("id", $args['id']);
$sth->execute();
$developer = $sth->fetchObject();
return $this->response->withJson($developer);
});


The above HTTP GET request will return specific developer records when make API Call using this URL http://slimrestapi/developer/1 with developer id.

Steps6: Implement POST API calls with Slim Framework
We will make changes in src/routes.php to implement POST HTTP Call to insert developer record.
$app->post('/developer/insert', function ($request, $response) {
$developer = $request->getParsedBody();
$sql = "INSERT INTO developers (name, skills, address, gender, designation, age) VALUES (:name, :skills, :address, :gender, :designation, :age)";
$sth = $this->db->prepare($sql);
$sth->bindParam("name", $developer->name);
$sth->bindParam("skills", $developer->skills);
$sth->bindParam("address", $developer->address);
$sth->bindParam("gender", $developer->gender);
$sth->bindParam("designation", $developer->designation);
$sth->bindParam("age", $developer->age);
$sth->execute();
$developer->id = $this->db->lastInsertId();
return $this->response->withJson($developer);
});


The above API call accepts POST request and will insert developer record into MySQL database table when make API Call using this URL http://slimrestapi/developer/insert


Steps6: Implement PUT API calls with Slim Framework
We will make changes in src/routes.php to implement PUT HTTP Call to update developer record.

$app->put('/developer/update/[{id}]', function ($request, $response, $args) {
$developer = $request->getParsedBody();
$sql = "UPDATE developers SET name=:name, skills=:skills, address=:address, gender=:gender, designation=:designation, age=:age WHERE id=:id";
$sth->bindParam("name", $developer->name);
$sth->bindParam("skills", $developer->skills);
$sth->bindParam("address", $developer->address);
$sth->bindParam("gender", $developer->gender);
$sth->bindParam("designation", $developer->designation);
$sth->bindParam("age", $developer->age);
$sth->bindParam("id", $id);
$sth->execute();
return $this->response->withJson($developer);
});


The above API call accepts PUT request and will update a developer record into MySQL database table when make API Call using URL like http://slimrestapi/developer/update/1 with developer id.


Steps6: Implement DELETE API calls with Slim Framework
We will make changes in src/routes.php to implement DELETE HTTP Call to delete developer record.

$app->delete('/developer/delete/[{id}]', function ($request, $response, $args) {
$sth = $this->db->prepare("DELETE FROM developers WHERE id=:id");
$sth->bindParam("id", $args['id']);
$sth->execute();
$developer = $sth->fetchAll();
return $this->response->withJson($developer);
});

The above API call accepts DELETE request and will delete developer record from MySQL database table when make API Call using URL like http://slimrestapi/developer/delete/1 with developer id.

That's all. I hope this tutorial will be helpful for you to develop simple REST API with Slim Framework. Feel free to discuss your queries. You can download complete source code of this API from the Download link below.
[sociallocker]Download[/sociallocker]

Ads middle content1

Ads middle content2