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 tge JSONAPI module route within the REST module resource class.
$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 request to the REST resource endpoint crashes with this:
SymfonyComponentSerializerExceptionNotEncodableValueException: Serialization for the format “api_json” is not supported. in SymfonyComponentSerializerSerializer->serialize() (line 112 of /var/www/vendor/symfony/serializer/Serializer.php).
This is because in DrupalrestEventSubscriberResourceResponseSubscriber->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. Changing over gradually to JSONAPI by switching 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.