Creating A REST API With Lumen and MySQL – Part II

This is Part 2 of the Rest API Using Lumen tutorial, we have completed configuration of lumen and migration of database.

Now we will learn about CRUD operation REST API Using Lumen and MySQL.We will create customer module that will have add customer record, edit customer record, delete customer record and get all customers information from MySQL database.

Creating A REST API With Lumen and MySQL

Its very easy and simple to create rest-api using lumen. We just need enter route information into routes.php file and add action method into controller file.

The File Structures of Lumen Application

There are following file will participate into this rest api tutorial,

  • \bootstrap\app.php : This file will use for enable and register library.
  • app\Http\routes.php : Rest api route information.
  • app\Model\Customer.php : This is model class for customer table.
  • app\Http\Controllers\CustomerController.php : This is main controller file of customer module, This will have all CRUD action method.

The Rest End Points Details

We will create following rest end point in this Lumen Rest Tutorial,

Route Method Type Posted JSON Description
/customer GET JSON Get all customers data
/customer/{id} GET JSON Get a single customer data
/customer POST JSON {"Name": "Rachel", "Address": "120 st park aevnue NY", "Country" : "America", "Phone" : "1234567451"} Insert new customer record into database
/customer/[id] PUT JSON {"Name": "Rachel1", "Address": "110 st park aevnue NY", "Country" : "America", "Phone" : "1234567451", "Id":1} Update customer record into database
/customer DELETE JSON {"Id" : 59} Delete particular customer record from database

How To Enable Eloquent in Lumen

Eloquent is an ORM with in Lumen that help to create ActiveRecord implementation with database.Each database table has a corresponding “Model” which is used to interact with that table for insert, update, delete etc operation.We need un-comment below line into bootstrap/app.php file.

$app->withFacades();
$app->withEloquent();

How to define Model into Lumen

We will create Customer Model class file into model folder, if If you don’t find Model folder please create new one.We will create Model\Customer.php file and paste below code into this file.


Here we have define column name which will use to insert/edit records and will send data from server side.created_on and updated_on column value will automatically insert using current server timestamp, you don’t need to send those col value from server.

Rest API for Insert Record into MySQL Using Lumen

We will create rest api to insert customer record into mysql database table.We will use json format data to send as a parameters and save into customer MySQL table using eloquent model.

Step 1: Added insert record route entry into routes.php.

$app->post('customer', 'CustomerController@createCustomer');

we have added /api/v1/customer end point with HTTP POST type request to create insert record rest api. End points telling routes class, where he will go, like CustomerController class and createCustomer method.

Step 2: We will create createCustomer() method into CustomerController.php.

	/**
    * Method to create new record into customer table
    *
    * @author Rachel
    */
    public function createCustomer(Request $request) {
        $response = array();
        $parameters = $request->json()->all();
 
        $rules =  array(
            'name'    => 'required'
        );
        $customer_name = $parameters['name'];
 
        $messages = array(
            'name.required' => 'name is required.'
        );
 
        $validator = \Validator::make(array('name' => $customer_name), $rules, $messages);
        if(!$validator->fails()) {
            $response = Customer::create($parameters);
 
            return Helper::jsonpSuccess($response);
        } else {
         $errors = $validator->errors();
            return Helper::jsonpError('Validation error(s) occurred', 400, 400, $errors->all());
      }
	}

I have use validator class for server side validation.We have get all json parameters using Request json()->all() method, successfully validate parameters, we will create entry into MySQL database using create() model method.

Rest API for Update Record into MySQL Using Lumen

We will create rest api to update customer record into MySQL database table.We will use json format data for request and response.

Step 1: Added update record route entry into routes.php
$app->put('customer/{id}', 'CustomerController@updateCustomer');

we have added /api/v1/customer end point with HTTP PUT type request to update record rest API. We will use CustomerController class and updateCustomer method.

Step 2: We will create updateCustomer() method into CustomerController.php. This method will update record into table against corresponding customer id

	/**
    * Method to update record into customer table
    *
    * @author Rachel
    */
    public function updateCustomer(Request $request, $id) {
        $response = array();
        $parameters = $request->json()->all();
        $customer = Customer::find($id);
       
        if(!empty($customer)) {
            $customer->Name = $parameters['name'];
            $customer->Id = $id;
            $customer->Address = $parameters['address'];
            $customer->Country = $parameters['country'];
            $customer->Phone = $parameters['phone'];
 
            $customer->save();
            return Helper::jsonpSuccess($customer);
           
        } else {
            return Helper::jsonpError('Record Does not found', 400, 400, '');
        }
    }

As you can see, I have get $id parameters as an URI and find into database table, if exist then bind all updated filed value and update entry into MySQL database using save() model method.

Rest API To Delete Record from MySQL Using Lumen

We will create rest api to delete customer record from MySQL database table.

Step 1: Added insert record route entry into routes.php.
$app->delete('customer/{id}', 'CustomerController@deleteCustomer');

we have added /api/v1/customer end point with HTTP DELETE type request to update record rest api. We are calling CustomerController class and deleteCustomer method.

Step 2: We will create deleteCustomer() method into CustomerController.php.This method will delete record from table of corresponding customer id

	/**
    * Method to delete record from customer table
    *
    * @author Rachel
    */
    public function deleteCustomer($id) {
        $customer = Customer::find($id);
       
        if(!empty($customer)) {
            $res = $customer->delete();
 
            return Helper::jsonpSuccess($res);
           
        } else {
            return Helper::jsonpError('Record Does not found', 400, 400, '');
        }
    }

As you can see, I have get $id parameters as an URI and find into database table, if exist then delete particular customer using delete() model method.

Rest API To Get All Records MySQL Using Lumen

We will create rest api to fetch all customers record from MySQL database table.We will define method CustomerController file and return all customers record as json format data.

Step 1: Added all record route entry into routes.php.

$app->get('customer', 'CustomerController@getAllCustomers');

we have added /api/v1/customer end point with HTTP GET type request to update record rest api. We are calling CustomerController class and getAllCustomers method.

Step 2: We will create getAllCustomers() method into CustomerController.php.This method will fetch all customer records from MySQL table.

	/**
    * Method to get all customers
    *
    * @author Rachel
    */
	public function getAllCustomers() {die('ddd');
	$response = Customer::all();
   
	 return $response;
	}

I used all() method of eloquent ORM to fetch all records from customer table.

Conclusion :

We have created customer module with Lumen micro-restFramework.We have created migration script and binded with model lumen class.This tutorial have CRUD operation functionality using REST api and updated data into MySQL database.

You can download source code from below link.