Nuno Barreto
Nuno Barreto

Reputation: 121

Proper way to use Accept header in a REST api made with Symfony2 and FOSRestBundle

I am trying to make my web services return the right format when sent with an Accept header. For example, if I send 'Accept: application/xml', it should return in xml format, and if I send 'Accept: application/json', should return in json format.

This works fine if I put the extension. http://example.com/api/users.json returns json, and http://example.com/api/users.xml returns XML. But if I don't put extensions, it returns always json, totally ignoring the Accept header.

How can I setup it in a way that when there is no extension, it returns whatever is asked on the Accept header?

My config file:

fos_rest:
    format_listener: true
    routing_loader:
        default_format: json
    view:
        view_response_listener: 'force'
        formats:
            json: true
            xml: true
        templating_formats:
            html: true
    serializer:
        serialize_null: true

sensio_framework_extra:
    view:       { annotations: false }
    router:     { annotations: true }

Also tried this:

format_listener:
    rules:
        - prefer_extension: false

The result was an error:

Unable to find template "WhateverBundle:Users:getUsers.html.twig"

Upvotes: 3

Views: 952

Answers (1)

Nuno Barreto
Nuno Barreto

Reputation: 121

I was able to do what I wanted with this:

fos_rest:
    format_listener:
        rules:
            - priorities: [ json, xml, html ]
            - prefer_extension: false
    routing_loader:
        default_format: json
    view:
        view_response_listener: 'force'
        formats:
            json: true
            xml: true
        templating_formats:
            html: true
    serializer:
        serialize_null: true

For some reason just having the prefer_extension config in format_listener is not enough.

Upvotes: 2

Related Questions