We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

"MVC" without "V", json response


I often need to make REST API with Phalcon. So the views are not needed to me. But if I set in controller:


I get empty response. So always I need to do one more step:

return $this->response;

Maybe there is some easy fix/hack to not try to render views if json response are set?

Real code example which I want to simplify:


use Phalcon\Http\Response;

class AjaxController extends ControllerBase
    public function insuranceAction()
        $insurance = $this->request->get('insurance');
        $this->session->set('insurance', $insurance === 'true');
        $response = new Response();

            'status' => 'ok',
            'insurance' => $insurance,

        return $response;


    return $this->response->setJsonContent([]);

edited Nov '18

Just use Phalcon Micro for RESTful API's.

Phalcon micro has no file structure. If you need to have a lot of endpoints, then you will have a headache. Thats why I prefer default phalcon file structure.

My idea is to avoid calling views if json content is already set to response. Actually do we really need to fetch views layer if any content already set to response?

edited Nov '18

Are you referring to default routes mapping, e.g. controller/action defaults?

There is MicroCollection which is great for REST API's.

The only thing Micro lacks is a Dispatcher. But if you structure few things well you can really live w/o it.

Take a look at the link I posted in a previous post.

This is the method I have in my base controller:

protected function outputJSON($what_to_output){
    header('Content-type: text/json');
    echo json_encode($what_to_output);

This thread also has some good ideas: https://forum.phalcon.io/discussion/22/the-best-way-for-json-response-


You can just do:

return $this->response->setJsonContent($responseData);

This is what i do in 99% of cases.