12

I am trying to use Symfony2 and FOSRestBundle to come up with a REST framework and I am failing miserably.

I have done the following:

in my deps file:

[FOSRest]
    git=git://github.com/FriendsOfSymfony/FOSRest.git
    target=fos/FOS/Rest

[FOSRestBundle]
    git=git://github.com/FriendsOfSymfony/FOSRestBundle.git
    target=bundles/FOS/RestBundle

[JMSSerializerBundle]
    git=git://github.com/schmittjoh/JMSSerializerBundle.git
    target=bundles/JMS/SerializerBundle

In my apps/config.yml

fos_rest:
    view:
        formats:
            rss: true
            xml: false
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig


sensio_framework_extra:
    view:
        annotations: false

In my Controller:

namespace Rest\WebServiceBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;  


class DefaultController extends Controller
{

    public function indexAction($name)
    {


  $view = View::create()
          ->setStatusCode(200)
          ->setData($name);
        return $this->get('fos_rest.view_handler')->handle($view);


    }
}

When I go to the URL: http://local.symfony.com/web/app_dev.php/hello/test

I get:

Unable to find template "".
500 Internal Server Error - InvalidArgumentException
2 linked Exceptions: Twig_Error_Loader ยป Twig_Error_Loader

The documentation seems confusing to me and I am unable to continue. All I want is to be able to pass an array of data to the controller and get back a JSON format. Can someone help?

Strong Like Bull
  • 11,155
  • 36
  • 98
  • 169
  • 4
    I'm also having trouble getting this going. It seems quite confusing for what seems like a relatively simple task. Have you had any luck with it? โ€“ greg Jun 04 '12 at 22:02

1 Answers1

18

In formats section of config.yml you have to enable json format and disable other formats and set default _format value as json in route. e.g

# app/config/config.yml
fos_rest:
    view:
        formats:
            json: true
            rss: false # removing them will also work
            xml: false
#.......

#bundle/routing.yml
route_name:
  pattern: /route
  defaults: { _controller: Bundle:Controller:Method, _format:json }

Or, in controller you can do

$view->setFormat('json');

Also checkout the example links given in the documentation.

Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
  • 3
    It worked for me too, but only when i use an array as data, what if i want to output an object? โ€“ alex88 Jul 09 '12 at 10:34
  • 1
    Doesn't work with the newer versions. A more recent answer: http://stackoverflow.com/a/18035437/842697. The comments are very interesants. โ€“ Brais Gabin Aug 27 '13 at 14:44