Building a RESTful API with CodeIgniter 3
Introduction
Creating a RESTful API may be an vital assignment for modern internet applications, enabling seamless communique between patron and server. CodeIgniter three, a lightweight PHP framework, simplifies this technique. In this manual, we can stroll thru the stairs to build a RESTful API the use of CodeIgniter 3.
Table of Contents
1. **Introduction to RESTful APIs**
2. Setting Up CodeIgniter
3. Creating the API Structure
4. Building API Endpoints
5. Testing the API
6. Conclusion
1. Introduction to RESTful APIs
REST (Representational State Transfer) is an architectural fashion that defines a set of constraints and properties primarily based on HTTP. RESTful APIs use widespread HTTP strategies like GET, POST, PUT, and DELETE to engage with resources. They provide a bendy and scalable manner to permit information change between customers and servers.
2. Setting Up CodeIgniter
To get started with CodeIgniter, follow these steps:
- Download CodeIgniter: Visit the [CodeIgniter website](https://codeigniter.com/) and download the latest version.
- Install Dependencies: Unzip the package and move it to your server’s document root (e.g., `htdocs` for XAMPP).
- Configure the Base URL: Open `application/config/config.php` and set the base URL:
$config['base_url'] = 'http://yourdomain.com/';
Set Up Database Configuration:
Configure your database settings in `application/config/database.php`:
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'your_username',
'password' => 'your_password',
'database' => 'your_database',
'dbdriver' => 'mysqli',
// other configurations...
);
Creating the API Structure
Create a new directory for your API within the `application` folder:
1. Create the Controller:
- Navigate to `application/controllers` and create a file named `Api.php`.
- This file will handle all API requests.
2. Create the Model:
- Go to `application/models` and create a file named `Item_model.php`. This model will interact with the database.
4. Building API Endpoints
Now, let’s create some endpoints in the `Api.php` controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Api extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Item_model');
header("Content-Type: application/json");
}
public function items() {
$items = $this->Item_model->get_all_items();
echo json_encode($items);
}
public function item($id) {
$item = $this->Item_model->get_item($id);
if ($item) {
echo json_encode($item);
} else {
http_response_code(404);
echo json_encode(['message' => 'Item not found']);
}
}
public function create_item() {
$data = json_decode(file_get_contents("php://input"), true);
$this->Item_model->insert_item($data);
echo json_encode(['message' => 'Item created']);
}
public function update_item($id) {
$data = json_decode(file_get_contents("php://input"), true);
$this->Item_model->update_item($id, $data);
echo json_encode(['message' => 'Item updated']);
}
public function delete_item($id) {
$this->Item_model->delete_item($id);
echo json_encode(['message' => 'Item deleted']);
}
}
5. Implementing the Model
In `Item_model.php`, add the following code to handle database operations:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Item_model extends CI_Model {
public function get_all_items() {
return $this->db->get('items')->result();
}
public function get_item($id) {
return $this->db->get_where('items', ['id' => $id])->row();
}
public function insert_item($data) {
$this->db->insert('items', $data);
}
public function update_item($id, $data) {
$this->db->where('id', $id);
$this->db->update('items', $data);
}
public function delete_item($id) {
$this->db->delete('items', ['id' => $id]);
}
}
6. Testing the API
You can test your API using tools like Postman or cURL. Here are some example requests:
- GET All Items: `GET http://yourdomain.com/api/items`
- GET Single Item: `GET http://yourdomain.com/api/item/1`
- Create Item: `POST http://yourdomain.com/api/create_item` with JSON body
- Update Item: `PUT http://yourdomain.com/api/update_item/1` with JSON body
- Delete Item: `DELETE http://yourdomain.com/api/delete_item/1`
Conclusion
You have now created a basic RESTful API using CodeIgniter 3. This API can be further extended with features such as authentication, validation, and error handling. CodeIgniter’s simplicity allows for rapid development, making it an excellent choice for creating APIs. Happy coding!