Strong Like Bull
Strong Like Bull

Reputation: 11297

FosRestbundle keeps sending text/html as response and we are expecting json.

Here is our controller:

function getLocationsAction(Request $request) {

        $dm = $this->get('doctrine.odm.mongodb.document_manager');
        $query = $dm->createQueryBuilder('MainClassifiedBundle:Location')->select('name', 'state', 'country', 'coordinates');
        $locations = $query->getQuery()->execute();

        $data = array(
            'success' => true,
            'locations' => $locations,
            'displaymessage' => $locations->count() . " Locations Found"
        );

        $view = View::create()->setStatusCode(200)->setData($data);
        return $this->get('fos_rest.view_handler')->handle($view);
    }

Here is the config.yml for fosrestbundle:

fos_rest:
    view:
        formats:
            json: true
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig

Here is the route:

MainClassifiedBundle_get_locations:
    pattern:  /locations/
    defaults: { _controller: MainClassifiedBundle:ClassifiedCrudWebService:getLocations, _format:json}
    requirements:
        _method:  GET

Why are we getting text/html ? Ho wcan we force the response to be application/json?

Please help as this is causing huge pains at the moment

Upvotes: 4

Views: 5096

Answers (2)

ShaneMit
ShaneMit

Reputation: 191

Or if you cant rely on the $_format (in my case) you can explicitly set the format like so:

    public function createAction(Request $request): Response
{
    // ...

    return $this->viewHandler->handle(View::create($json)->setFormat('json'));
}

Upvotes: 0

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52483

You are creating your view statically and have not enabled any listeners.

This way there is no format guessing involved.

Pass the format as argument to your function and set the format on the View object:

function getLocationsAction(Request $request, $_format) {
{
    // ...
    $view = View::create()
         ->setStatusCode(200)
         ->setData($data)
         ->setFormat($_format)   // <- format here
    ;
    return $this->get('fos_rest.view_handler')->handle($view);
}

See the documentation chapter The View Layer.


If you want automatic format guessing you have to enable the listeners.

fos_rest:
    param_fetcher_listener: true
    body_listener: true
    format_listener: true
    view:
        view_response_listener: 'force'

Read more in the chapter Listener Support.

Upvotes: 12

Related Questions