Problem/Motivation
- When retrieving an entity in json format (e.g.,
/node/1?_format=json
), all entity fields that the user has permission to view are returned, including the local ID (nid
for node entities) and revision ID (vid
for node entities) fields. - When retrieving an entity in hal+json format (e.g.,
/node/1?_format=hal_json
), the local ID and revision fields are excluded. The code that performs this exclusion is$exclude = array($entity->getEntityType()->getKey('id'), $entity->getEntityType()->getKey('revision'));
inDrupal\hal\Normalizer\ContentEntityNormalizer
. - The decision to exclude the local ID was made in the initial patch that added hal.module (#1924220: Support serialization in hal+json) with no clear explanation as to why. Perhaps it was believed that too many identifiers would be confusing and lead to misuse. For most use cases, the entity's URI and UUID are more reliable and semantically meaningful identifiers.
- The decision to exclude the revision ID was made in #2219795: Config entity references broken and other bugs also without a clear explanation as to why. Perhaps it was believed that because revision IDs are also local (rather than UUIDs), that if one is excluded, then so should the other one.
- However, there are use cases where you need the local ID. For example, suppose you have a View with a contextual filter (e.g., core provides several such as
taxonomy/term/{tid}
and/admin/content/files/usage/{fid}
). Given a term or file, a JS application may want to output a link to one of these Views, contextually filtered to that term or file. It currently has no way to do so, since neither the term or file's URI, nor its UUID can be used as the value within such a link. - There are also use cases where you need the revision ID. An Entity ID is not enough to know what state of the original entity was captured; as an API consumer you need to be able to identify when a revision switches. There's no revision UUID stored in Drupal's entity schema, so the revision ID is the only revision identifier available.
Proposed resolution
Revert the mentioned change from #3 that is remove the excludes thus adding the id and revision to the normal state properties as mentioned in #9
<?php
$exclude = array($entity->getEntityType()->getKey('id'), $entity->getEntityType()->getKey('revision'));
?>
Remaining tasks
User interface changes
API changes
Original report by @webchick
I suppose this might be "by design" but I hope it's merely an oversight. :)
When you look at the hal+json output of a node, "nid" is not one of the top-level keys. In fact, the only way to get a node's nid seems to be by doing horrific string parsing on [_links][_self]. Yet, this seems like a really useful key, for example to construct a link to a node from a mobile app.