Question

My goal is to have a default json output when the user agent is set to anything else than json or xml. I have configured FOSRestBundle 1.1.0 as follows:

fos_rest:
format_listener: true
param_fetcher_listener: true
view:
    default_engine: php
    formats:
        json: true
        xml: true
    templating_formats:
        html: false
    view_response_listener: force
routing_loader:
    default_format: json

This works. Now I added the following configuration:

format_listener:
    rules:
        - { fallback_format: json, prefer_extension: false, priorities: ['xml', 'json'] }

As soon as I do that, I can no longer switch between formats by either appending ?_format=json or ?_format=xml and also the Accept header seems to be ignored, it always uses whatever I specify in the accept header.

How to configure FOSRestBundle so that it accepts json or XML via Parameter/HTTP Request header and falls back to json if the format accepted by the browser is HTML?

Was it helpful?

Solution

According to the FOSRestBundle Docs:

Note that if _format is matched inside the route, then a virtual Accept header setting is added with a q setting one lower than the lowest Accept header, meaning that format is checked for a match in the priorities last. If prefer_extension is set to true then the virtual Accept header will be one higher than the highest q causing the extension to be checked first. Setting priorities to a non empty array enables Accept header negotiations.

Also, I noticed that in the rules section, you are missing the path option. So the application doesn't know which path to apply the rules to.

Take a look at the docs I linked to above, it has an example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top