Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added the json() shortcut to the controller chapter #6502

Closed
wants to merge 10 commits into from
27 changes: 24 additions & 3 deletions book/controller.rst
Original file line number Diff line number Diff line change
Expand Up @@ -762,9 +762,9 @@ headers and content that's sent back to the client::
// create a simple Response with a 200 status code (the default)
$response = new Response('Hello '.$name, Response::HTTP_OK);

// create a JSON-response with a 200 status code
$response = new Response(json_encode(array('name' => $name)));
$response->headers->set('Content-Type', 'application/json');
// create a CSS-response with a 200 status code
$response = new Response('<style> ... </style>');
$response->headers->set('Content-Type', 'text/css');

There are also special classes to make certain kinds of responses easier:

Expand All @@ -778,6 +778,27 @@ There are also special classes to make certain kinds of responses easier:
:class:`Symfony\\Component\\HttpFoundation\\StreamedResponse`.
See :ref:`streaming-response`.

JSON Helper
~~~~~~~~~~~

Returning JSON contents is increasingly popular for API-based applications. For
that reason, the base controller class defines a ``json()`` method which creates
a ``JsonResponse`` and encodes the given contents automatically::

// ...
public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));

// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}

If the :doc:`serializer service </cookbook/serializer>` is enabled in your
application, contents passed to ``json()`` are encoded with it. Otherwise,
the :phpfunction:`json_encode()` function is used.

.. seealso::

Now that you know the basics you can continue your research on Symfony
Expand Down