Search code examples
phprestsymfonyfosrestbundle

Routes not working in FOSRestBundle and Symfony


I've been going round in circles with this one. I've been either getting 500 errors saying template cannot be rendered or found, or when I attempt to use the annotations, they clash with the fact I'm using Symfony's annotations for my routes. With the current code, I'm just getting 404's.

My config:

# config.yml
fos_rest:
routing_loader:
    default_format: json

An example of my controller:

namespace IGIG\GigBundle\Controller;

use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Route;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

use IGIG\GigBundle\Document\Gig;

class GigApiController extends FOSRestController
{
    public function getGigsAction()
    {
        $gigs = $this->get('doctrine_mongodb')
                     ->getRepository('IGIGGigBundle:Gig')
                     ->findAll();

        $view = $this->view($gigs, 200)
            ->setTemplate("IGIG:GigBundle:getGigs.html.twig")
            ->setTemplateVar('gigs');

        return $this->handleView($view);
    }
 }

Routing

gigs:    
  prefix: /api   
  type: rest    
  resource: IGIG\GigBundle\Controller\GigApiController

I should also add, the .html.twig file within the controller doesn't actually exist, I was under the impression that it was automatically generated, is that the case?

Thanks in advance!


Solution

  • First of all it looks like your config is not indented properly, but might also just be a copy/paste error, otherwise it should throw an exception for you.

    # config.yml
    fos_rest:
        routing_loader:
            default_format: json
    

    I should also add, the .html.twig file within the controller doesn't actually exist, I was under the impression that it was automatically generated, is that the case?

    No, you do need to generate that template file yourself and that is probably the cause for your 500 errors. However if you don't intend to use twig templates next to your REST API, so if you ever only want to return JSON responses, then you won't need them at all and can remove the calls from your controller too.

    For your 404's: do a ./app/console router:debug | grep api and see if the generated routes are like what you expect.

    You should have a look at the bundle documentation again, in particular the full config reference: https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/configuration-reference.md

    And I found this very helpful too when starting out with REST APIs with Symfony: http://welcometothebundle.com/symfony2-rest-api-the-best-2013-way/