2

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.

4

0 回答 0