3

I am using Codeigniter Version 4.1.7. Where I am implementing Rest API. In the routes the GET method works,however Post method is not working.

I am testing this using POSTMAN.

URL : http://localhost/myproject/api/add-user

Following is the header

Accept: application/json

Content-Type: application/json

Authorization: Basic xxxxxxxxxxx=

Please check the code below for reference.

Routes.php

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

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
 */

// We get a performance increase by specifying the default
// route since we don't have to scan directories.
//$routes->get('/', 'Home::index');


$routes->group("api", ["namespace" => "App\Controllers\Api", "filter" => "basicauth"] , function($routes){
    $routes->get("list-users", "ApiController::index");
    $routes->post("add-user", "ApiController::create");
});

ApiController.php

app\Controllers\Api\ApiController.php

<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use App\Models\UsersModel;

class ApiController extends ResourceController
{
    /**
     * Return an array of resource objects, themselves in array format
     *
     * @return mixed
     */
    public function index()
    {
        //
        $users = new UsersModel();

        $response = [
            'status' => 200,
            "error" => false,
            'messages' => 'User list API',
            'data' => $users->findAll()
        ];

        return $this->respondCreated($response);
    }

    /**
     * Create a new resource object, from "posted" parameters
     *
     * @return mixed
     */
    public function create()
    {
        //
        $rules = [
            'first_name' => 'required|min_length[3]|max_length[20]',
            'last_name' => 'required|min_length[3]|max_length[20]',
            'email' => 'required|min_length[6]|max_length[50]|valid_email|is_unique[users.email]',
            'password' => 'required|min_length[8]|max_length[255]',
            'password_confirm' => 'matches[password]',
        ];      
        ...
        ...
        ...
        return $this->respondCreated($response);
    }
}

Any help would be appreciated.

Ruprit
  • 733
  • 1
  • 6
  • 23
  • 1
    What do you mean by the *Post method is not working*? Do you receive any errors? What response do you get? – steven7mwesigwa Jan 30 '22 at 22:18
  • It just does not find the correct class and method `ApiController::create` . It redirects to the default page. – Ruprit Jan 31 '22 at 07:06
  • Try submitting the wrong route(s) and share your findings. I.e: `GET/ http://localhost/myproject/api/bad-route` and `POST/ http://localhost/myproject/api/dummy-route` – steven7mwesigwa Jan 31 '22 at 09:32
  • Can you also share the default route settings normally found at the top of your `app\Config\Routes.php` file? I.e: `$routes->setDefaultController(...);`, `$routes->setDefaultMethod(...);`, etc... – steven7mwesigwa Jan 31 '22 at 09:38
  • 1
    @steven7mwesigwa I had updated routes code above. I had set `$routes->setAutoRoute(false);` auto routes to false as it was redirecting to default page. – Ruprit Jan 31 '22 at 15:43
  • 1
    @steven7mwesigwa Wrong routes/api give `404 error` whereas POST correct routes/api gives `303 error` AND GET Correct route/api works successfully – Ruprit Jan 31 '22 at 15:46
  • Try performing a *dump and die* at the beginning of the controller's `create(...)` method to confirm if the execution reaches that point. – steven7mwesigwa Feb 01 '22 at 13:23
  • In addition, after that, try performing a *dump and die* in your *basicauth* filter to confirm if it exits successfully and if it isn't responsible for the redirection to the default page. – steven7mwesigwa Feb 01 '22 at 13:27
  • Lastly, could you try making the `POST/` request **without** the *basicauth* filter and see what happens? – steven7mwesigwa Feb 01 '22 at 13:31
  • @steven7mwesigwa Thank you so much for your help. `basicauth` filter working perfectly. Execution does not reach `create()` method with ``POST request``, however if I change post to ``GET`` `create()` metods works :( Not sure what is wrong. – Ruprit Feb 02 '22 at 12:26
  • Hmm, interesting! It appears the issue lies elsewhere than what we're looking at. The closest I could think of is probably a global *filter* is responsible for the redirection to the default page. It would be nice if you shared your `app/Config/Filters.php` and `app/Filters/BasicauthFilter.php` files in your question and probably someone else here could pinpoint the culprit. – steven7mwesigwa Feb 03 '22 at 04:13
  • Did you add CSRF to POSTMAN? Because every POST request in CI4 must have it – Ali Sheykhi Oct 23 '22 at 00:03
  • POST => PUT; `$routes->put` – totoprayogo1916 Mar 13 '23 at 16:30

0 Answers0