Member-only story

The Typed Data API, by example

Matt Glaman
3 min readDec 31, 2021

There is a fantastic low-level API in Drupal called the Typed Data API. It is fantastic and provides a great way to handle data representation via a schema and validate that data’s values. The Typed Data API is the foundation for the Entity API. Entities are composed of fields that are composed of properties, and each step is tied into the Typed Data API.

The Typed Data API was created to provide developers with a consistent way of interacting with data differently.

The Typed Data API integrates with the Validator component from Symfony. This allows us to apply constraints and validators to data type values and ensure they’re valid. This is how content entity validation works. And, the beautiful part is that it can be used anywhere, especially when validating payloads to custom API endpoints. The Serialization module in Drupal core connects the Typed Data API into the Serializer component from Symfony. This allows us to seamlessly convert a timestamp into ISO8601 by having the correct data definition.

$definition = DataDefinition::create('timestamp');
$timestamp = $typed_data_manager->create($definition, 1640639271);

// Output: 1640639271
$timestamp->getValue();

// Gets a DateTime object, available for this data type class.
$timestamp->getDateTime();

// Output: 2021-12-27T21:07:51+00:00
$serializer->normalize($timestamp, 'json');

// Output: "2021-12-27T21:07:51+00:00"
$serializer->serialize($timestamp, 'json');

--

--

Matt Glaman
Matt Glaman

Written by Matt Glaman

PHP software engineer, open source contributor, and speaker

No responses yet