Introducing “Unit” Types in GraphQL

Joseph Weidinger
2 min readOct 28, 2019
Photo by William Warby on Unsplash

“Units” is an experimental library for enriching GraphQL schemas with a comprehensive suite of unit-related types. Source code and additional details are located here!

These types allow you to express a unit of measurement within your API without specifying a particular system. This allows API consumers to request values in their local system, e.g Metric or Imperial.

Consider an API which provides flight details. Data types might contain fields denoted in specific units:

Although each field of type Float is a completely unrelated unit, there is no way to know without referring to documentation. Moreover, if we choose the wrong units for our clients, they would manually need to perform conversions.

The nested nature of GraphQL provides the flexibility needed to solve these problems; fields which terminate with object types instead of scalars enable far greater expressiveness:

Here’s the Output type for volume up close:

How can we use Output types in our queries?

Getting Started

First, import the types exported by “Units” into your schema. See our GitHub repository for more details.

Output Types

Set the return value of any field to be the kind of unit you want to use, e.g. DurationOutput, DistanceOutput, etc.

The resolver for the field should return an object with amounts in whatever unit you have to work with. For example, if one of your fields is a DistanceOutput, its resolver might look like this:

The built-in resolvers for DistanceOutput will automatically perform conversions and rounding for you:

Input Types

In addition to Output types, Units provides a similar set of Input types.

Let’s expand our flight info API from earlier to allow for mutations:

Here’s an example of Input types in action:

Whatever the user provides, e.g. { gallons: 6 }, is passed to your resolver:

There is a playground in our repository which demonstrates almost every feature, check it out!

Further Development

We’re marketing this as “experimental” to allow for breaking changes as we work toward a rock-solid set of types. In addition to using it within our projects, we’re also interested in collecting usage-driven feedback wherever possible. Let us know what you think!

Finally, “we” are Joseph Weidinger and Conner Ruhl. We publish GraphQL related-tools and experiments under Graph Engineering.

Special thanks to Conner who provided the initial idea and code for what would become this library. He also helped guide me in designing this API and even writing this article. Thanks again!



Joseph Weidinger

software engineer, music producer, amateur interviewer, pizza dough roller, class clown, boring uncle. More at