Symfony2 + FOSRestBundle: Enable/disable REST functionality per controller/action?

Jeff Maes picture Jeff Maes · Aug 9, 2012 · Viewed 7.6k times · Source

A part of my application will be available as an API, so some of my pages needs to be available in JSON or XML (based on the Accept header 'Content Type').

I've used the FOSRestBundle and it works very well, but now ALL my pages are available in XML (or JSON) when sending Accept header 'Content Type: application/xml'.

So, I would like to enable/disable this functionality for some of my controllers/actions. I would be ideal to do this using annotations.

Is that possible?

My config.yml:

fos_rest:
    view:
        formats:
            rss: false
            xml: true 
            json: true
        templating_formats:
            html: true
        force_redirects:
            html: false
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig
        view_response_listener: force
    body_listener:
        decoders:
            json: acme.decoder.json
            xml: fos_rest.decoder.xml
    format_listener:
        default_priorities: ['html', 'xml', 'json', '*/*']
        fallback_format: html
        prefer_extension: false    

Answer

William Durand picture William Durand · Aug 16, 2012

According to the RestBundle's documentation, you won't get an XML output if you don't use a View in your controller. So, if you don't use the @View annotation, or a View::create() in your action, and you return a classic response, you will get a HTML output.

If you want to force the format for some reasons, you can turn the prefer_extension to true and adjust the routing definition:

my_route:
    pattern:  /my-route
    defaults: { _controller: AcmeDemoBundle:action, _format: <format> }

Where <format> is the format you want to force.