Сервер CodeIgniter + RESTfull выдает 400 ответов при запросе пользователя

1


Я работаю над учебником. Работа с RESTful Services в CodeIgniter, и у меня проблема с одной строкой кода. В user_get() if(!$this->get('id')) выдает ответ 400, если я пытаюсь получить ресурс http://localhostApp/api/user/1

Что я упускаю?
Я неправильно запрашиваю ресурсы?

Это мой контроллер Api:

    class Api extends REST_Controller
    {
        function user_get(){
            if(!$this->get('id')){ //Problem line
                $this->response(NULL, 400);
            }
            $user = $this->user_model->get( $this->get('id') );
            if($user){
                $this->response($user, 200); // 200 being the HTTP response code
            }else{
                $this->response(NULL, 404);
            }
        }

        function user_post(){
            $result = $this->user_model->update( $this->post('id'), array(
                'name' => $this->post('name'),
                'email' => $this->post('email')
            ));

            if($result === FALSE){
                $this->response(array('status' => 'failed'));
            }else{
                $this->response(array('status' => 'success'));
            }

        }

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

            if($users){
                $this->response($users, 200);
            }else{
                $this->response(NULL, 404);
            }
        }
    }
    ?>

Если вам нужна дополнительная информация, пожалуйста, дайте мне знать.
заранее спасибо

Теги:
codeigniter
rest

2 ответа

2
Лучший ответ

Если вы хотите передать данные user_get(), вы должны определить его в своем URL-адресе.

http://localhostApp/api/user/1

Здесь вы определяете user. но нет никакого идентификатора, переданного для вызова того пользователя

Таким образом, ваш URL должен быть

http://localhostApp/api/user/id/1

Примечание. Не просто копируйте и вставляйте код с этого сайта в свой проект. Измените его так, как вам нужно.

  • 0
    ЗДРАВСТВУЙ! Я пытаюсь этот код просто посмотреть, как он работает, тогда я напишу свой собственный. если я попробую ваш запрос localhostApp / api / user_get / 1, я получу ответ {"status": false, "error": "Unknown method." } насколько я знаю, этот контроллер покоя автоматически знает, что вы вызываете пользовательский ресурс, и сам добавляет GET / POST / .... на основании вашего запроса
  • 0
    В учебном пособии есть пример: $ this-> get () Используется для возврата переменных GET из строки запроса, подобной этому index.php / example_api / user? Id = 1, или может быть задано более методом CodeIgniter'esque с индексом .php / example_api / пользователь / ID / 1.
Показать ещё 6 комментариев
1

Вот как я использовал службу RESTful - используя сервер останова Phil Sturgeon.

Используется POST вместо GET для получения сведений о пользователе

routes.php

$route['api/view/user_details'] = 'api/view/user_details';

Форма для тестирования:

<form class="form-horizontal inline" action="<?php echo base_url(); ?>api/view/user_details" method="post">
        <label for="user_id">Enter User ID</label>
        <input id="user_id" type="text" name="id" value="" />
        <input type="submit" name="submit" value="submit" />
</form>

Метод контроллера для возврата пользовательской информации в JSON

public function user_details_post()
{


    $id = $this->post('id');

    $this->load->model('admin_model');

    $users = $this->admin_model->view_clients();



    // If the id parameter doesn't exist return all the users

    if ($id == NULL)
    {
        // Check if the users data store contains users (in case the database result returns NULL)
        if ($users)
        {
            // Set the response and exit
            $this->response(['all_users'=>$users], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
        }
        else
        {
            // Set the response and exit
            $this->response([
                'status' => FALSE,
                'message' => 'No users were found'
            ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
        }
    }

    // Find and return a single record for a particular user.

    $id = (int) $id;

    // Validate the id.
    if ($id <= 0)
    {
        // Invalid id, set the response and exit.
        $this->response(NULL, REST_Controller::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code
    }

    // Get the user from the array, using the id as key for retreival.
    // Usually a model is to be used for this.

    $user = NULL;

    if (!empty($users))
    {
        foreach ($users['user_details'] as $key => $value)
        {
            if (isset($value['id']) && $value['id'] === $id)
            {
                $user = $value;
            }
        }
    }

    if (!empty($user))
    {
        $this->set_response([
            'user_details'=>$user], REST_Controller::HTTP_OK); // OK (200) being the HTTP response code
    }
    else
    {
        $this->set_response([
            'status' => FALSE,
            'message' => 'User could not be found'
        ], REST_Controller::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code
    }

}

MODEL: возврат массива пользователей со всеми подробностями в контроллер

public function view_clients()
    {

        $result=$this->db->get('clients');

        $results=array();

        foreach ($result->result() as $row)
        {
            $id = $row->id;
            $id = (int) $id;
            $results[] = array(
                'id' => $id,
                'full_name' => $row->full_name,
                'gender' => $row->gender,
                'email' => $row->email,
                'dob' => $row->dob,
                'phone' => $row->phone,
                'address' => $row->address,
                'username' => $row->username,
                'country' => $row->country,
                'city' => $row->city,
                'rec_status' => $row->rec_status,
                'crt_date' => $row->crt_date,
                'email_ver_status' => $row->email_ver_status,
                'mobile_ver_status' => $row->mobile_ver_status,
            );
            $return_array= array("status:" =>'success',
                "user_details" => $results );

        }

        return($return_array);
    }

Ответ я получаю как JSON для запроса POST с идентификатором

{
    "user_details": {
        "id": 1,
        "full_name": "sudheesh sudhakaran",
        "gender": "Male",
        "email": "[email protected]",
        "dob": "12\/03\/1986",
        "phone": "0567462013",
        "address": "kottayil house po kundaliyoor\r\nthrissur",
        "username": "sudheesh",
        "country": "India",
        "city": "KERALA",
        "rec_status": "A",
        "crt_date": "",
        "email_ver_status": null,
        "mobile_ver_status": null
    }
}

Чтобы получить запись всех пользователей, отправьте значение NULL.

Вопросы, заданные при создании этого, здесь

Ещё вопросы

Сообщество Overcoder
Наверх
Меню