A complete tutorial on building a REST API with the CodeIgniter 3 framework. From setup to endpoint testing.
Introduction
REST API (Representational State Transfer Application Programming Interface) is the standard approach for communication between applications over HTTP. In this tutorial, we will learn how to build a REST API using the CodeIgniter 3 framework ÔÇö one of the most popular PHP frameworks in Indonesia.
Why CodeIgniter 3?
CodeIgniter 3 is an excellent choice for building REST APIs because:
- Lightweight and fast ÔÇö minimal footprint with maximum performance
- Easy to learn ÔÇö especially for developers already familiar with PHP
- Flexible ÔÇö no rigid structure, giving you freedom in architecture
- Comprehensive documentation ÔÇö clear and well-organized official docs
Project Setup
Follow these steps to set up your CodeIgniter 3 project for REST API development:
- Download CodeIgniter 3 from the official website and extract it to your web server directory
- Configure the database in
application/config/database.php - Set the base URL in
application/config/config.php - Enable query strings if needed for API parameters
Creating an API Controller
Create a new controller that will handle API requests. The controller should output JSON responses instead of HTML views:
class Api extends CI_Controller {
public function users_get() {
$users = $this->db->get('users')->result();
$this->output
->set_content_type('application/json')
->set_output(json_encode(['status' => 'success', 'data' => $users]));
}
}
HTTP Methods
A proper REST API uses different HTTP methods for different operations:
- GET ÔÇö Retrieve data
- POST ÔÇö Create new data
- PUT ÔÇö Update existing data
- DELETE ÔÇö Remove data
Testing the API
Use tools like Postman or cURL to test your API endpoints. Make sure to test all CRUD operations and edge cases like invalid input and authentication.
Conclusion
Building a REST API with CodeIgniter 3 is straightforward and efficient. The key principles are: use proper HTTP methods, always return JSON responses, implement proper error handling, and secure your endpoints with authentication.
Komentar
Belum ada komentar. Jadilah yang pertama!