Welcome Guest, Not a member yet? Register   Sign In
Codeigniter website and REST api from same models
#1
Brick 

I have a website and I want to also integrate a mobile app. I'm thinking about adding another set on controllers to the website that will respond with JSON (based on https://github.com/chriskacerguis/codeig...restserver ) so I can reuse the models and hopefully sending JSON data straight from the controllers would be faster that sending data from a view that converts to JSON. Let's consider the GET case for now.

Does anyone have experience doing something like this in CodeIgniter.


Thanks,
Reply
#2

Absolutely, I have used the same REST server library for a lot of different projects.

I usually create a folder in the controllers folder that host all the controllers for the REST server (API) that I build.
Reply
#3

you can use a library but this is so incredibly simple with codeigniter
so here is a sample method, its getting an order based on an id and then sending it as JSON  


PHP Code:
// load your model in this case getorders
// validate the $id 
// then call something like:

function jsonOneOrder($id) {


 
       
       
if ( ! $orderdetail $this->getorders->getOne$id ) ) {

 
             // if the order does not come back go to error page
 
             $this->error_msg .= 'Error getting orders' ;
 
              $this->_showError() ; }

     // we have $orderdetail output as JSON 
 
   $this->output
    
->set_content_type('application/json')
    ->set_output(json_encode($orderdetail));

  

the other very cool thing -- $orderdetail can be an array returned from the model  -- but it also can be an object returned by the model.

so then for the receiving server -- decode JSON -- and you can use $orderdetail->name, $orderdetail->id, etc etc
Reply
#4

(03-11-2015, 01:11 PM)cartalot Wrote: you can use a library but this is so incredibly simple with codeigniter
so here is a sample method, its getting an order based on an id and then sending it as JSON

I agree with you that you don't really need a library to develop a basic RESTful API with CI. But the library, just like CI, has some functions that speed up development.

Here is a few
  • Can format your response array/object to JSON or XML
  • Has a simple and good "response" function that sets correct headers, HTTP status and such
  • Include rate limitations based on IP or key
  • Include support for whitelist/blacklist of IPs
But in the end, it is all up to your own preferences and liking.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB