This is a second part tutorial on Simple Restful API Example of CRUD Operation Using Slim framework.
We have configured MySQL with the slim framework, we have also created customer table into the database, Added CORS module for CROSS origin issue of rest API access from other application.
We will create the following REST API endpoints in this rest API tutorial,
Route | Method | Type | Posted JSON | Description |
---|---|---|---|---|
/customers | GET | JSON | – | Get all customers data |
/customer/{id} | GET | JSON | – | Get a single customer data |
/create | POST | JSON | {"name": "Rachel", "address": "120 st park aevnue NY", "country" : "America", "phone" : "1234567451"} | Insert new customer record into database |
/update/{id} | PUT | JSON | {"name": "Rachel1", "address": "110 st park aevnue NY", "Country" : "america", "phone" : "1234567451", "Iid":1} | Update customer record into database |
/delete/{id} | DELETE | JSON | {"id" : 59} | Delete particular customer record from database |
I will add the above rest endpoints and register them into the routes file.
Table of Contents
Rest API to insert a record into MySQL database
We will create a rest call to insert a record into the MySQL database. I will add insert customer routes information into src/routes.php
file,
// API group $app->group('/api', function () use ($app) { // Version group $app->group('/v1', function () use ($app) { $app->post('/create', 'addCustomer'); } }
As you can see, I have created api/v1
prefix endpoints into each rest api, this is helpful into API versioning process. I have used POST type HTTP request to handle insert record rest API. The rest endpoints would be http://host/api/v1/create and controller method is addCustomer().I am creating all controller actions into public/index.php
file.
Now, We will create addCustomer
method into public/index.php
the file to insert customer information using the rest api.
function addCustomer($request) { $cust = json_decode($request->getBody()); $sql = "INSERT INTO customer (name, address, country, phone) VALUES (:name, :address, :country, :phone)"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("name", $cust->name); $stmt->bindParam("address", $cust->address); $stmt->bindParam("country", $cust->country); $stmt->bindParam("phone", $cust->phone); $stmt->execute(); $cust->id = $db->lastInsertId(); $db = null; echo json_encode($cust); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } }
We have got all posted JSON data into $cust a variable, we have created SQL query using posted data and execute() model method to insert records into the MySQL database.
You can test rest calls http://hostname/api/v1/create using any rest test client like postman etc, it will return customer JSON data as a result.
Rest API to Fetch All Customers
We will create rest call to fetch records from MySQL database. I will add fetch all customer’s routes information into src/routes.php
file,
$app->get('/customers', 'getCustomers');
I have used GET type HTTP request to fetch records from the database using rest api. The rest endpoints would be http://host/api/v1/customers
and controller method is getCustomers()
.
Now, We will create getCustomers()
method into public/index.php
file for fetching customer’s information using rest api.
function getCustomers() { $sql = "select * FROM customer"; try { $db = getConnection(); $stmt = $db->query($sql); $emp = $stmt->fetchAll(PDO::FETCH_OBJ); $db = null; return json_encode($emp); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } }
I have prepared an SQL query to fetch customer records from the database and return results as a JSON object array.
Rest API to Fetch Single Customer Data
We will create a rest call to fetch a single record from the MySQL database. I will add get customer information routes information into src/routes.php
file,
$app->get('/customer', 'getCustomer');
I have used GET type HTTP request to fetch customer information from the database using rest api. The rest endpoints would be http://host/api/v1/customer
and controller method is getCustomer()
.
Now, We will create getCustomer()
method into public/index.php
file for fetching customer information using rest api.
function getCustomer($request) { $id = 0;; $id = $request->getAttribute('id'); if(empty($id)) { echo '{"error":{"text":"Id is empty"}}'; } try { $db = getConnection(); $sth = $db->prepare("SELECT * FROM customer WHERE id=$id"); $sth->bindParam("id", $args['id']); $sth->execute(); $todos = $sth->fetchObject(); return json_encode($todos); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } }
I have prepared an SQL query to fetch customer records from the database and return results as JSON object.
Rest API to Update Customer Data
We will create a rest call to update customer records in the MySQL database. I will add updated customer information routes information into src/routes.php
file,
$app->put('/update/{id}', 'updateCustomer');
I have used PUT type HTTP request to update customer information from MySQL database using rest api. The rest endpoints would be http://host/api/v1/update/{id}
and controller method is updateCustomer()
.
Now. We will create updateCustomer()
method into public/index.php
file for updating customer information using rest api.
function updateCustomer($request) { $cust = json_decode($request->getBody()); $id = $request->getAttribute('id'); $sql = "UPDATE customer SET name=:name, address=:address, country=:country, phone=:phone WHERE id=:id"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("name", $cust->name); $stmt->bindParam("address", $cust->address); $stmt->bindParam("country", $cust->country); $stmt->bindParam("phone", $cust->phone); $stmt->bindParam("id", $id); $stmt->execute(); $db = null; echo json_encode($cust); } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } }
$cust
variable will have all updated record params and created MySQL query to update record against customer id, We executed prepare SQL query into MySQL customer table using inbuilt execute()
method.
Rest API to Delete Customer Data From Database
To remove the customer record from the MySQL database, we will make a rest call. I’ll update the routes information in the src/routes.php
file and delete the customer information.
$app->delete('/delete/{id}', 'deleteCustomer');
I have used DELETE type HTTP request to update customer information from MySQL database using rest api. The rest end points would be http://host/api/v1/delete/{id}
and controller method is deleteCustomer()
.
Now, We will create deleteCustomer()
method into public/index.php
file for delete customer information using rest api.
function deleteCustomer($request) { $id = $request->getAttribute('id'); $sql = "DELETE FROM customer WHERE id=:id"; try { $db = getConnection(); $stmt = $db->prepare($sql); $stmt->bindParam("id", $id); //$stmt->execute(); $db = null; echo '{"error":{"text":"successfully! deleted Records"}}'; } catch(PDOException $e) { echo '{"error":{"text":'. $e->getMessage() .'}}'; } }
We have used passed customer id and delete record from MySQL database against customer id.
Conclusion:
We have configured SLIM framework in first part of this application, here I have learn rest API for CRUD operation for customer management module.We have created Restful API for fetch customer, add customer, update customer and delete customer from MySQL database.
You can download source code from below link.