Stack Exchange
Codeigniter 4 Rest API Routing Post method not working
I am using Codeigniter 4. Where I am implementing Rest API. In the routes the GET method only works, however Post method is not working.
I am testing this using POSTMAN.
[URL](URL : http://localhost/project/api/users/create)
Please check the code below for reference.
Routes.php
$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home'); 
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override(function()
{
    echo json_encode(array(
        "status"=>false,
        "err_code"=>404,
        "err_message"=>"Route not found"
    ));
});
$routes->setAutoRoute(false);

$routes->get('/', 'Home::index');
$routes->post('api/users/create', 'UserRegister::register');

Controller
app\Controllers\UserRegister.php
namespace App\Controllers;
use CodeIgniter\Controller;
use Config\Email;
use Config\Services;
use App\Models\RegisterModel;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\HTTP\RequestInterface;


class UserRegister extends BaseController
{
use ResponseTrait;
   /**
     * Access to current session.
     *
     * @var \CodeIgniter\Session\Session
     */
    protected $session;

    /**
     * Authentication settings.
     */
    protected $config;


    //--------------------------------------------------------------------

    public function __construct()
    {
        // start session
        $this->session = Services::session();
    }

    //--------------------------------------------------------------------

    /**
     * Displays register form.
     */
    public function register()
    {
        $data =  $this->request->getJSON();
        $method = $this->request->getMethod();

        helper('text');

        // save new user, validation happens in the model
        $users = new RegisterModel();
        
        $rules = [
                'firstname'         => 'required|alpha_space|min_length[2]',
                'lastname'          => 'required|alpha_space|min_length[2]',
                //'name'                => 'required|alpha_space|min_length[2]',
                'mobile'            => 'required|max_length[10]',
                'address'           => 'required',
                'mobile'            => 'required',
                'email'             => 'required|valid_email|is_unique[users.email,id,{id}]',
                'password'          => 'required|min_length[5]',
                'password_confirm'  => 'required|matches[password]'
                ];
        
        if (!$this->validate($rules)) {
            
            return $this->response
                ->setStatusCode(400)->setJSON($this->validator->getErrors());
        } else {
        
        $activate_hash = random_string('alnum', 32);
        
            $user = [
                'firstname'          => $this->request->getVar('firstname'),
                'lastname'          => $this->request->getVar('lastname'),
                'name'              => $this->request->getVar('firstname'),
                'mobile'            => $this->request->getVar('mobile'),
                'user_type'         => 'user',
                'address'           => $this->request->getVar('address'),
                'econtact_name1'    =>$this->request->getVar('econtact_name1'),
                'econtact_number1'  =>$this->request->getVar('econtact_number1'),
                'econtact_name2'    =>$this->request->getVar('econtact_name2'),
                'econtact_number2'  =>$this->request->getVar('econtact_number2'),
                'email'             => $this->request->getVar('email'),
                'password'          => $this->request->getVar('password'),
                'password_confirm'  => $this->request->getVar('password_confirm'),
                'active'            => 1,
                'activate_hash'     => $activate_hash
            ];
    
            if (! $users->save($user)) {
                return $this->response
                ->setStatusCode(401)->setJSON('Error occur while registring.');
            //return redirect()->back()->withInput()->with('errors', $users->errors());
             } else {
             
             $id = $users->insertID;
             
             $user = $users->where('user_type', 'user')->where('id', $id)->first();
             //print_r($user); exit;
             
             $this->session->set('userLoggedIn', true);
             $this->session->set('userinfoData', [
                'id'            => $user["id"],
                'name'          => $user["name"],
                'user_type'     => $user["user_type"],
                'firstname'     => $user["firstname"],
                'lastname'      => $user["lastname"],
                'email'         => $user["email"]
                //'new_email'   => $user["new_email"]
            ]);
        
            return $this->response
                ->setStatusCode(200)->setJSON($this->session->userinfoData);
            }
        
        }

        
    }

    //--------------------------------------------------------------------

    
     
    
}


Any help would be appreciated.
Thank You
It does not find the correct class and method UserRegister::register . It redirects to the default page.

You are POSTing to project/api/users/create, which is not the same as api/users/create. It looks like you do not have your installation configured correctly - your webserver's document root should be the public/ directory; the URL to reach your register method should be localhost/api/users/create. https://codeigniter.com/user_guide/installation/running.html#virtual-hosting, https://codeigniter.com/user_guide/installation/running.html#hosting-with-nginx

Still not working.

@Don'tPanic Can you please help me to sort this issues. Thank you.

What does "still not working" mean?  What did you change?  What is your project's Document Root? "It redirects to the default page" - do you mean a real redirect, with a 300 or 301 http code, or do you just mean the route shows the index page?  Edit your question, add details.  If you've made changes based on my first comment, tell us what and what happened afterwards.
