@@ -585,6 +585,45 @@ represented by a PHP callable instead of a string::
585585
586586.. _component-http-foundation-serving-files :
587587
588+ Streaming a JSON Response
589+ ~~~~~~~~~~~~~~~~~~~~~~~~~
590+
591+ The :class: `Symfony\\ Component\\ HttpFoundation\\ StreamedJsonResponse ` class allows
592+ an API to return a lot of data as JSON and keep the used resources low by make usage
593+ of Generators.
594+
595+ It expects a JSON structure with one or multiple replacers identifiers, as example
596+ the `'__articles__' `. As a second argument it requires one or multiple Generators
597+ which items can be converted to a JSON via ``json_encode `` method. The key of the
598+ Generators requires to be the used replacer identifiers.
599+
600+ .. code-block :: php
601+
602+ use Symfony\Component\HttpFoundation\StreamedJsonResponse;
603+
604+ $response = new StreamedJsonResponse(
605+ // json structure with replace identifiers
606+ [
607+ '_embedded' => [
608+ 'articles' => '__articles__',
609+ ],
610+ ],
611+ // array of generators with replace identifier used as key
612+ [
613+ '__articles__' => (function (): \Generator { // any method or function returning a Generator
614+ yield ['title' => 'Article 1'];
615+ yield ['title' => 'Article 2'];
616+ yield ['title' => 'Article 3'];
617+ })(),
618+ ]
619+ );
620+
621+ .. tip ::
622+
623+ If loading data via doctrine the ``toIterable `` method of ``Doctrine `` can be
624+ used to keep also the resources low and fetch only one row one by one.
625+ See the `Doctrine Batch processing `_ documentation for more.
626+
588627Serving Files
589628~~~~~~~~~~~~~
590629
@@ -823,3 +862,4 @@ Learn More
823862.. _`JSON Hijacking` : https://haacked.com/archive/2009/06/25/json-hijacking.aspx/
824863.. _OWASP guidelines : https://cheatsheetseries.owasp.org/cheatsheets/AJAX_Security_Cheat_Sheet.html#always-return-json-with-an-object-on-the-outside
825864.. _RFC 8674 : https://tools.ietf.org/html/rfc8674
865+ .. _Doctrine Batch processing : https://www.doctrine-project.org/projects/doctrine-orm/en/2.13/reference/batch-processing.html#iterating-results
0 commit comments