Rest API In Codeigniter – 3.

Rest API In Codeigniter – 3.

Before understanding “REST API” we have to understand what is REST and what is API first.

What is REST?

REST stands for Representational State Transfer which is a technique or architecture for managing information over the Internet. It is used for sending requests from client to server  and getting response from server to client using http methods like GET,POST,PUT,DELETE.Codeigniter Form Validation

What is An API?

API stands for “Application Programming Interface” , which is a set of rules to communicate that allow one application to talk to another application. Rules might be insert data into table, select data from table etc.

Why do we need a Rest API?

1 .It is lightweight -> it is the lightest way to create , read, update and delete records from the database. 

2 .It is cross platform ->  It can be  used by any website or application regardless what language it is written in because requests are based on the standard HTTP method and response is usually returned in the JSON format that all modern programming languages can read.

In this example we will create contact form and perform the database operations using REST API in codeigniter.

These are the steps to create Rest API In Codeigniter-3.

Create table.

CREATE TABLE `contact_form` ( `con_id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(250) NOT NULL , `email` VARCHAR(250) NOT NULL , `mobno` BIGINT(10) NOT NULL , `address` TEXT NOT NULL , `date_added` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`con_id`)) ENGINE = InnoDB;

Create Model in application/models folder names as contact_model .

Write getData function within model class. This function is being used for select data from the database.

public function getData(){

        return $this->db->get('reg')->result();

    }

Create save function within model class. This function is being used for insert data into the database.

 public function save($data){        

	$address = isset($data->address)?$this->db->escape($data->address):'';
            $data = array(
                            'name' => $this->db->escape($data->name),
                            'email'=> $this->db->escape($data->email),
                            'mobno' => $this->db->escape($data->mobno),
                            'address' =>$address
                     );

           if($this->db->insert('reg',$data)){
                     return true;
            }else{
                     return false;
            }
    }

Write update function within model class. This function is being used for update data into the database.

public function update($postdata){        

	$address = isset($postdata->address)?$this->db->escape($postdata->address):'';
            $data = array(
                            'name' => $this->db->escape($postdata->name),
                            'email'=> $this->db->escape($postdata->email),
                            'mobno' => $this->db->escape($postdata->mobno),
                            'address' =>$address
                     );

            if($this->db->update('reg', $data, array('id' => $this->db->escape($postdata->id)))){
                 return true;
            }else{
                return false;
            }
    }

Write deletedata function within model class. This function is being used for delete data from the database.

public function deletedata($id){
		
		$this->db->where('id', $id)->delete('reg');		
		return $this->db->affected_rows()>0?true:false;
		 
	}

Create Controller in application/controllers folder named as Contact.

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Contact extends CI_Controller
{

    public function __construct(){

           parent::__construct();
          $this->load->model('contact_model');        
    }
    
    public function index() {
                
		$data['contacts'] = $this->contact_model->getData();
                echo json_encode($data);
    }

    public function create(){

		$postdatas = json_decode( file_get_contents('php://input') );		
		$required_parameters = array('name','email','mobno');
		 
        $retval = $this->validate($required_parameters,$postdatas);		 
        if($retval==1) {
				 
			   $return = $this->contact_model->save($postdatas);
               if($return == true){ 
			   
                  $array = array('sts'=>true,'val'=>'Data saved successfully');
                }else{
                    $array = array('sts'=>false,'val'=>'Something went wrong');
                }               
        }else{
			 
			$array = array('sts'=>false,'val'=>$retval);
        }

        echo json_encode($array);
    }
	
	public function update(){
   
		$postdatas = json_decode( file_get_contents('php://input') );		
		$required_parameters = array('name','email','mobno'); 		 
		if(!isset($postdatas->id)){
			
			$array = array('sts'=>false,'val'=>'Please enter id to update');
		}else{
			
			$retval = $this->validate($required_parameters,$postdatas);	
			if($retval==1) {
					 
				   $return = $this->contact_model->update($postdatas);
				   if($return == true){ 
				   
					  $array = array('sts'=>true,'val'=>'Data updated successfully');
					}else{
						$array = array('sts'=>false,'val'=>'Something went wrong');
					}               
			}else{
				 
				$array = array('sts'=>false,'val'=>$retval);
			}
		}

        echo json_encode($array);
   }

   public function remove(){
	   
	   $postdatas = json_decode( file_get_contents('php://input'));
	   if(!isset($postdatas->id)){
			
			$array = array('sts'=>false,'val'=>'Please enter id to delete');
	  }else{
			
			$return = $this->contact_model->deletedata($postdatas->id);
			 
				if($return == true){ 
				   
					$array = array('sts'=>true,'val'=>'Data deleted successfully');
				}else{
						$array = array('sts'=>false,'val'=>'Something went wrong');
				}               
		}
		
	 echo json_encode($array);
	   
   }

	public function validate($required_parameters,$postdatas){
		
		$error = array();
		foreach($required_parameters as $field){
			
			if(!isset($postdatas->$field)){
				
				$error[] = $field;
			}
		}
		 
		if(count($error)==0){
			
			return 1;
			
		}else{
			
			$count = (count($error)>=2?'are':'is');
			return implode(", ", $error).' '.$count.' required';;
			
		}
	}
	
	
}


This is the screen how we can call rest api to display all data.

This is the screen how we can call rest api to save the data.

Exit mobile version