The RESTful web services provide a simple way to exchange data between different applications. If your web application needs to communicate over the across platforms, RESTful web service needs to be developed. The application can connect and work with different platforms (web, mobile, etc) using RESTful API. The REST API uses GET, PUT, POST and DELETE HTTP request for data handling across platforms.
CodeIgniter RESTful web service is the easiest way to integrate REST API service in the web application. Using CodeIgniter Rest Server you can easily create the REST API in CodeIgniter. In this tutorial, we will show you how to implement user login and registration with CodeIgniter REST API.
The example code will demonstrate how to build REST API and handle the user authentication (login and registration) with CodeIgniter.
The following steps will be implemented to create REST API in CodeIgniter.
Before getting started, take a look the files structure of CodeIgniter REST application.
To store user’s account information, a table needs to be created in the database. The following SQL creates a users
table with some basic fields in MySQL database.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
`email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`phone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '1=Active | 0=Inactive ',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The following SQL creates a keys
table to store REST API key for authentication.
CREATE TABLE `keys` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`key` varchar(40) NOT NULL,
`level` int(2) NOT NULL,
`ignore_limits` tinyint(1) NOT NULL DEFAULT '0',
`is_private_key` tinyint(1) NOT NULL DEFAULT '0',
`ip_addresses` text,
`date_created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Import the API key data in the keys
table, which will be used to validate the API call.
INSERT INTO `keys` (`id`, `user_id`, `key`, `level`, `ignore_limits`, `is_private_key`, `ip_addresses`, `date_created`) VALUES
(NULL, 1, 'CODEX@123', 0, 0, 0, NULL, '2018-10-11 13:34:33');
We will use REST Controller library to build RESTful web services in CodeIgniter. Follow the below steps to integrate RESTful server in CodeIgniter using REST Controller library.
application/config/
folder and specify the API configurations.
$config['rest_auth'] = 'basic';
$config['rest_valid_logins'] = ['admin' => '1234'];
$config['rest_keys_table'] = 'keys';
$config['rest_enable_keys'] = TRUE;
application/libraries/
folder.application/libraries/
folder.application/language/english/
folder for multilingual support.Note that: All the required files are included in the source code, you don’t need to download these files separately.
The User model handles the database related operations (fetch, insert, update, and delete).
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Model {
public function __construct() {
parent::__construct();
// Load the database library
$this->load->database();
$this->userTbl = 'users';
}
/*
* Get rows from the users table
*/
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->userTbl);
//fetch data by conditions
if(array_key_exists("conditions",$params)){
foreach($params['conditions'] as $key => $value){
$this->db->where($key,$value);
}
}
if(array_key_exists("id",$params)){
$this->db->where('id',$params['id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
//set start and limit
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
$result = $this->db->count_all_results();
}elseif(array_key_exists("returnType",$params) && $params['returnType'] == 'single'){
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->row_array():false;
}else{
$query = $this->db->get();
$result = ($query->num_rows() > 0)?$query->result_array():false;
}
}
//return fetched data
return $result;
}
/*
* Insert user data
*/
public function insert($data){
//add created and modified date if not exists
if(!array_key_exists("created", $data)){
$data['created'] = date("Y-m-d H:i:s");
}
if(!array_key_exists("modified", $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
//insert user data to users table
$insert = $this->db->insert($this->userTbl, $data);
//return the status
return $insert?$this->db->insert_id():false;
}
/*
* Update user data
*/
public function update($data, $id){
//add modified date if not exists
if(!array_key_exists('modified', $data)){
$data['modified'] = date("Y-m-d H:i:s");
}
//update user data in users table
$update = $this->db->update($this->userTbl, $data, array('id'=>$id));
//return the status
return $update?true:false;
}
/*
* Delete user data
*/
public function delete($id){
//update user from users table
$delete = $this->db->delete('users',array('id'=>$id));
//return the status
return $delete?true:false;
}
}
It’s always better to make a separate folder for API related controller. In this example, we will place the API controller in controllers/api/
folder.
The Authentication API controller handles the API requests. It allows to implement a RESTful interface for the user login and registration through the GET, POST, and PUT request.
getRows()
method of the User model.insert()
method of the User model.getRows()
method of the User model.<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
// Load the Rest Controller library
require APPPATH . '/libraries/REST_Controller.php';
class Authentication extends REST_Controller {
public function __construct() {
parent::__construct();
// Load the user model
$this->load->model('user');
}
public function login_post() {
// Get the post data
$email = $this->post('email');
$password = $this->post('password');
// Validate the post data
if(!empty($email) && !empty($password)){
// Check if any user exists with the given credentials
$con['returnType'] = 'single';
$con['conditions'] = array(
'email' => $email,
'password' => md5($password),
'status' => 1
);
$user = $this->user->getRows($con);
if($user){
// Set the response and exit
$this->response([
'status' => TRUE,
'message' => 'User login successful.',
'data' => $user
], REST_Controller::HTTP_OK);
}else{
// Set the response and exit
//BAD_REQUEST (400) being the HTTP response code
$this->response("Wrong email or password.", REST_Controller::HTTP_BAD_REQUEST);
}
}else{
// Set the response and exit
$this->response("Provide email and password.", REST_Controller::HTTP_BAD_REQUEST);
}
}
public function registration_post() {
// Get the post data
$first_name = strip_tags($this->post('first_name'));
$last_name = strip_tags($this->post('last_name'));
$email = strip_tags($this->post('email'));
$password = $this->post('password');
$phone = strip_tags($this->post('phone'));
// Validate the post data
if(!empty($first_name) && !empty($last_name) && !empty($email) && !empty($password)){
// Check if the given email already exists
$con['returnType'] = 'count';
$con['conditions'] = array(
'email' => $email,
);
$userCount = $this->user->getRows($con);
if($userCount > 0){
// Set the response and exit
$this->response("The given email already exists.", REST_Controller::HTTP_BAD_REQUEST);
}else{
// Insert user data
$userData = array(
'first_name' => $first_name,
'last_name' => $last_name,
'email' => $email,
'password' => md5($password),
'phone' => $phone
);
$insert = $this->user->insert($userData);
// Check if the user data is inserted
if($insert){
// Set the response and exit
$this->response([
'status' => TRUE,
'message' => 'The user has been added successfully.',
'data' => $insert
], REST_Controller::HTTP_OK);
}else{
// Set the response and exit
$this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
}
}
}else{
// Set the response and exit
$this->response("Provide complete user info to add.", REST_Controller::HTTP_BAD_REQUEST);
}
}
public function user_get($id = 0) {
// Returns all the users data if the id not specified,
// Otherwise, a single user will be returned.
$con = $id?array('id' => $id):'';
$users = $this->user->getRows($con);
// Check if the user data exists
if(!empty($users)){
// Set the response and exit
//OK (200) being the HTTP response code
$this->response($users, REST_Controller::HTTP_OK);
}else{
// Set the response and exit
//NOT_FOUND (404) being the HTTP response code
$this->response([
'status' => FALSE,
'message' => 'No user was found.'
], REST_Controller::HTTP_NOT_FOUND);
}
}
public function user_put() {
$id = $this->put('id');
// Get the post data
$first_name = strip_tags($this->put('first_name'));
$last_name = strip_tags($this->put('last_name'));
$email = strip_tags($this->put('email'));
$password = $this->put('password');
$phone = strip_tags($this->put('phone'));
// Validate the post data
if(!empty($id) && (!empty($first_name) || !empty($last_name) || !empty($email) || !empty($password) || !empty($phone))){
// Update user's account data
$userData = array();
if(!empty($first_name)){
$userData['first_name'] = $first_name;
}
if(!empty($last_name)){
$userData['last_name'] = $last_name;
}
if(!empty($email)){
$userData['email'] = $email;
}
if(!empty($password)){
$userData['password'] = md5($password);
}
if(!empty($phone)){
$userData['phone'] = $phone;
}
$update = $this->user->update($userData, $id);
// Check if the user data is updated
if($update){
// Set the response and exit
$this->response([
'status' => TRUE,
'message' => 'The user info has been updated successfully.'
], REST_Controller::HTTP_OK);
}else{
// Set the response and exit
$this->response("Some problems occurred, please try again.", REST_Controller::HTTP_BAD_REQUEST);
}
}else{
// Set the response and exit
$this->response("Provide at least one user info to update.", REST_Controller::HTTP_BAD_REQUEST);
}
}
}
routes.php
Specify the routes for REST API requests (login, registration, view, and update).
$route['api/authentication/login'] = 'api/authentication/login';
$route['api/authentication/registration'] = 'api/authentication/registration';
$route['api/authentication/user/(:num)(\.)([a-zA-Z0-9_-]+)(.*)'] = 'api/authentication/user/id/$1/format/$3$4';
You can interact and use the CodeIgniter REST API methods to integrate the user login system in the different applications. The cURL allows you to make HTTP requests in PHP. We will use PHP cURL to interact with CodeIgniter REST API, and perform the GET, POST, and PUT requests. The following examples uses HTTP Basic authentication with API key to connect to the RESTful API.
User Registration via REST API:
The following code performs a POST request to insert the user data for registration (signup) via CodeIgniter REST API.
// API key
$apiKey = 'CODEX@123';
// API auth credentials
$apiUser = "admin";
$apiPass = "1234";
// API URL
$url = 'http://example.com/codeigniter/api/authentication/registration/';
// User account info
$userData = array(
'first_name' => 'John',
'last_name' => 'Doe',
'email' => 'john@example.com',
'password' => 'login_pass',
'phone' => '123-456-7890'
);
// Create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey));
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $userData);
$result = curl_exec($ch);
// Close cURL resource
curl_close($ch);
User Login via REST API:
The following code performs a POST request to validate the credential for login (sign in) via CodeIgniter REST API.
// API key
$apiKey = 'CODEX@123';
// API auth credentials
$apiUser = "admin";
$apiPass = "1234";
// API URL
$url = 'http://example.com/codeigniter/api/authentication/login/';
// User account login info
$userData = array(
'email' => 'john@example.com',
'password' => 'login_pass'
);
// Create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey));
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $userData);
$result = curl_exec($ch);
// Close cURL resource
curl_close($ch);
Retrieve User Account Data via REST API:
The following code performs a GET request to retrieve the user’s account data via CodeIgniter REST API.
// API key
$apiKey = 'CODEX@123';
// API auth credentials
$apiUser = "admin";
$apiPass = "1234";
// Specify the ID of the user
$userID = 1;
// API URL
$url = 'http://example.com/codeigniter/api/authentication/user/'.$userID;
// Create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-API-KEY: " . $apiKey));
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
$result = curl_exec($ch);
// Close cURL resource
curl_close($ch);
Update User Account via REST API:
The following code performs a PUT request to update the user data via CodeIgniter REST API.
// API key
$apiKey = 'CODEX@123';
// API auth credentials
$apiUser = "admin";
$apiPass = "1234";
// Specify the ID of the user
$userID = 1;
// API URL
$url = 'http://example.com/codeigniter/api/authentication/user/';
// User account info
$userData = array(
'id' => 1,
'first_name' => 'John2',
'last_name' => 'Doe2',
'email' => 'john2@example.com',
'password' => 'user_new_pass',
'phone' => '545-856-3439'
);
// Create a new cURL resource
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-KEY: '.$apiKey, 'Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_USERPWD, "$apiUser:$apiPass");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($userData));
$result = curl_exec($ch);
// Close cURL resource
curl_close($ch);
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
nice explanation, but delete method is missing. how i can delete records?
It was very useful, but when i change http to https i am not getting any output
Hi how do we upload a image file image1.png using this API ?
Sir, i have trouble, when i post in Hosting, client can’t #Update or #PUT and can’t #Delete, just #POST and #GET
Great tutorial… but may i ask how you implrment thr routes.. what if you expand you API
i want to use jquery/ajax to call the rest api methods. How can i achieve that?
It was very useful
great article!! thanks a lot for helping / guiding us 🙂 i am new to CI and searching to learn by example and found this great site !!
The restful service is really great. I use a lot of restful and thanks for this wonderful article