greg
greg

Reputation: 6913

Using http request headers with Symfony routing to return different content (html / json)

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.

Upvotes: 0

Views: 3451

Answers (2)

greg
greg

Reputation: 6913

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

Upvotes: 0

Jakub Zalas
Jakub Zalas

Reputation: 36191

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

Upvotes: 1

Related Questions