This week I was working on a Drupal 8 project that includes a page that uses Drupal as a simple proxy to convert a weak XML API into a simple JSON response the browser is willing to accept.
When I first built the site I hadn’t yet gotten my head around Drupal 8 caching, and so the JSON responses weren’t cached and therefore the page was slow. After some issues with the site caused me to have to look at this part of the project again I decided it was time to try to do something about this.
Drupal 8’s use of symfony means we have great access to tools for things like providing JSON responses. Originally in the controller all I had to do was provide the JSONResponse class an array of data and it would handle the rest:
That’s all well and good if you don’t want your response to ever be cached, but Drupal provides a CacheableJsonResponse class the links up to the rest of the Drupal 8 caching engine to provide much better performance. But it turns out the docs kinda suck for explaining how to use it. After a great deal of digging I found this Question on StackExchange which gave me what I needed.