Error when get rest resource : The controller result claims to be providing relevant cache metadata I try to create a REST resource. I used EntityResource as base. I would like to return my fields in html.
Here is a exemple of my code :  

public function get($id) {
    if (!$this-&gt;currentUser-&gt;hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }

    $entity = \Drupal::entityTypeManager()-&gt;getStorage('node')-&gt;load($id);
    $entity_access = $entity-&gt;access('view', NULL, TRUE);
    if (!$entity_access-&gt;isAllowed()) {
      throw new AccessDeniedHttpException($entity_access-&gt;getReason() ? : $this-&gt;generateFallbackAccessDeniedMessage($entity, 'view'));
    }

    $result = array();
    $other_entity_dependency = array();
    if ($entity instanceof FieldableEntityInterface) {
      $fields = array();
      $contentType = $entity-&gt;bundle();
      if (isset($contentType) &amp;&amp; !empty($contentType)) {
        foreach (\Drupal::entityManager()-&gt;getFieldDefinitions('node', $contentType) as $field_name =&gt; $field_definition) {
          if (!empty($field_definition-&gt;getTargetBundle())) {
            $fields[] = $field_name;
          }
        }
      }
      foreach ($fields as $field_name) {
        $field = $entity-&gt;$field_name;
        $field_access = $field-&gt;access('view', NULL, TRUE);
        if ($field_access-&gt;isAllowed()) {
           $value = \Drupal::service('renderer')-&gt;render($field-&gt;view())
           $result[$field_name]['value'] = $value;
            $result[$field_name]['label'] = $field-&gt;getFieldDefinition()-&gt;getLabel();

        }
      }
    }


    $response = new ResourceResponse($result, Response::HTTP_OK);
    $response-&gt;addCacheableDependency($entity);
    $response-&gt;addCacheableDependency($entity_access);

      return $response;
  }


The problem is that when I use a render function, I have this error : 


  The controller result claims to be providing relevant cache metadata,
  but leaked metadata was detected. Please ensure you are not rendering
  content too early. Returned object class:
  Drupal\rest\ResourceResponse.


I haven't this issue when I use $field-&gt;value instead of \Drupal::service('renderer')-&gt;render($field-&gt;view()), but I would like to have the html render of fields, for file or image too (these types of fields are empty when I use $field-&gt;value). 

How can I solve this problem ?
The problem is, that render() produces metadata which leaks to the outside of the controller. You can try renderPlain() if you don't care about the metadata or see this question how to provide your own render context to catch the metadata and add it to the response:

How to get cache metadata from nested render array when returning response?