I'm trying to create a simple REST server using CI 4 based on this article. this is my code:
app/Controllers/Barang.php
<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\Model_Barang;
class Barang extends ResourceController
{
use ResponseTrait;
// get multiple data
public function index()
{
$apiModel = new Model_Barang();
$data = $apiModel->orderBy('id', 'ASC')->findAll();
return $this->respond($data);
}
// get single data
public function getBarang($id = null)
{
$apiModel = new Model_Barang();
$data = $apiModel->where('id', $id)->first();
if($data){
return $this->respond($data);
}else{
return $this->failNotFound('Barang tidak ditemukan.');
}
}
// the other functions for create, update, delete
}
app/Models/Model_Barang.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class Model_Barang extends Model
{
protected $table = 'barang';
protected $primaryKey = 'id';
protected $allowedFields = [
'nama',
'harga',
'jumlah',
'kode_supplier'
];
}
when I test it using Postman with method GET on this URL http://localhost:8080/barang/
it works fine (it shows all the data in the barang
table), but when I use http://localhost:8080/barang/1
it suddenly returns an error saying
{
"status": 501,
"error": 501,
"messages": {
"error": "\"show\" action not implemented."
}
}
I know that according to the code, I should use http://localhost:8080/barang/getBarang/1
instead, and when I tried using getBarang/
it DID work.. but isn't that not RESTful? also, the article said that I can use the url without getBarang/
to get a specific data.. am I doing something wrong? or is this just a CI4's cons?