Rectangle 27 1

I would suggest modelling this as a collections property of the contact, to which you POST IDs. i.e.

GET /collections/{id}
GET /contacts/{id}/collections
POST /contacts/{id}/collections
POST
LINK
UNLINK
LINK /contacts/{id}
Link: </collections/{id}>;rel="collection"
collection

Nicholas, are you suggesting to pass in ID's as part of the POST data (such as name: 'collection_id' or 'collection_ids') and then let the contact_model figure out what to do with them?

Yes, I am. POST, when not being abused for everything else, was designed to 'post' new items onto the end of a list. /contacts/{id}/collections is that list, and if that resource can accept POST requests, you should not need any PUT request with both IDs in the URL. If the collection is already in the list, you can either pretend adding it succeeded, or return a 4xx error if the user is supposed to know what's in the list already.

I have just found another SO question which discusses many-to-many relationships in REST, although it doesn't cover the CodeIgniter aspect of your question. The answers there are more eloquent than mine. Basically, the accepted answer says what I was trying to convey, although the highest voted answer differs in structure and has a lot of merit too.

php - Codeigniter REST API many to many Relationships? - Stack Overflo...

php codeigniter rest model
Rectangle 27 1

So I'm just a messenger, as Chris, already point out the problem is in REST_Controller.php, just add

$this->output->_display();
      exit;

On line 828 of REST_Controller.php, the problem is with the last release of codeigniter 3, and the last release of chriskacerguis/codeigniter-restserver.

I've been fighting with this all day.I just test Chris solution and everything seems to be working fine.

php - Codeigniter REST API Keys not working - Stack Overflow

php rest codeigniter postman api-key
Rectangle 27 1

So I'm just a messenger, as Chris, already point out the problem is in REST_Controller.php, just add

$this->output->_display();
      exit;

On line 828 of REST_Controller.php, the problem is with the last release of codeigniter 3, and the last release of chriskacerguis/codeigniter-restserver.

I've been fighting with this all day.I just test Chris solution and everything seems to be working fine.

php - Codeigniter REST API Keys not working - Stack Overflow

php rest codeigniter postman api-key
Rectangle 27 1

According to CodeIgniter Rest Server doc, you can access request parameter as below :

$this->get('blah'); // GET param 
$this->post('blah'); // POST param 
$this->put('blah'); // PUT param
class Api extends REST_Controller {

    public function user_get() {
        echo $this->get('id');
    }

    public function user_post() {
       echo $this->post('id');
    }
}

When you test with postman, you can request as below :

http://localhost/proj/api/user?id=3
http://localhost/proj/api/user/id/3
http://localhost/proj/api/user
form-data : [id : 2]

Alright, but I learnt online that accessing the resource should be done with /users/(:id),,, it makes no sense to me that this isn't possible with the REST api, as it IS possible with the vanilla codeigniter. Isn't there some way I can define a route or something?

@maor10 The problem is method name in your controller. When you use index_get as your method name, the library assume the url as http://localhost/proj/index.php/users/index. That's why when you call http://localhost/proj/index.php/users/ with GET method, index_get is triggered automatically. So, try to change class name and method name to get more meaningful url. I've updated my answer. Please check it again !

php - Codeigniter REST API giving unknown method? - Stack Overflow

php codeigniter rest
Rectangle 27 3

The official, production version does not. Not a single word on that in docs. But...

This feature is implemented in the development branch. It was merged from this pull request. Here's a part of the development version of documentation refering to that feature:

Using HTTP Verb in Routes

If you prefer you can use HTTP Verb (or method) to define your routing rules. This is particularly useful when building RESTful application. You can use standard HTTP Verb (GET, PUT, POST, DELETE) or custom HTTP Verb (e.g: PURGE). HTTP Verb rule is case insensitive. All you need to do is add array index using HTTP Verb rule. Example:

$route['products']['put'] = 'product/insert';

In the above example, a PUT request to URI "products" would call the "product" controller class and "insert" method.

$route['products/(:num)']['DELETE'] = 'product/delete/$1';

A DELETE request to URL with "products" as first segment and a number in the second will be remapped to the "product" class and "delete" method passing in the match as a variable to the method.

$route['products/([a-z]+)/(\d+)']['get'] = 'product/$1/$2';

A GET request to a URI similar to products/shirts/123 would call the "product" controller class and "shirt" method with number as method parameter.

Using HTTP Verb is optional, so if you want any HTTP Verb to be handled in one rule You could just write your routing rule without HTTP Verb. Example:

$route['product'] = 'product';

This way, all incoming request using any HTTP method containing the word "product" in the first segment will be remapped to "product" class.

system/core/Router.php

Also, the pull request references Pigeon library for handling advanced routing configurations.

@user3148070 It does: "Alternatively, download and drag the Pigeon.php file into your application/libraries folder. Autoload the library and away you go."

Actually, the develop branch currently supports http_verb routing

php - codeigniter 2.1.4 support for http methods custom routings? - St...

php api codeigniter rest codeigniter-2
Rectangle 27 2

A route rule as below should help:

$route['v1/(:any)/(:any)'] = 'api/v1/$1/$2';
$route['v(:num)/(:any)/(:any)'] = 'api/v$1/$2/$3';

php - Rewrite rule to simplify codeigniter url for REST api - Stack Ov...

php .htaccess api codeigniter rest
Rectangle 27 2

Frameworks like codeigniter and Restfull "backends" are not mutually exclusive. You could in fact write a RESTful API that takes advantage of CI.

CI's typical UI structure is segmented as follows...

example.com/class/function/ID

There is no reason why you can't use this std structure to implement a RESTful API. Though using CI is probably overkill.

(Check out the README on this site. Has some great examples plus a tutorial that might help you understand how to move forward)

As far as communicating with an Android application using a RESTful API is a great option since it means your application doesn't need to be aware of the servers underlying technology and therefore you gain some flexibility in how you manage your system/code.

Alternatively you could look into using other protocols such as Sockets. There are numerous options for implementing Sockets for different languages and frameworks.

If you take this approach I would suggest ditching PHP.

Thank you for the answer. "You could in fact write a RESTful API that takes advantage of CI." So, how can I do that? Do I need to use some extra code/concepts or simply taking $_POST / $_GET input/output and printing results in JSON will do?

If your focus is to do it correctly then I would strongly suggest you read up on what RESTful APIs are. A simple JSON return from POST/GET does not necessarily qualify. In my answer I linked to a Great CI REST class which can get you started.

Will ditching PHP work? Basically I want to communicate with server. I know PHP that's why I am talking about PHP here.

Understood. The ditching PHP part was meant for if you decided to implement Socket based communication. PHP in that specific case doesn't have the greatest support. Something like Node.js would be better

Does implementation of socket not require backend programming?

REST API for Android, PHP and MySQL - Stack Overflow

php android mysql json rest
Rectangle 27 46

I'll be writing about Kohana 3.1 and main advantages I've seen over CodeIgniter 2 so far. Before Kohana 3.0 (year and a half ago), I used CodeIgniter, ZF, Symfony, Cake and tried many others (at the moment trying to do Yii only because I have to). I'm aware that many will spit on me for "being subjective". Go ahead.

Kohana doesn't use any of the old code (meaning 2.x or CodeIgniter's) in the current version. It was totally rewritten to be fully object oriented and not to get in developer's way. Simply put, it feels natural to develop with it, like it's "the way" for PHP development.

This is a framework built "by the community, for the community", not for promotional purposes. And not by / for any community but a very leet one.

CodeIgniter stood still for way too long hanging on PHP4. Looking at the CI2s' source, I can't say they've fully moved on to PHP5 (let's say PHP 5.1 isn't really ... PHP 5). I've seen FuelPHP, which seems to be more like a mashup of CI2 with Kohana than a CI2 branch, though I have to say it definitely has potential.

The main reason for Kohana to feel natural was born out of this pattern. The idea was to isolate every request to respect the pattern and it ended up with respecting the RFC 2616. Now you have a separate Response object for each Request, being able to reuse your code in a really neat way. Right now I'm working on a web service which is used with iPhone, Android and the web app. I can't describe what a privilege it is to call the API "on the inside". Raw example:

public function action_delete()
{
    $deleted = Request::factory('api/route')
        ->method(Request::DELETE)
        ->headers('Accept', 'text/html')
        ->execute();

    $this->response->body($deleted);
}

The team behind Kohana is dedicated to making the framework "the best it can be", not "everything it can be, because we .. have too much spare time". Each maintenance version is backward compatible with previous ones (e.g. 3.1.2 with 3.1.0), having all "major" changes wait for the minor versions (e.g. 3.1 isn't fully backward compatible with 3.0 "out of the box"). Previous minor versions are maintained for 6 months after the new one is released.

Kohana's Cascading File System makes it extremely easy to extend existing components, or even the ones used by vendors. You can override everything on application / module level, without thinking about setting include / load paths manually anywhere (because all files and folders respect the same convention).

There is a whole bunch of modules, including Zend Framework. How's that? Simply put, you can even use ZF or any other library as a module inside of your Kohana app.

Besides all the community built modules, every Kohana installation includes a few which almost every application can benefit from:

public function action_update($post_id)
{
    $post   = ORM::factory('post', $post_id);
    $errors = array();

    if ($values = $this->request->post())
    {
        try
        {
            $post->values($values)->update();

            $this->request->redirect('post');
        }
        catch (ORM_Validation_Exception $e)
        {
            $errors += $e->errors();
        }
    }

    $this->template->content = View::factory('post/update', array(
        'post'  => $post,
        'errors'=> $errors,
    ));
}

In this example ORM is used to update a row, having update() call it's check() method to validate it's values. In case that validation fails, ORM_Validation_Exception is caught and the rest of try block isn't executed (i.e. redirection to /post). In the end, both the post object (Model_Post) and errors array are passed to View where they can be accessed directly.

Notice that all Database_Query_Builder methods are available inside of ORM, so you can also do 'fancy' stuff like:

ORM::factory('post')
    ->where('user_id','=',$user_id)
    ->join('users','INNER')
    ->on('users.id','=','posts.user_id')
    ->find_all();
$user = ORM::factory('user', $id);

foreach ($user->posts->find_all() as $post)
{
    foreach ($post->quotes->find_all() as $quote)
    {
        if ($quote->illegal())
        {
            $quote->delete();
        }
    }
}

Where illegal() can be some custom model-level method with fancy joins and stuff. I'm aware how inefficient this chunk looks like, it's just a code example, not "are JOINs better than additional queries" :)

+1 overall. I'm not familiar with Kohana and found this quite useful. Just a quick note though, typically versions are major.minor.maintenance. You appear to be referring to maintenance versions are backwards compatible and minor versions are not guaranteed to be. A major version change would be from 2.3 to 3, for example.

@coreyward: thanks, I referred to minor ones as "major" and maintenance ones as "minor" because most of the community refers to them that way. This is the second "major major version" I'm talking about anyways :)

Great answer :). Its a bit worry that every major release breaks the previous versions.. Can you give some details on how things like the controllers, models, views work differently than CI, and perhaps also how form validation and DB access/queries are done?

@Click Upvote: I updated the post with a few small code examples

php - How is Kohana different from CodeIgniter? - Stack Overflow

php codeigniter kohana kohana-3 codeigniter-2
Rectangle 27 2

The error message being generated by PHP, as far as I know, there's nothing you can do about this (other than using the @ operator, which I do NOT recommend). So, your only option is to manually check file_get_content()'s return value:

$response = file_get_contents('http://...');

if ($response === false) {
    // return whatever you feel is appropriate
} else {
    $user = json_decode($response);
    echo $user;
}

I see, this would be fine if I were only using the api myself but the chances are it will be passed on to other developers to integrate with their own applications therefore I would prefer to return something more specific to the problem. I am able to return a message providing I do not return the http response code along with it, would you think it more suitable to do it this way or is an http response code necessary

thanks for the update. That makes more sense now, suppose I'll just have to include something like that in any documentation I provide to other users of the api. Thanks for your help.

response !== false

Codeigniter API error returning - Stack Overflow

api codeigniter rest php
Rectangle 27 1

yes you can give custom routing in codeigniter but you have to put this routing in route.php e.g here admin is my folder name and login is controller in admin folder

$route['admin'] = "admin/login";
http://sonedomain/CI/project/admin

Thanks for your input, but as stated your answer does not solve the problem of a HTTP REQUEST type calling reroute

Thanks but your link is discussing about HTTPand HTTPS. My question is relating more to the GET , POST , PUT , DELETE kind of http request

php - codeigniter 2.1.4 support for http methods custom routings? - St...

php api codeigniter rest codeigniter-2
Rectangle 27 3

I think your problem is the name of controller is the same with the name of method try to make a test:

if the name of your controller is:

class Test extends REST_Controller{
    //your method name is different from the name of controller class
    public function testget_get(){ 
        echo $this->response(array('test'=> 'test'), 200);
    }
}

php - philsturgeon’s REST Api codeigniter Always returning: status:0, ...

php codeigniter rest codeigniter-restserver
Rectangle 27 2

You also need to check that from device which method your are getting means they are sending 'POST' or 'GET' so you can update your function name accordingly.

In my case I have done the function name as _get to the methods but from device methods of sending parameter is 'POST' which I am trying to access as 'GET'.

So please cross check this once. :) Hope this help anyone.

php - philsturgeon’s REST Api codeigniter Always returning: status:0, ...

php codeigniter rest codeigniter-restserver
Rectangle 27 0

"philsturgeon Phil Sturgeon Why do people ask questions about my code on StackOverflow and random forums instead of just asking me?"

thx. In my defense I will say that I did spent time trying to find solutions. i.e in the inconclusive codeigniter.com/forums/viewthread/159098/#766632 in which Phil participates himself. Which lead me to believe that perhaps a thread in a another place might been a good idea.

Heh, thanks whoever that was. You already have more reputation than plenty of other members ;) That thread died off as using Digest for advanced api protection gets to be an arse. Using keys is much more manageable.

method specific authentication in Phil Sturgeons php codeigniter rest ...

php api authentication rest codeigniter
Rectangle 27 0

file_get_contents($your_url)

Additionally you can use php curl wrapper for finer control over your request. http://php.net/manual/en/book.curl.php

php - Codeigniter / MVC way of calling a rest api - Stack Overflow

php api codeigniter rest
Rectangle 27 0

I believe the db class is at $this->db. Have you tried that?

EDIT: ah it seems that $this->rest->db is also an alias for $this->db.

php - Authenticate Against Database with Phil Sturgeon’s Rest-Server -...

php api authentication codeigniter rest
Rectangle 27 0

I think your problem is the name of controller is the same with the name of method try to make a test:

if the name of your controller is:

class Test extends REST_Controller{
    //your method name is different from the name of controller class
    public function testget_get(){ 
        echo $this->response(array('test'=> 'test'), 200);
    }
}

php - philsturgeon’s REST Api codeigniter Always returning: status:0, ...

php codeigniter rest codeigniter-restserver
Rectangle 27 0

Great suggestion, senthilbp. But I think much better to have only one record per API request, with your code for each request will be created 2 records with all the same fields except 'response'. So there is my option. The good practice is not change original source code but use the beauty of OOP and inherit own class

abstract class MY_REST_Controller extends REST_Controller
{
    /**
     * PK from $config['rest_logs_table'] table for last inserted log.
     *
     * @var integer|null
     */
    protected $_log_id;

    /**
     * Log request
     *
     * Record the entry for awesomeness purposes
     *
     * @param boolean $authorized
     * @return object
     */
    protected function _log_request($authorized = FALSE)
    {
        $res = $this->rest->db->insert(config_item('rest_logs_table'), array(
                    'uri' => $this->uri->uri_string(),
                    'method' => $this->request->method,
                    'params' => $this->_args ? (config_item('rest_logs_json_params') ? json_encode($this->_args) : serialize($this->_args)) : null,
                    'api_key' => isset($this->rest->key) ? $this->rest->key : '',
                    'ip_address' => $this->input->ip_address(),
                    'time' => function_exists('now') ? now() : time(),
                    'authorized' => $authorized
                ));
        $this->_log_id = $this->db->insert_id();
        return $res;
    }

    /**
     * Log request response, update existing record, created by @see _log_request()
     *
     * @param string $response
     * @return object
     */
    protected function _log_response($response="")
    {
        if(!$this->_log_id)
        {
            return;
        }
        $log_data['response'] = $response;
        $this->rest->db->where('id', $this->_log_id);
        $this->rest->db->where('response', NULL);// to prevent overwriting
        return $this->rest->db->update(config_item('rest_logs_table'), $log_data);
    }

    /**
     * Response
     *
     * Takes pure data and optionally a status code, then creates the response.
     *
     * @param array $data
     * @param null|int $http_code
     */
    public function response($data = array(), $http_code = null)
    {
        global $CFG;

        // If data is empty and not code provide, error and bail
        if (empty($data) && $http_code === null)
        {
            $http_code = 404;

            // create the output variable here in the case of $this->response(array());
            $output = NULL;
        }

        // If data is empty but http code provided, keep the output empty
        else if (empty($data) && is_numeric($http_code))
        {
            $output = NULL;
        }

        // Otherwise (if no data but 200 provided) or some data, carry on camping!
        else
        {
            // Is compression requested?
            if ($CFG->item('compress_output') === TRUE && $this->_zlib_oc == FALSE)
            {
                if (extension_loaded('zlib'))
                {
                    if (isset($_SERVER['HTTP_ACCEPT_ENCODING']) AND strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE)
                    {
                        ob_start('ob_gzhandler');
                    }
                }
            }

            is_numeric($http_code) OR $http_code = 200;

            // If the format method exists, call and return the output in that format
            if (method_exists($this, '_format_'.$this->response->format))
            {
                // Set the correct format header
                header('Content-Type: '.$this->_supported_formats[$this->response->format]);

                $output = $this->{'_format_'.$this->response->format}($data);
            }

            // If the format method exists, call and return the output in that format
            elseif (method_exists($this->format, 'to_'.$this->response->format))
            {
                // Set the correct format header
                header('Content-Type: '.$this->_supported_formats[$this->response->format]);

                $output = $this->format->factory($data)->{'to_'.$this->response->format}();
            }

            // Format not supported, output directly
            else
            {
                $output = $data;
            }
        }

        header('HTTP/1.1: ' . $http_code);
        header('Status: ' . $http_code);

        // If zlib.output_compression is enabled it will compress the output,
        // but it will not modify the content-length header to compensate for
        // the reduction, causing the browser to hang waiting for more data.
        // We'll just skip content-length in those cases.
        if ( ! $this->_zlib_oc && ! $CFG->item('compress_output'))
        {
            header('Content-Length: ' . strlen($output));
        }

        if (config_item('rest_enable_logging'))
        {
            $this->_log_response($output);
        }

        exit($output);
    }    
}

I hope code is enough clear but I will focus on key areas:

  • The method _log_request() modified to store ID of inserted log

php - Codeigniter REST API response log - Stack Overflow

php api codeigniter response
Rectangle 27 0

json data you can't get through post method you have to use like this

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

class user_api extends REST_Controller {

    function user_post() {

       $params = json_decode(file_get_contents('php://input'), TRUE);

        $user = array(
            'id' => null,
            'firstname' => $params['firstname'],
            'lastname' => $params['lastname']
        );

        $result = $this->user_model->insert($user);
        if ($result) {
            $this->response($result, 200); // 200 being the HTTP response code
        } else {
            $this->response(NULL, 404);
        }
    }

}

php - $this->post codeigniter don't work with rest api - Stack Overflo...

php codeigniter rest post
Rectangle 27 0

society is your model function name ..call it by index name http://localhost/api/index.php/index/?date=20/04/2017&s_name=ssr

php - Codeigniter Not allowing to post data in REST API post method vi...

php codeigniter api codeigniter-restserver
Rectangle 27 0

I managed to find out what the issue was! Turns out my server api was fastcgi and so the solution was to change the REST_Controller file. I found this link that works for fast cgi users

php - CodeIgniter REST API Basic Authentication not working - Stack Ov...

php rest codeigniter