Strategy for API using Codeigniter REST!


What was needed?

An existing codeigniter application needed to be fixed, and API endpoints needed to be created for a mobile application.

 

How we tackled it?

We implemented REST CodeIgniter API using the RESTful library by CHRIS.  The controllers worked flawlessly out of the box but there was also a requirement for a standalone controller to take care of certain data-exchange, and REST was not an option.

A controller was coded to accept the post data, process it and returned the desired result in JSON format.

All tests using postman and via jQuery.ajax turned out successful until tests were done from the mobile application itself.

Apparently, the mobile application was not sending form-data or x-www-form-urlencoded data. The application was sending JSON data with application/json header which PHP was unable to read using the $_POST or $this->input->post() class of CodeIgniter.

 

After some reading and testing, here is what we changed and thus needs to be kept in mind
  1. Since the data sent via mobile application or from your project in concern may vary, you need to make sure you are coding and testing per your requirements
  2. In our case, the data was being sent from a React Native application and as a json string with application/json content type header. The data was thus not being read by the PHP into the $_POST global variables.
  3. So instead of testing as form-encoded or x-www-form-urlencoded, we started testing  using raw application/json type data
  4. In CodeIgniter, you need to make sure your code is fetching the data from the correct input stream, if the data is being sent as application/json string, then you can access it using CodeIgniter input class, else if the data is form-encoded POST data, then you can access it using CodeIgniter’s $_POST equivalent, $this->input->post(key);
  5. In our case, we used the input class to fetch the raw input stream using $this->input->raw_input_stream, and then json_decoded it into a JSON object.
    $instream = $this->input->raw_input_stream;
    $instream = json_decode($instream);
  6. For this to work, the post data had to be sent as a json-stringified object

And then everything fell into place and started working beautifully, and they lived happily ever after.

Read more PHP related knowledgebase articles here

Screenshots –

, ,