2

Hello everyone I am working on REST API in Codeigniter but i am surprise in normal codeigniter when we give method name after controller for example(localhost/project_name/controller/user_get) it will get all users from table but while working with REST API in Codeigniter I am getting unknown method error please tell me how to define method name while rest api in form action

below i have written my code

in view page when i want to click button in form it should call method and retrieve all users

<form method="post" action="<?=base_url('index.php/Api/user_get')?>">

    <button>Click Here</button>


</form>

controller code

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

require(APPPATH . '/libraries/REST_Controller.php');

class Api extends REST_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
    }


  public function user_get() {   //this method will get all users from table
            $r = $this->user_model->read();
            $this->response($r);
        }


      public function user_put() { //this method will insert users details 
           $id = $this->uri->segment(3);
            $data = array('name' => $this->input->get('user_name'),
                'pass' => $this->input->get('user_password'),
                'type' => $this->input->get('user_type')
            );
            $r = $this->user_model->update($id, $data);
            $this->response($r);
        }

}

Below code written in model

public function read() {

   $query = $this->db->query("select * from `tbl_user`");

   return $query->result_array();

}

Getting error like this

Anonymous
  • 1,074
  • 3
  • 13
  • 37
  • i'm not sure if you understood the principle here; if you send a form via post you simply have to use `
    ` according to html standards you can't use `put` in a form so you've to rename your method `user_put()` to `user_post()`, if you don't want that you should use a library like jQuery (https://stackoverflow.com/questions/2153917/how-to-send-a-put-delete-request-in-jquery?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa), angular or something similiar...
    – Atural May 24 '18 at 13:35
  • @sintakonte user_get or user_put is just name you cangive any name to the method here what i want to ask is in form action whatever url address is given it should go to that method only but I am getting error unknown method again I am not using rout mostly people use in codeigniter – Anonymous May 25 '18 at 04:53
  • no you don't understand the principle here ... i'll write an answer for clarification – Atural May 25 '18 at 05:45
  • @sintakonte method is working fine without rest api but ineed rest api for my project so in this case observe below method how controller extends actually in all github following this way to work with rest api we have to load from libraries . require(APPPATH . '/libraries/REST_Controller.php'); class Api extends REST_Controller {} – Anonymous May 25 '18 at 05:49
  • @sintakonte please show me how to do this i need it, it's very urgent . – Anonymous May 25 '18 at 05:51
  • dude if you want an answer with quality you've to gv me some time - i posted it now - it should clarify your problem and you should be able to understand what the `REST_Controller` is doing... – Atural May 25 '18 at 06:12
  • @sintakonte ok take your time please give me solution for this problem – Anonymous May 25 '18 at 06:14
  • Hi MSp! What is your controller name here? – Anand Pandey May 25 '18 at 07:29
  • @AnandPandey my controller name is Api but using extends from rest_controller – Anonymous May 25 '18 at 07:33
  • @MSp: Can you extend only to CI_controller and try again? In your custom controller you extend ci_controller or not?Give your REST_controller here? – Anand Pandey May 25 '18 at 07:39

3 Answers3

0

try this :

function users_get()
{
    $users = $this->user_model->get_all();

    if($users)
    {
        $this->response($users, 200);
    }

    else
    {
        $this->response(NULL, 404);
    }
}
Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71
0

The Rest Controller is designed for the purpose of reacting with the different kind of HTTP Methods which means you have only one URL but a lot of varying methods.

the allowed methods by default are get, delete, post, put, options, patch, head. For more clarification take a look here:

Real World Example based on your question:

First of all, everytime you type in an address in your browser and press Enter you make a GET Request.

You don't need the _get suffix in your browser - the rest Controller will take care of. It recognises this and adds in a self acting way the _get suffix to your function which means, you've to type in your browser:

localhost:81/sample_api/index.php/api/user/

The Rest Controller now checks your Type of Request, recognises it as a GET request and tries to call the function user_get.

The same applies to your form, if you build a form with the method POST and an action like <?=base_url('index.php/Api/user')?> the Controller knows its a POST Request and tries to call the function user_post.

So your controller should look like:

defined('BASEPATH') OR exit('No direct script access allowed');

require(APPPATH . '/libraries/REST_Controller.php');

class Api extends REST_Controller 
{

    public function __construct() {
        parent::__construct();
        $this->load->model('user_model');
    }


    public function user_get() {   
        //this method will get all users from table
        $r = $this->user_model->read();
        $this->response($r);
    }


    public function user_post() { //this method will insert users details 
        $id = $this->uri->segment(3);
        $data = array(
            'name' => $this->input->post('user_name'),
            'pass' => $this->input->post('user_password'),
            'type' => $this->input->post('user_type')
        );
        $r = $this->user_model->update($id, $data);
        $this->response($r);
    }

}

and your view

<form method="post" action="<?=base_url('index.php/api/user')?>">
    <button>Click Here</button>
</form>

Update

The Rest_Controller allows you to define the different kind of Request Methods through an field called _method, which means you can use manually set it in your form like the following:

<form method="post" action="<?=base_url('index.php/api/user')?>">
    <input type="hidden" name="_method" value="put" />
    <button>Click Here</button>
</form>

You just have to set the variable enable_emulate_request in your rest config to true.

You can find this information here


All this magic stuff is happening in the _remap method as you can see here.

Atural
  • 5,389
  • 5
  • 18
  • 35
  • instead of error it should show user details from table i have added my model code also I didn't did any wrong . – Anonymous May 25 '18 at 06:19
  • so if i want to update users details i will pass id but in form how can i write put method normally we do like this
    – Anonymous May 25 '18 at 06:28
  • sry dude, but are you even reading what i'm posting ? do you even understand a little bit of them what i wrote here ? you are talking about a rest api but want a simple MVC - why do you even want to use a rest service at the first place ? – Atural May 25 '18 at 06:42
  • yes i have read you the post which have mentioned ,but in postman they have option GET,POST,PUT,DELETE so all operation will work fine in POSTMAN but now coming to form if i want to update or retrieve value of user what should be the action i have to write because my requirement is api that should work everywhere even in app also. – Anonymous May 25 '18 at 06:48
  • i gv you this exact answer in my first comment of your question - use jquery, angular or something like that - the basic form method doesn't support that... for more information you can take a look here https://stackoverflow.com/questions/165779/are-the-put-delete-head-etc-methods-available-in-most-web-browsers?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Atural May 25 '18 at 06:50
  • basic form method will not support REST API? – Anonymous May 25 '18 at 06:53
  • previously you told use jquey or ajax ok i did so many times so i here i want to do simple form action without jquery or ajax – Anonymous May 25 '18 at 06:54
  • basic form method will only partial support the REST API - because the html standard defines the possibility of sending a form only in 2 ways `POST` and `GET`- thats it - you got all the references in my previous comments - btw i'll edit my post, there is another option – Atural May 25 '18 at 06:58
  • thanks for your support and valuable time but l have one more doubt can i use same code for android app ? because concept of api is only a single link can work so many places like in php ,apps – Anonymous May 25 '18 at 07:02
  • of course you can - thats the purpose of an api ;) - btw i've updated my answer - because i found a way how you can manage your forms ... – Atural May 25 '18 at 07:04
  • when i use only user it calling to last method because all methods name are like this user_put(),user_get(),user_delete,user_post() suppose i want to get results so if after controller if you mention only user it will call the method user_post not user_get() – Anonymous May 25 '18 at 07:10
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/171745/discussion-between-sintakonte-and-msp). – Atural May 25 '18 at 07:13
0

You are not add echo and second thing not load helper url it will help you.

  1. If you want to post than you will correct it
  2. If you want to get than you ha

<form method="post" action="<?php echo base_url('index.php/Api/user_put'); ?>">
<form method="get" action="<?php echo base_url('index.php/Api/user_get'); ?>">

ve to call like

Anand Pandey
  • 2,025
  • 3
  • 20
  • 39
  • do you have idea how to create REST api in codeigniter inform me – Anonymous May 25 '18 at 07:52
  • yes i made lots but i separate into different controller and folders – Anand Pandey May 25 '18 at 07:53
  • can you please tell me how to define separate method like get,post,put in
    – Anonymous May 25 '18 at 07:54
  • =?> is short tag use for php which i had mentioned in my question,if you have amy demo or practice project based on Codeigniter rest api the send the link of that project – Anonymous May 26 '18 at 04:17
  • i have created rest api and checked in postman it is working without any issue but i have one form same api i want to use in form action but whenever i do this getting problem because in postman you call metod name only like this user_get then call in postman user and perform get or post but in form if i mention same api with full anme it is not working if use only user it is trying to call other methods – Anonymous May 29 '18 at 05:17
  • @MSp: you should use method="post" or "get" in the form and they work well. – Anand Pandey May 29 '18 at 05:30
  • already had used that but nothing worked ,if you have any demo or source code of project kindly send me – Anonymous May 29 '18 at 06:36
  • @MSp: Here is the link for basic https://selftaughtcoders.com/creating-processing-form-codeigniter/ – Anand Pandey May 29 '18 at 06:54
  • i need api how to define in form with different methods like insert update post not basic way ,because i know that i want to know whatever different api key(post ,put,get ) i have created how to use that in the form . – Anonymous May 29 '18 at 07:14