0

I'm working on a REST API using the FOSRestBundle and I'd like to be able to use the same URL for returning HTML and JSON depending on the request Accept header; i.e. if you call the URL directly from a browser (Accept : text/html etc) HTML is returned from a twig file, if you are making an AJAX request (Accept : application/JSON etc), JSON is returned using the FOSRestBundle.

Currently I can get this to work by throwing a small if statement at the top of each function to check the request accept header, if it's asking for HTML it returns the twig file, if it's asking for JSON it hits the service.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
greg
  • 6,853
  • 15
  • 58
  • 71

2 Answers2

1

You should rather send "Accept" header with your requests. Read content negotiation (“Accept” HTTP header) based routing in symfony2.0 and Format listener.

Community
  • 1
  • 1
Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
  • Thanks for the response, no problem using the accept header but I still can't work out how to route to a different controller based on the header. Currently I'm using the one controller to determine the type then either returning a twig template or hitting my service and returning JSON. It works but it means repeating the same if statement inside every single service, which isn't really ideal. – greg Jun 12 '12 at 17:20
0

The request scope does not exist when run in command line mode, I had to remove request from each constructor and the problem disappeared.

greg
  • 6,853
  • 15
  • 58
  • 71