For complicated and unpleasant reasons[*], I want to embed entity data from the JSONAPI module inside JSON returned from a REST module resource.
I am trying to do this by making an HTTP subrequest to the JSONAPI module route within the REST module resource class.
Like this:
$kernel = \Drupal::service('http_kernel');
$current_request = \Drupal::request();
$request = Request::create('/jsonapi/paragraph/' . $paragraph->bundle() . '/' . $paragraph->uuid->value);
$request->setSession($current_request->getSession());
$response = $kernel->handle($request, HttpKernelInterface::SUB_REQUEST);
$json = $response->getContent();
$data = json_decode($json, TRUE);
I get the data I want and it's great!
However, the main request to the REST resource endpoint crashes with this:
Symfony\Component\Serializer\Exception\NotEncodableValueException: Serialization for the format "api_json" is not supported. in Symfony\Component\Serializer\Serializer->serialize() (line 112 of /var/www/vendor/symfony/serializer/Serializer.php).
This is because in Drupal\rest\EventSubscriber\ResourceResponseSubscriber->getResponseFormat(), $route = $route_match->getRouteObject();
is the JSONAPI module route from the subrequest, and not the route from the main request.
What am I doing wrong with my subrequest?
[*] Enormous amount of custom code powering a REST resource for a decoupled front end. I want to change it to using JSONAPI but it's a massive change with huge repercussions on the frontend. To change over incrementally to JSONAPI, I want to switch some paragraph types to the JSONAPI format. Could call the JSONAPI module's PHP code directly, but that's not a public API and so future versions of Drupal could break it. Making a subrequest is using the API and so more maintainable.