user2733521
user2733521

Reputation: 449

Symfony2 FOSRestBundle overrides default application

I'm using FOSRestBundle to manage my api. I already have a running sf2 application, and i want to allow third person to access some of my application features. I configured my api, and it works as expected, i can consume my api route with success for example :

GET http://my.domain.ldt/api/v1/users

My Api only handle json format, here is my fos_rest configuration :

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'
        exception_wrapper_handler: My\ApiBundle\Handlers\ApiExceptionWrapperHandler
        formats:
            json : true
        failed_validation: HTTP_BAD_REQUEST
        templating_formats:
            html: false
            xml: false
    routing_loader:
        default_format: json
        include_format: false
    exception:
        enabled: true
    service:
        view_handler: my.view_handler

services:
    my.json_handler:
       class: My\ApiBundle\Handlers\JsonHandler      

    my.view_handler:
       parent: fos_rest.view_handler.default
       calls:
        - ['registerHandler', [ 'json', ["@my.json_handler", 'createResponse'] ] ]

As i said, my Api works well, but i face a major problem : When i try to access to the main application from my web browser, ( http://my.domain.ldt/, or http://my.domain.ldt/login), i get the following response instead of my classic web page :

An Exception was thrown while handling: No matching accepted Response format could be determined

Why my fos_rest conf applies on my main website ? Is it possible to only set the api conf for the api routes ? Did i miss something ?

Upvotes: 1

Views: 447

Answers (1)

Guilhem N
Guilhem N

Reputation: 218

The problem is that you forgot to define rules for FOSRestBundle's format listener.

In fact I'm not sure you need this listener as it seems you use json as the default format. The format listener will try to match the Accept header and extract the current request format based on it. So except if you want to support other formats than json for your api, you can just not use it.

In case you want to fix it instead of removing it, you have to update your config with something like:

fos_rest:
    format_listener:
        enabled: true
        rules:
            - { path: '^/', priorities: ['json', 'xml', 'html], fallback_format: 'json' }

Of course you can change this rule to have a different rule for your api:

fos_rest:
    format_listener:
        enabled: true
        rules:
            - { path: '^/api', fallback_format: 'json' }
            - { path: '^/', fallback_format: 'html' }

Upvotes: 2

Related Questions