Search code examples
phpapicodeignitercodeigniter-4

Code Igniter 4 Restful API only default controller, routes not work


I try to create restful api using Code Igniter 4 on Apache2. If I open http://<my-ip:port>, it shows welcome message. Then I created Account.php controller to get account list from database.

<?php namespace App\Controllers;
 
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\AccountModel;
 
class Account extends ResourceController
{
    use ResponseTrait;
    public function index()
    {
        $model = new AccountModel();
        $data = $model->findAll();
        return $this->respond($data, 200);
    }
 
    public function show($id = null)
    {
        $model = new AccountModel();
        $data = $model->getWhere(['account_id' => $id])->getResult();
        if($data){
            return $this->respond($data);
        }else{
            return $this->failNotFound('No Data Found with id '.$id);
        }
    }
}

AccountModel.php

<?php namespace App\Models;
 
use CodeIgniter\Model;
 
class AccountModel extends Model
{
    protected $table = 'account';
    protected $primaryKey = 'id';
    protected $allowedFields = ['account_id','name'];
}

I set Cors and Filters.

and this is my routes

<?php

namespace Config;

$routes = Services::routes();

if (file_exists(SYSTEMPATH . 'Config/Routes.php')) {
    require SYSTEMPATH . 'Config/Routes.php';
}

$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
$routes->setAutoRoute(true);

//$routes->get('/','Home::index');
$routes->resource('account');

if (file_exists(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
    require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}

http://my-ip:port shows welcome message. But if I open http://<my-ip:port/account> using postman I got error

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
<hr>
<address>Apache/2.4.46 (Ubuntu) Server at <my-ip> Port 80</address>
</body></html>

and I set Account as a default controller $routes->setDefaultController('Account'); I got list of account if I open http://<my-ip:port>. Do I miss some set up? I want to get account list if I open http://<my-ip:port/account> and others.


Solution

  • Is it works if tried http://<my-ip:port/index.php/account? if yes, you have to config your apache to hide index.php from URL. visit following link for more infos. => more infos