Course Content
Expense Manager App – Login API
0/1
Expense Manager App – Customer API
0/1
Expense Manager App – Product API
0/1
Expense Manager App – Payment Mode API
0/1
CodeIgniter 4 API Tutorial
    About Lesson

    To create an API for managing Products in an Expense Manager App using CodeIgniter 4, you need to set up RESTful routes, controllers, and models. This example will guide you through building a simple API with endpoints for managing customers.

    Steps to Create the Product API

    1. Database Setup

    Create a product_info table in your database to store customer information.

    CREATE TABLE `product_info` (
      `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
      `name` varchar(100) NOT NULL,
      `sale_price` varchar(100) DEFAULT NULL,
      `purchase_price` varchar(100) DEFAULT NULL,
      `ip_address` varchar(100) NOT NULL,
      `created_at` datetime NOT NULL,
      `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
      `status` varchar(10) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

     


    2. Create the Model

    Create a model named ProductModel.php in the app/Models/product directory.


    class ProductModel extends Model {

    protected $db;
    public function __construct(ConnectionInterface &$db) {
    $this->db =& $db;

    $this->table = 'product_info';
    }

    public function addEntry($data) {
    $this->db
    ->table($this->table)
    ->insert($data);
    return $this->db->insertID();
    }

    public function updateEntry($where, $data) {
    return $this->db
    ->table($this->table)
    ->where($where)
    ->set($data)
    ->update();
    }

    public function deleteEntry($where) {
    return $this->db
    ->table($this->table)
    ->where($where)
    ->delete();
    }

    public function getEntry($where) {
    return $this->db
    ->table($this->table)
    ->where($where)
    ->get()
    ->getRow();

    }

    public function getEntryList($where = 0, $start = 0, $limit = 0, $columnName = 0, $orderBy = 0) {
    $builder = $this->db->table($this->table);
    if($where)
    $builder->where($where);
    if($columnName && $orderBy)
    $builder->orderBy($columnName, $orderBy);
    if($limit)
    $builder->limit($limit, $start);
    return $builder
    ->get()
    ->getResult();
    }

    }

     


    3. Create the Controller

    Create a controller named ProductApi.php in the app/Controllers/api/v1 directory.

    class ProductApi extends BaseController {

    public function __construct() {
    $db = db_connect();
    $this->session = ConfigServices::session();

    $this->product = new ProductModel($db);

    $this->ip_address = $_SERVER['REMOTE_ADDR'];
    $this->datetime = date("Y-m-d H:i:s");
    }

    public function index() {

    }

    public function list() {
    $start_limit = $this->request->getPost('start_limit');
    $load_limit = $this->request->getPost('load_limit');
    $where = [
    'status' => '1',
    ];
    $result = $this->product->getEntryList($where, $start_limit, $load_limit, 'name', 'ASC');
    if($result) {
    $json = [
    'status' => true,
    'message' => 'Fetched successfully',
    'results' => $result,
    ];
    } else {
    $json = [
    'status' => false,
    'message' => 'Something went wrong. Please try again!',
    ];
    }
    echo json_encode($json);
    }

    public function create() {
    $name = $this->request->getPost('name');
    $sale_price = $this->request->getPost('sale_price');
    $purchase_price = $this->request->getPost('purchase_price');

    $product_result = $this->product->getEntry(['name' => $name]);
    if($product_result) {
    $json = [
    'message' => "Entered product is already exists.",
    'status' => false,
    ];
    } else {
    $data = [
    'name' => $name,
    'sale_price' => $sale_price,
    'purchase_price' => $purchase_price,
    'ip_address' => $this->ip_address,
    'created_at' => $this->datetime,
    'status' => '1',
    ];
    $result = $this->product->addEntry($data);
    if($result) {
    $json = [
    'message' => "Product has been created successfully.",
    'status' => true,
    ];
    } else {
    $json = [
    'message' => "Something went wrong. Please try again.",
    'status' => false,
    ];
    }
    }
    echo json_encode($json);
    }

    public function details() {
    $product_id = $this->request->getPost('product_id');
    $result = $this->product->getEntry(['id' => $product_id]);
    if($result) {
    $json = [
    'status' => true,
    'message' => 'Fetched successfully',
    'result' => $result,
    ];
    } else {
    $json = [
    'status' => false,
    'message' => 'Something went wrong. Please try again!',
    ];
    }
    echo json_encode($json);
    }

    public function update() {
    $product_id = $this->request->getPost('product_id');
    $name = $this->request->getPost('name');
    $sale_price = $this->request->getPost('sale_price');
    $purchase_price = $this->request->getPost('purchase_price');

    $product_result = $this->product->getEntry(['name' => $name, 'id !=' => $product_id]);
    if($product_result) {
    $json = [
    'message' => "Entered product is already exists.",
    'status' => false,
    ];
    } else {
    $data = [
    'name' => $name,
    'sale_price' => $sale_price,
    'purchase_price' => $purchase_price,
    'ip_address' => $this->ip_address,
    ];
    $result = $this->product->updateEntry(['id' => $product_id], $data);
    if($result) {
    $json = [
    'message' => "Product has been updated successfully.",
    'status' => true,
    ];
    } else {
    $json = [
    'message' => "Something went wrong. Please try again.",
    'status' => false,
    ];
    }
    }
    echo json_encode($json);
    }

    public function delete() {
    $product_id = $this->request->getPost('product_id');
    $where = [
    'id' => $product_id,
    ];
    $result = $this->product->deleteEntry($where);
    if($result) {
    $json = [
    'status' => true,
    'message' => 'Selected product has been deleted successfully.',
    ];
    } else {
    $json = [
    'status' => false,
    'message' => 'Something went wrong. Please try again!',
    ];
    }
    echo json_encode($json);
    }
    }

     


    4. Configure Routes

    Add the following routes to your app/Config/Routes.php file to set up the API endpoints.

    $routes->group('api', function($routes) {
    $routes->group('v1', function($routes) {
    // Products
    $routes->group('product', function($routes) {
    $routes->post('list', 'api/v1/ProductApi::list');
    $routes->post('create', 'api/v1/ProductApi::create');
    $routes->post('details', 'api/v1/ProductApi::details');
    $routes->post('update', 'api/v1/ProductApi::update');
    $routes->post('delete', 'api/v1/ProductApi::delete');
    });
    });
    });

     

    NOTE: Please replace the forward slash in Routes.php with the backward slash in your code.

    This setup provides a complete RESTful API for managing customers in your Expense Manager App using CodeIgniter 4.