antanas_sepikas
antanas_sepikas

Reputation: 5704

Symfony2 FOSRestBundle solely json

I started working with FOSRestBundle building restful api. I wan't to make code as simple and clear as possible. I will use api only for json responses (No templates). Now I saw "@View" annotation which is quite nice and when using it return statement becomes as simple as returning "$data" object

//http://symfony.com/doc/current/bundles/FOSRestBundle/3-listener-support.html 
/**
 * @View()
 */
public function getUsersAction()
{
    return $data;
}

But this requires me to create template, and I don't realy need nor wan't to that.

What would be nice if I could just simply return any $data (or at least array) and it would be automatically formatted into json response. Is that possible if so what configuration of this setup might look like?

Upvotes: 0

Views: 199

Answers (2)

Rahul
Rahul

Reputation: 2279

yes it's possible to return response as JSON with FOSRestBundle. For that you can set config options like this:

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'
        formats:
            xml:  true
            json: true
        templating_formats:
            html: true
    format_listener:
        rules:
            - { path: ^/, priorities: [ json, xml, html ], fallback_format: ~, prefer_extension: true }

Note in above code view_response_listener is set to 'force'.

and in your controller you can send data as JSON response by creating $view object as follows

$view = View::create();

$view->setFormat('json');

$view->setStatusCode(200)->setData($data); 

return $this->get('fos_rest.view_handler')->handle($view);

Upvotes: 0

Esiable
Esiable

Reputation: 1

"When view_response_listener is set to true instead of force and @View() is not used, then rendering will be delegated to SensioFrameworkExtraBundle."

You need to set annotations to false in SensioFrameworkExtraBundle:

sensio_framework_extra:
view:    { annotations: false }

and

fos_rest:
view:
    view_response_listener: force

You can look at this example https://github.com/liip/LiipHelloBundle/blob/master/Controller/ExtraController.php

Upvotes: 0

Related Questions