How can I serve HTML and JSON requests from the same route using Symfony 2 and FOSRestBundle using headers in addition to _format?

I try to serve content in both formats htmland json(I also want to eventually resolve xml) using Symfony and FOSRestBundle (version 1.3). I managed to use different content for the routes using a parameter _format, for example:

  • /foo.json will lead to a JSON response,
  • and /foowill produce an HTML response.

Is there a way to put together (on the same host!) The same content matching using something other than _format, for example, headers Content-Typeor Accept?

I looked at the Format Listener , but I think I have a fundamental misunderstanding of how to configure it.


The specified route:

<route id="foo" pattern="/foo.{_format}" methods="GET">
    <default key="_controller">FooBundle:Foo:get</default>
    <default key="_format">html</default>
</route>

... for the following action:

public function getAction(Request $request)
{
    $view = View::create()
        ->setData(array('greeting' => 'hello world'))
        ->setFormat($request->getRequestFormat('html'))
        ->setTemplate('FooBundle:Foo:get.html.twig');
    return $this->get('fos_rest.view_handler')->handle($view);
}

... and the following FOSRestBundle configuration (snippet):

fos_rest:
  ...
  format_listener: true

I need to specify a parameter _formatin the request if I want consistent content in a format other than the default ( html), as indicated above.

However, if I set the following rules for the format listener:

fos_rest:
  format_listener:
    rules:
      - { path: '^/', priorities: ['json'], fallback_format: ~, prefer_extension: false }
      - { path: '^/', priorities: ['html', '*/*'], fallback_format: html, prefer_extension: true }

The browser request returns my answers as Content-Type: application/json, but the actual content is this text/html, not serialized JSON. If I explicitly specify the header Accept, although in the request, the Accept: text/htmlresponse I receive has a header of the content type Content-Type: text/html.

Any help would be greatly appreciated!

+4
1

Content-type, BodyListener FormatListener. .

+1

Source: https://habr.com/ru/post/1548259/


All Articles