Your Yummy
Your Yummy

Reputation: 153

cakephp json webservice for beginners

I am beginner in cakephp
my task is to create restfull json web services
I have started from posts table
give my link to basic json webservice I have googled but some are for previous versions some are for xml I am not getting started I have cakephp 2.4 version

currently my controller is

<?php
class PostsController extends AppController {
    public function index() {
        //$posts= $this->Post->find('all');
        $this->set('posts', $this->Post->find('all'));
        //$this->set($posts);
    }
    public function view($id = null)
    {
        if(!$id)
        {
            throw new NotFoundException(__('View Not Found'));
        }
        $posts = $this->Post->findById($id);
        if(!$posts)
        {
            throw new NotFoundException(__('View Not Found'));
        }
        $this->set(compact('posts', 'posts'));
    }

 }

View is

<?php
    echo json_encode(compact('posts', 'posts'));
?>

1- it is showing within default html template, I need pure json 2- it show each record as in Post array, don't need subarray that's it show like this

{"posts":{"Post":{"id":"1","title":"The title","body":"This is the post body.","created":"2014-02-08 00:35:50","modified":null}}} 

while I need

{"posts":[{"id":"1","title":"The title","body":"This is the post body.","created":"2014-02-08 00:35:50","modified":null}},{"id":"2","title":"A title once again","body":"And the post body follows.","created":"2014-02-08 00:35:50","modified":null}]} 

Upvotes: 0

Views: 7049

Answers (2)

ADmad
ADmad

Reputation: 8100

Check out the friendsofcake/crud plugin. It has an Api Transform listener to generate the json format you need.

Upvotes: 1

floriank
floriank

Reputation: 25698

The official documentation describes how to create a RESTful site and it has a section about XML and json views as well.

Try the documentation, there are plenty of code examples as well.

Upvotes: 2

Related Questions