Codeigniter RESTful API not returning JSON - php

I have this application where I use Codeigniter as backend and Backbone as frontend. Now I use the RESTful API from https://github.com/philsturgeon/codeigniter-restserver. I want to fetch RSS feeds, so I created a RSS-model.php in application->models:
<?php
class Rss_model extends CI_Model
{
var $table_name = 'artist_news';
var $primary_key = 'news_id';
function get_all_rss_feeds()
{
$this->db->select($this->primary_key);
$this->db->from($this->table_name);
return $this->db->get();
}
}
?>
and then in application->controllers I created the folder api in which I created the file rss.php:
<?php
require(APPPATH.'libraries/REST_Controller.php');
class rss extends REST_Controller{
public function get_all_rss_feeds_get()
{
$this->load->database();
$this->load->model('rss_model');
$data = $this->rss_model->get_all_rss_feeds();
if($data) {
$this->response($data, 200);
} else {
$this->response(array('error' => 'Couldn\'t find any news!'), 404);
}
}
}
?>
So far so good, it returns an array of text with a lot of rss-feeds, but NOT in JSON format, which I need for my frontend.
Does anyone know what the issue is here?
Thanks in advance...
[EDIT]
My Backbone Code looks like this:
function (App, Backbone) {
var Rss = App.module();
Rss.View = Backbone.View.extend({
template: 'rss',
initialize: function() {
this.listenTo(this.collection, 'all', this.render)
},
serialize: function() {
return this.collection ? this.collection.toJSON() : [];
}
});
Rss.RssCollection = Backbone.Collection.extend({
url: function() {
return '/myproject/index.php/api/rss/get_all_rss_feeds/';
}
});
return Rss;
}

go to config/rest.php file and find this line :
$config['rest_default_format'] = 'xml';
change it to :
$config['rest_default_format'] = 'json';

I think you missed the result in return in the model please check below
function get_all_rss_feeds()
{
$this->db->select($this->primary_key);
$this->db->from($this->table_name);
return $this->db->get()->result();
}

If you are usign the Phil Sturgeon REST library you need to append the format type in the URL. Example:
http://example.com/books.json
http://example.com/books?format=json
If you want it in another format, let's say XML, you just need to pass the new format in the URI, doesn't need to change anything in your code. Example:
http://example.com/books.xml
http://example.com/books?format=xml
Further reading:
Content-Type Section - https://github.com/philsturgeon/codeigniter-restserver

Related

How to create rest method for get all datas and get data by id in codeigniter?

I want to perform CRUD operations through REST, I am implementing this in codeigniter, The code whatever I pasted here is working, but I have to handle a way to fetch all the datas from the database and also a way to fetch the data by id. Is there any best way to do this?
Backbone.js
(function(){
Backbone.emulateHTTP = true;
//Backbone.emulateJSON = true;
window.App = {
Models: {},
Collections: {},
Views: {},
Router: {}
};
App.Models.Task = Backbone.Model.extend({
defaults: {
title: '',
done: 0
},
urlRoot: 'index.php/taskController/task'
});
})();
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require(APPPATH.'libraries/REST_Controller.php');
class taskController extends REST_Controller {
public function task_get($id){
$this->load->model('Task', 'task');
$data['task'] = $this->task->findbyid($id);
}
public function tasks_get(){
$this->load->model('Task','task');
$data['task'] = $this->task->find();
$this->response($data,200);
}
public function task_put($id)
{
# code...
$this->load->model('Task', 'task');
$data = json_decode(file_get_contents('php://input'), true);
// $data['title'] = $var['title'];
// $data['done'] = $var['done'];
echo var_dump($data);
$data['task'] = $this->task->updatebyid($id,$data);
//$this->response($data,200);
}
public function task_delete($id){
$this->load->model('Task','task');
$data['task'] = $this->task->delete($id);
}
public function task_post(){
$this->load->model('Task','task');
$data = json_decode(file_get_contents('php://input'),true);
return $data['task'] = $this->task->create($data);
}
}
I use /get/id for the items and /list/number_to_show/limit
So add a list_get($number, $limit)
method
if code for a /get/id is no id is passed, Send the entire lot ?
The principle of REST is that the CRUD actions are represented by the HTTP verbs. GET = select, PUT = update, POST = create and DELETE = delete.
You use nouns in your URL to represent your resources (e.g. tasks).
From your CI code it looks like you use always GET and have verbs+nouns in your URLs.
In REST, to get all tasks you would need to do GET http://example.com/tasks. To get one specific task you would need to do GET http://example.com/tasks/1234
Please read http://info.apigee.com/Portals/62317/docs/web%20api.pdf to understand the principle.

Laravel 4 RESTful API data return types

When createing a RESTful API with Laravel 4 and the repositories pattern (MVRC) is it best to declare a function such as
returnData($data, $dataType = 'JSON' ) {
if( $dataType == 'XML' ) {
return SimpleXML($data);
}
else {
return json_encode($data);
}
}
within the BaseController or is it best practice to place this in a helper library class? or maybe somewhere else?
Well, in fact I did something similar in the BaseController in the project I'm working on:
public function smart_response($data, $redirect_to_route = null, $route_params = array())
{
if (Request::ajax())
{
return Response::json($data);
}
else
{
Alert::boolean($data['msg'], $data['success']);
return is_null($redirect_to_route) ? Redirect::back() : Redirect::to_route($redirect_to_route, $route_params);
}
}
I guess you can get my idea.
Maybe you could use a post filter too? But I don't think there is a right or wrong solution for this.

Save multiple images fetched in Cakephp

I am trying to save multiple images on the server. Lets start from the beginning:
//I use this function for testing
function testSave(){
$this->_renderChart(156);
}
//This function takes chart_id as a parameter to render a proper chart.
function _renderChart($chart_id = null){
if(!$chart_id)
return false;
$chartFilterList = $this->getChartFilterListFromId($chart_id);
$this->loadChartFromId($chart_id, $chartFilterList);
$this->layout = 'analytics\chart_one.ctp';
}
The above function's view contains all the necessary scripts to render the chart. This is the part that is translating the rendered chart into base64string and saves it:
//../views/layouts/analytics/chart_one.ctp
<script type="text/javascript">
$(document).ready(function(){
saveChartAsImage('#chart1');
});
</script>
And the above function's body:
function saveChartAsImage(div){
var base64string = $(div).jqplotToImageStr();
$.ajax({
url: 'saveImage',
type: "POST",
dataType: "html",
data:"data=" + base64string
});
}
}
This is not even close to be working. Am I doing something wrong here?
If these functions are controller actions you can use $this->response->body() in controller's afterFilter() callback to get the response content and save it to file. If these are helper functions you can get the content in afterLayout() or afterRender() callbacks of the helper using $this->_View->Blocks->get('content');
I advise creating a behavior, and add the action beforeValidate();
After that make the conditions necessary to invoke the specific actions (listed in your question).
Example:
app/Model/Behavior/ChartBehavior.php
class ChartBehavior extends ModelBehavior {
// if necessary, create a setup action
public function setup(Model $Model, $settings = array()) { }
public function upload(Model $Model) {
// use the $Model->data to see all information from your form
debug($Mode->data);
// now call your functions below to upload
}
public function line_chart($chart_id = null){
//magic...
}
public function bar_chart($chart_id = null){
//magic...
}
public function pie_chart($chart_id = null){
//magic...
}
I hope it helps you.

REST API with CodeIgniter

I am creating a web-service backend for a mobile app I am developing. (I am an experience Obj-C developer, not a web-designer!) Essentially I would like to use Codeigniter and Phil Sturgeon's RESTful API Server https://github.com/philsturgeon/codeigniter-restserver however, I'm having some trouble getting it all setup and working.
I have MySQL database that is setup with data in it. And I need some help writing a CodeIgniter PHP model and controller that returns JSON data of what is inside that database. All of the tutorials and forum post's i have found deal with hardcoded data in the controler, not a MySQL database. I would ideally like to have the URL formatted like this http://api.mysite.com/v1/search?id=1&name=foo&city=bar , I could potentially have 50+ parameters to pass in the url.
Using Phil's code, I have come up with this as my controller:
public function index_get()
{
if (!$this->get('id'))
{
$this->response(NULL, 400);
}
$data = $this->grid_m->get_id($this->get('id'));
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
That only gets me one search term: id?=# .. I need to know how to get multiple search terms
Here is my Codeigniter model:
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
This just returns EVERYTHING in my MySQL database regardless of what id or url term I pass it in the URL.
I'm a big noob when it comes to developing my own custom API so any suggestions on how to fix my controller and database model would be a huge help!
Thanks for the help!
-brian
This is old question but if somebody go here and still need help, try these code:
In your controller:
public function index_get()
{
$where = '';
if ($this->get('id')) // search by id when id passed by
{
$where .= 'id = '.$this->get('id');
}
if ($this->get('name')) // add search by name when name passed by
{
$where .= (empty($where)? '' : ' or ')."name like '%".$this->get('name')."%'";
}
if ($this->get('city')) // add search by city when city passed by
{
$where .= (empty($where)? '' : ' or ')."city like '%".$this->get('city')."%'";
}
// you can add as many as search terms
if ( ! empty($where))
{
$data = $this->grid_m->get_searched($where);
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
else
{
$this->response(NULL, 404);
}
}
In your model, create get_searched function:
class Grid_m extends CI_Model
{
function get_searched($where = NULL)
{
if ( ! is_null($where))
{
$this->db->where($where);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
}
return FALSE;
}
}
User Codeigniter's Active record to build proper query, you can build any type of query using methods of active record, refer following example I have just added one condition in it you can add more conditions as per your need.
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$this->db->select('col1, col2, col3')->where('id', 5);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
}
Please check you query
$query = $this->db->get_where('grid', array('id' => $id));

CodeIgniter returning different request format / content type html|json|xml etc

What is a simple way in CodeIgniter that I can return a specific content type for request URL extension? For example I want to return json if the url is http://example.com/phone/digits/1.json, html if the URL ends in /1 or /1.html, and XML if the URL ends in /1.xml. This will load a view in the format specified. So in the above example (phone/digits/1.json) would return the json version of the digits method. Here is what I've got so far that is NOT correctly working but gives an idea of what I'm going for. It's currently generating a 404 if no arguments are passed (/phone/digits.json)... Any suggestions would be appreciated.
class Phone extends CI_Controller {
public $layout = FALSE;
public function __construct()
{
if (preg_match('/\.(html|json)$/', $ci->uri->uri_string(), $matches))
{
$this->format = ('html' == $matches[1] || !isset($matches[1])) ? '' : '.json.php';
}
}
public function digits()
{
$this->load->view('phone/digits' . $this->format);
}
Updated for clarity,
I didint understand your question well, asuming you want to simplify your url
its solution for this url : http://domain.com/phone/digits.json (xml or html also)
But with few modification , it can be useful also with http://domain.com/phone/digits/n.json (n - id number)
in config/routes.php
$route['phone/digits.(json|html|xml|php)'] = 'Phone/digits/$1';
$route['phone/digits'] = 'Phone/digits';
Controller
class Phone extends CI_Controller {
public $layout = FALSE;
public function __construct()
{
//hmm
}
public function digits($format = '')
{
if($format == '') {
//default view or something else
}
else {
$this->load->view('phone/digits' . $format);
}
}
Parse the url
grab the extension
use a switch condtional and set relevant output
-
switch( $extension ){
case 'json':
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
break;
case 'xml':
$this->output
->set_content_type('application/xml')
->set_output(file_get_contents(some_xml_file.xml));
break;
// etc etc
}

Categories