Search code examples
symfonyfosrestbundle

FOSRestBundle how to return a JsonResponse


There is a lot of topic on this but none of the answer I found worked for me.

I want to use the FOSRestBundle to build an API returning JSON (for now, I will maybe add XML in the future).

When I make a request to my route, I have the following exception :

[
   {
       message: "Unable to find template "".",
       class: "InvalidArgumentException",
   ...

I have a controller with a route built dynamically. I configured the json format and I return a View with an array of data to serialize in json. Without using FOSRestBundle, I would have returned a JSONResponse and be done with it but as I said, I will eventually add others formats in the future so I would like to do things the right way.

This is my route :

categories:
    type: rest
    resource: Certiz\Bundle\ExamBundle\Controller\CategoryController
    prefix: /api
    requirements:
        _format: "json"

I request the following route : /api/categories

My config.yml :

fos_rest:
view:
    formats:
        json: true
        xml: false
        html: false
        rss: false
    templating_formats:
        json: true
        xml: false
        html: false
        rss: false
    view_response_listener: 'force'
routing_loader:
    default_format: json
    include_format: true
exception:
    codes:
        'Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException': 401
    messages:
        'Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException': true

jms_serializer:
    metadata:
        directories:
            exam:
                namespace_prefix: "Certiz\\Bundle\\ExamBundle"
                path: "@CertizExamBundle/Resources/config/serializer"

And my controller :

public function getCategoriesAction()
{
    $categories = $this
        ->getDoctrine()
        ->getManager()
        ->getRepository('Certiz\Bundle\ExamBundle\Entity\Category')
        ->getTree();

    return View::create()
        ->setStatusCode(200)
        ->setData($categories)
   ;
} // "get_categories" [GET] /categories

I use symfony 2.5 with FOSRestBundle 1.4.2.

Regards


Solution

  • I found what was wrong. In my fos_rest config.yml, I said that the response for json format should be manage by the template engine instead of the serializer.

    I changed my configuration to :

    fos_rest:
        view:
            templating_formats:
                json: false