Skip to content

Codeigniter 13: Building a REST API for User Management with CodeIgniter

Computer pc and laptop with programming code on screens at software development company.

Codeigniter 13: Building a REST API for User Management with CodeIgniter

User management is a fundamental feature in most applications. A REST API for managing users allows you to handle essential operations such as user registration, login, and profile updates. This guide will walk you through building a user management API using CodeIgniter.

 

Step 1: Setting Up the Database
 

Create a users table to store user information:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

 

Step 2: Create a User Model
 

  1. Navigate to the app/Models directory.
  2. Create a file named UserModel.php:
namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model {
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'email', 'password'];
    protected $useTimestamps = true;
}

 

Step 3: Create a Controller for User Management
 

  1. Navigate to the app/Controllers directory.
  2. Create a file named UserController.php:
namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\RESTful\ResourceController;

class UserController extends ResourceController {
    protected $userModel;

    public function __construct() {
        $this->userModel = new UserModel();
    }

    // User Registration
    public function register() {
        $data = $this->request->getPost();
        $data['password'] = password_hash($data['password'], PASSWORD_BCRYPT);

        if (!$this->userModel->insert($data)) {
            return $this->failValidationErrors($this->userModel->errors());
        }

        return $this->respondCreated(['message' => 'User registered successfully']);
    }

    // User Login
    public function login() {
        $data = $this->request->getPost();
        $user = $this->userModel->where('email', $data['email'])->first();

        if (!$user || !password_verify($data['password'], $user['password'])) {
            return $this->failUnauthorized('Invalid email or password');
        }

        return $this->respond(['message' => 'Login successful']);
    }

    // Fetch User Profile
    public function profile($id) {
        $user = $this->userModel->find($id);

        if (!$user) {
            return $this->failNotFound('User not found');
        }

        unset($user['password']); // Remove password from the response
        return $this->respond($user);
    }

    // Update User Profile
    public function updateProfile($id) {
        $data = $this->request->getRawInput();

        if (!$this->userModel->update($id, $data)) {
            return $this->fail('Failed to update profile');
        }

        return $this->respondUpdated(['message' => 'Profile updated successfully']);
    }

    // Delete User
    public function deleteUser($id) {
        if (!$this->userModel->delete($id)) {
            return $this->failNotFound('User not found');
        }

        return $this->respondDeleted(['message' => 'User deleted successfully']);
    }
}

 

Step 4: Define Routes
 

Add the following routes in app/Config/Routes.php:

$routes->group('users', function($routes) {
    $routes->post('register', 'UserController::register');
    $routes->post('login', 'UserController::login');
    $routes->get('profile/(:num)', 'UserController::profile/$1');
    $routes->put('profile/(:num)', 'UserController::updateProfile/$1');
    $routes->delete('(:num)', 'UserController::deleteUser/$1');
});

 

Step 5: Testing the API
 

  1. Register a User:
    • Endpoint: /users/register
    • Method: POST
    • Body:
      {
          "name": "John Doe",
          "email": "john@example.com",
          "password": "password123"
      }
  2. Login:
    • Endpoint: /users/login
    • Method: POST
    • Body:
      {
          "email": "john@example.com",
          "password": "password123"
      }
  3. Fetch Profile:
    • Endpoint: /users/profile/1
    • Method: GET
  4. Update Profile:
    • Endpoint: /users/profile/1
    • Method: PUT
    • Body:
      {
          "name": "John Updated"
      }
  5. Delete User:
    • Endpoint: /users/1
    • Method: DELETE

 

Best Practices for User Management APIs
 

  1. Hash Passwords: Always hash passwords before storing them in the database.
  2. Validate Input: Validate user input to prevent invalid or malicious data.
  3. Secure Endpoints: Protect sensitive endpoints with authentication and authorization mechanisms.
  4. Remove Sensitive Data: Exclude sensitive fields (e.g., passwords) from API responses.

 

Conclusion
 

Building a REST API for user management in CodeIgniter involves creating endpoints for essential operations like registration, login, and profile management. By following the steps in this guide, you can create a secure and efficient user management API. In the next blog, we’ll explore how to consume external APIs with CodeIgniter for data integration.
  
  

  

Recent Posts