Skip to content

Commit 4b18743

Browse files
Add documentation for StreamedJsonResponse
1 parent 2cc8f4b commit 4b18743

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

components/http_foundation.rst

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,45 @@ represented by a PHP callable instead of a string::
631631

632632
.. _component-http-foundation-serving-files:
633633

634+
Streaming a JSON Response
635+
~~~~~~~~~~~~~~~~~~~~~~~~~
636+
637+
The :class:`Symfony\\Component\\HttpFoundation\\StreamedJsonResponse` class allows
638+
an API to return a lot of data as JSON and keep the used resources low by make usage
639+
of Generators.
640+
641+
It expects a JSON structure with one or multiple replacers identifiers, as example
642+
the `'__articles__'`. As a second argument it requires one or multiple Generators
643+
which items can be converted to a JSON via ``json_encode`` method. The key of the
644+
Generators requires to be the used replacer identifiers.
645+
646+
.. code-block:: php
647+
648+
use Symfony\Component\HttpFoundation\StreamedJsonResponse;
649+
650+
$response = new StreamedJsonResponse(
651+
// json structure with replace identifiers
652+
[
653+
'_embedded' => [
654+
'articles' => '__articles__',
655+
],
656+
],
657+
// array of generators with replace identifier used as key
658+
[
659+
'__articles__' => (function (): \Generator { // any method or function returning a Generator
660+
yield ['title' => 'Article 1'];
661+
yield ['title' => 'Article 2'];
662+
yield ['title' => 'Article 3'];
663+
})(),
664+
]
665+
);
666+
667+
.. tip::
668+
669+
If loading data via doctrine the ``toIterable`` method of ``Doctrine`` can be
670+
used to keep also the resources low and fetch only one row one by one.
671+
See the `Doctrine Batch processing`_ documentation for more.
672+
634673
Serving Files
635674
~~~~~~~~~~~~~
636675

@@ -866,3 +905,4 @@ Learn More
866905
.. _`JSON Hijacking`: https://haacked.com/archive/2009/06/25/json-hijacking.aspx/
867906
.. _OWASP guidelines: https://cheatsheetseries.owasp.org/cheatsheets/AJAX_Security_Cheat_Sheet.html#always-return-json-with-an-object-on-the-outside
868907
.. _RFC 8674: https://tools.ietf.org/html/rfc8674
908+
.. _Doctrine Batch processing: https://www.doctrine-project.org/projects/doctrine-orm/en/2.13/reference/batch-processing.html#iterating-results

0 commit comments

Comments
 (0)