RESTful APIs in CodeIgniter
β± Estimated reading time: 2 min
RESTful APIs in CodeIgniter (CodeIgniter 4)
CodeIgniter 4 has first-class support for RESTful APIs, making it easy to build APIs using controllers, routing, validation, and proper HTTP responses.
1. What Is a RESTful API?
REST (Representational State Transfer) uses:
-
HTTP methods (GET, POST, PUT, DELETE)
-
Stateless requests
-
JSON responses
-
Proper HTTP status codes
2. API Folder Structure (Recommended)
3. Create a Resource Controller
This creates a controller with REST methods:
-
index() β GET
-
show() β GET /id
-
create() β POST
-
update() β PUT/PATCH
-
delete() β DELETE
4. Example API Controller
5. API Routes
In app/Config/Routes.php:
Endpoints:
6. Create (POST Request)
7. Update (PUT / PATCH)
8. Delete
9. Validation in API
10. API Authentication Options
-
API Keys
-
JWT (JSON Web Tokens)
-
OAuth 2.0
-
CodeIgniter Shield
11. HTTP Status Codes
| Code | Meaning |
|---|---|
| 200 | OK |
| 201 | Created |
| 400 | Bad Request |
| 401 | Unauthorized |
| 404 | Not Found |
| 500 | Server Error |
12. Best Practices
β
Use ResourceController
β
Always return JSON
β
Validate request data
β
Use proper status codes
β Donβt expose sensitive data
Summary
-
CodeIgniter supports REST APIs out of the box
-
Resource controllers simplify CRUD APIs
-
Proper routing, validation & responses
-
Secure APIs using authentication
Register Now
Share this Post
β Back to Tutorials