codeigniter: Rest api + Json

前端 未结 1 366
迷失自我
迷失自我 2021-01-26 09:40

How, do I implement code igniter rest API that outputs with ajax outputting the JSON. I\'m unsure how to use the REST API for deleting and adding with the JSON. How to delete a

相关标签:
1条回答
  • 2021-01-26 09:46

    1. Rest API routing

    Let's start with the routing of your API - If you apply best practice to your API you will want to use HTTP verbs (POST/PUT/GET...). (Read more on HTTP Verbs and REST here)

    If you are on Codeigniter 2.x then read this SO question and answer

    If you are on Codeigniter 3.x then read this documentation

    On the other side, if you are planning to use the API only internally and the scope of the project is limited you can just ignore HTTP verbs and simply make POST and GET calls to your controllers.

    2. Creating JSON response

    Generally you will not need to use views - you can have your controllers echo the JSON response. Here is an example of a fictional API that has an API call to get an actor from a database of actors.

    /*   ----------------------------------------------
    |    Example of an API Method to get an actor from
    |    a database of actors:
    |    call: http://example.com/api/GetActorById
    |    parameter: actor_id
    |    Method: POST
    */
    public function GetActorById(){
    
        // Let's first get the actor ID from the POST data
        $actor_id = $this->input->post('actor_id');
    
        // If the API Method would be GET you would get the
        // actor ID over the URI - The API call would look
        // like this: http://example.com/api/GetActorById/<actor_id>
    
        // In that case you take your actor ID from the segment:
        $actor_id = $this->uri->segment(3);
    
    
        // Do your database query magic here!
        // ...
        // ...
    
        // Let's create an array with some data 
        // In real life this usually comes from a DB query above
        $data = array(
                'Firstname' => 'Michael',
                'Lastname' => 'Fox',
                'IsActor' => True,
                'UserId' => 1234567
                );
    
        // Now let's convert the array into a JSON
        $json = json_encode($data);
    
        // if the API is accessed from a different domain
        // you will want to allow cross domain access
        header('Access-Control-Allow-Origin: *'); 
    
        // Now let's return the json
        echo $json;
    }
    

    The output will look like this:

    {"Firstname":"Michael","Lastname":"Fox","IsActor":true,"ActorID":123456789}
    

    Hope this helps - Good luck with your project!

    0 讨论(0)
提交回复
热议问题